Skip to content

Instantly share code, notes, and snippets.

@fragoulis
Created October 6, 2014 10:11
Show Gist options
  • Save fragoulis/73ce9c34dcde10162454 to your computer and use it in GitHub Desktop.
Save fragoulis/73ce9c34dcde10162454 to your computer and use it in GitHub Desktop.
RDBMS: Generate the next auto increment ID
-----------------------------------------------------------------
-- PostgreSQL
--
SELECT last_value, is_called
FROM :sequence
-- If is_called is false, last_value is 1 and the next ID also 1.
-- If is_called is true, the next ID is last_value + 1
-----------------------------------------------------------------
-- MySQL
--
SELECT AUTO_INCREMENT
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = :database AND TABLE_NAME = :table
-- Returns the next ID
@fragoulis
Copy link
Author

PostgreSQL is a bit trickier but the end is the same.

The above comes in useful when you are handling complex migrations between databases and you need to know the primary keys of rows before hand, put them down in a file and do a simple transactional import.

Another thing that needs some attention is the fact that when you set the value of a sequence related column in PostgreSQL manually, you need to update the sequnce manually as well. Eg. inserting a row in a table with a serial column id and manually setting that id to 5, does not trigger any sequence updates.

Haven't checked if that is the case with MySQL as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment