Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Option 2 is not going to be the most efficient. The database will already be making this check for you when you do the actual insert or update in order to enforce the primary key. By making this check yourself you are incurring the overhead of a table lookup twice as well as an extra round trip from your Java code. Choose which case is the most likely and code optimistically. </p> <p>Expanding on option 1, you can use a stored procedure to handle the insert/update. This example with PostgreSQL syntax assumes the insert is the normal case.</p> <pre><code>CREATE FUNCTION insert_or_update(_id INTEGER, _col1 INTEGER) RETURNS void AS $$ BEGIN INSERT INTO my_table (id, col1) SELECT _id, _col1; EXCEPTION WHEN unique_violation THEN UPDATE my_table SET col1 = _col1 WHERE id = _id; END; END; $$ LANGUAGE plpgsql; </code></pre> <p>You could also make the update the normal case and then check the number of rows affected by the update statement to determine if the row is actually new and you need to do an insert. </p> <p>As alluded to in some other answers, the most efficient way to handle this operation is in one batch:</p> <ol> <li>Take all of the rows passed to the web service and bulk insert them into a temporary table</li> <li>Update rows in the mater table from the temp table</li> <li>Insert new rows in the master table from the temp table</li> <li>Dispose of the temp table</li> </ol> <p>The type of temporary table to use and most efficient way to manage it will depend on the database you are using.</p>
    singulars
    1. This table or related slice is empty.
    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. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    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