Created
October 6, 2014 10:11
-
-
Save fragoulis/73ce9c34dcde10162454 to your computer and use it in GitHub Desktop.
RDBMS: Generate the next auto increment ID
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
----------------------------------------------------------------- | |
-- 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 thatid
to 5, does not trigger any sequence updates.Haven't checked if that is the case with MySQL as well.