Skip to content

Instantly share code, notes, and snippets.

@nickgrim
Created May 12, 2020 19:46
Show Gist options
  • Select an option

  • Save nickgrim/f6e5c68a99a17783096d6c911e220c15 to your computer and use it in GitHub Desktop.

Select an option

Save nickgrim/f6e5c68a99a17783096d6c911e220c15 to your computer and use it in GitHub Desktop.
Postgres SEQUENCEs and ROLLBACK
$ psql
Expanded display is used automatically.
Pager won't be used for less than 60 lines.
psql (12.2 (Ubuntu 12.2-4), server 10.12 (Ubuntu 10.12-0ubuntu0.18.04.1))
Type "help" for help.
[local] nick@nick=# CREATE SEQUENCE test;
CREATE SEQUENCE
[local] nick@nick=# CREATE TABLE foo (id INT PRIMARY KEY DEFAULT nextval('test'));
CREATE TABLE
[local] nick@nick=# INSERT INTO foo VALUES(default);
INSERT 0 1
[local] nick@nick=# BEGIN;
BEGIN
[local] nick@nick=# INSERT INTO foo VALUES(default);
INSERT 0 1
[local] nick@nick=# INSERT INTO foo VALUES(default);
INSERT 0 1
[local] nick@nick=# SELECT * FROM foo;
id
----
1
2
3
(3 rows)
[local] nick@nick=# ROLLBACK;
ROLLBACK
[local] nick@nick=# INSERT INTO foo VALUES(default) RETURNING id;
id
----
4
(1 row)
INSERT 0 1
[local] nick@nick=# SELECT * FROM foo;
id
----
1
4
(2 rows)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment