Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can rewrite your procedural logic with <strong>pure SQL</strong> in a <em>single</em> SQL statement using <a href="http://www.postgresql.org/docs/current/interactive/queries-with.html#QUERIES-WITH-MODIFYING" rel="nofollow noreferrer">data-modifying CTEs</a>.</p> <pre><code>WITH usr1 AS (SELECT id FROM users WHERE mongoid = $1) , usr2 AS ( INSERT INTO users (mongoid, shopid, idinshop, attributes) SELECT $1, $2, $3, $4 WHERE NOT EXISTS (SELECT 1 FROM usr1) RETURNING id ) , ses1 AS (SELECT id FROM sessions WHERE mongoid = $5) , ses2 AS ( INSERT INTO sessions (mongoid, shopid, userid, session, traffic, counts) SELECT $5, $2, (SELECT id FROM usr1 NATURAL FULL OUTER JOIN usr2 , $6, $7, $8 WHERE NOT EXISTS (SELECT 1 FROM ses1) RETURNING id ) INSERT INTO events (shopid, sessionid, userid, type, attributes, mongoid) VALUES ($2 , (SELECT id FROM usr1 NATURAL FULL OUTER JOIN usr2) , (SELECT id FROM ses1 NATURAL FULL OUTER JOIN ses2) , $9, $10, $11); </code></pre> <p>Requires Postgres <strong>9.1</strong> or later.<br> Untested. Provide a test case in your question if you want tested answers.</p> <p>Should be considerably faster than individual commands (<a href="https://stackoverflow.com/questions/7510092/which-is-better-performing-calculations-in-sql-or-in-your-application/7518619#7518619">let alone repeated round trips to the db server!</a>).</p> <p>Be aware of <strong>potential concurrency issues</strong> with heavy concurrent load. The single statement presented is already <em>much</em> less likely to cause trouble. But the possibility is there. Possible solutions include <a href="http://www.postgresql.org/docs/current/interactive/explicit-locking.html#LOCKING-TABLES" rel="nofollow noreferrer">manual locking</a> (expensive) <a href="http://www.postgresql.org/docs/current/interactive/explicit-locking.html#ADVISORY-LOCKS" rel="nofollow noreferrer">advisory locks</a> or <a href="http://www.postgresql.org/docs/current/interactive/applevel-consistency.html#SERIALIZABLE-CONSISTENCY" rel="nofollow noreferrer">serializable transactions</a> (may be expensive, too).</p> <p>Related answer with more information:<br> <a href="https://stackoverflow.com/questions/11890599/postgresql-batch-insert-or-ignore/11892007#11892007">Postgresql batch insert or ignore</a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload