How can you create an auto-increment column in SQL?
Posted by AliceWk
Last Updated: June 10, 2024
In SQL, an auto-increment column can be created using specific syntax depending on the SQL database management system (DBMS) you are using (e.g., MySQL, PostgreSQL, SQL Server, or SQLite). Below are examples for the most common systems:
MySQL / MariaDB
In MySQL, you can create an auto-increment column in a CREATE TABLE statement by using the AUTO_INCREMENT keyword.
CREATE TABLE example (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255)
);
In this example, the id column will automatically increment with each new row inserted.
PostgreSQL
In PostgreSQL, you can use the SERIAL data type, which automatically creates an integer column that auto-increments.
CREATE TABLE example (
    id SERIAL PRIMARY KEY,
    name VARCHAR(255)
);
Alternatively, you can use the BIGSERIAL for larger integers.
SQL Server
In SQL Server, you would use the IDENTITY property.
CREATE TABLE example (
    id INT IDENTITY(1,1) PRIMARY KEY,
    name NVARCHAR(255)
);
In this case, IDENTITY(1,1) means that the starting value is 1 and each subsequent value will increase by 1.
SQLite
In SQLite, you can declare a column with the INTEGER PRIMARY KEY and it will automatically be an auto-incrementing primary key.
CREATE TABLE example (
    id INTEGER PRIMARY KEY,
    name TEXT
);
General Notes
- Make sure to define the auto-increment column as a primary key or unique if necessary, to ensure each value is unique. - Depending on the DBMS, you might also need to manage other configurations for behavior when rows are removed or when maximum values are reached. Choose the syntax according to the database management system you are using, and you will have an auto-incrementing column in your table!