title: Return ID of newly inserted row on a PostgreSQL database using C# and Npgsql?
body: <p>I'm building a WinForms project in C# using a PostgreSQL database and the Npgsql framework.</p>
  
  <p>For inserting a record, I need to return the ID of the new record. <a href="https://stackoverflow.com/questions/18373461/execute-insert-command-and-return-inserted-id-in-sql">This SO question</a> says to add <code>SELECT SCOPE_IDENTITY()</code> to the query string passed to cmd. So my query string looks like this:</p>
  
  <pre><code>string insertString = "INSERT INTO sometable (company_name, category, old_value, old_desc, new_value, new_desc, reference1, reference2) VALUES (@comp, @cat, @oldValue, @oldDesc, @newValue, @newDesc, @ref1, @ref2); SELECT SCOPE_IDENTITY();";
  </code></pre>
  
  <p>and then get the ID with something like</p>
  
  <pre><code>int modified = cmd.ExecuteNonQuery();
  </code></pre>
  
  <p>But that's likely SQL Server-specific. If I use that method, I get an exception at the above line saying, "fuction scope_identity() does not exist".</p>
  
  <p>I wasn't able to find anything that seemed to address this on the <a href="https://www.npgsql.org/doc/index.html" rel="nofollow noreferrer">Npgsql documentation</a>.</p>
  
  <p>Per the linked SO question and Denis' suggestions I've tried adding both</p>
  
  <pre><code>RETURNING id;
  </code></pre>
  
  <p>and </p>
  
  <pre><code>CURRVAL(pg_get_serial_sequence('my_tbl_name','id_col_name'))
  </code></pre>
  
  <p>to the query string, replacing <code>SELECT SCOPE_IDENTITY();</code> with those statements in the code above. In both cases they work as intended in DBeaver on an insert, but in my C# code in my WinForm project, modified was set to "1".</p>
  
  <p>NOTE: I re-titled the question and added more information about what I've done.</p>