How LASTVAL() Works in PostgreSQL

In PostgreSQL, the lastval() function returns the value most recently returned by nextval() in the current session.

The lastval() function is very similar to the currval() function, except that lastval() doesn’t require the name of a sequence like currval() does. That’s because lastval() doesn’t report on any particular sequence – it reports on the last time nextval() was used in the current session, regardless of which sequence was used.

Read more

Fix “START value (…) cannot be greater than MAXVALUE (…)” When Creating a Sequence in PostgreSQL

If you’re getting an error that reads something like “START value (11) cannot be greater than MAXVALUE (10)” in PostgreSQL when you’re trying to create a sequence, it’s because your sequence’s start value is higher than its maximum value, when it should be lower or the same.

To fix this issue, be sure that the sequence’s maximum value is not less than its start value.

Read more

3 PostgreSQL AUTO_INCREMENT Equivalents

In MySQL and MariaDB we can use the AUTO_INCREMENT keyword to create an automatically incrementing column in a table. In SQLite, we’d use the AUTOINCREMENT keyword. And in SQL Server we can use the IDENTITY property. Some of those DBMSs also allow us to create sequence objects, which provide us with more options for creating an auto-increment type column.

When it comes to PostgreSQL, there are a few ways to create an auto-incrementing column. Below are three options for creating an AUTO_INCREMENT style column in Postgres.

Read more

Create a Sequence in PostgreSQL

PostgreSQL allows us to create sequence objects, otherwise known as “sequence generators”, or simply “sequences”. As the name suggests, a sequence object is used to generate sequence numbers.

We can use sequences to generate incrementing numbers or decrementing numbers.

Read more

How SERIAL Works in PostgreSQL

In PostgreSQL we can create auto-incrementing columns using the serial data type. The serial type causes the column to be automatically populated with an auto-incrementing value each time a new row is inserted. The same applies for the smallserial and bigserial types.

This article provides an overview of how these data types work.

Read more

6 Ways to Clone a Table in PostgreSQL

PostgreSQL provides us with several options when it comes to cloning a table. Below are six methods we can use to clone a table in Postgres. The method we use will depend on things like, whether or not we want to transfer the data, indexes, etc.

Read more