SQL AUTO INCREMENT
SQL AUTO INCREMENT is a feature used in SQL databases to automatically generate a unique value for a column in a table when a new row is inserted. This is particularly useful for primary keys.
Example Using MySQL
-
Creating a Table with AUTO_INCREMENT:
CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(255) NOT NULL, email VARCHAR(255) NOT NULL );Here, the
idcolumn will automatically increment by 1 each time a new row is inserted into theuserstable. TheAUTO_INCREMENTkeyword is used to specify that theidcolumn should automatically increment, andPRIMARY KEYensures that eachidis unique. -
Inserting Data into the Table:
INSERT INTO users (username, email) VALUES ('john_doe', 'john@example.com'); INSERT INTO users (username, email) VALUES ('jane_doe', 'jane@example.com'); -
Table Data after Insertions:
SELECT * FROM users;Output:
+----+-----------+-----------------+ | id | username | email | +----+-----------+-----------------+ | 1 | john_doe | john@example.com| | 2 | jane_doe | jane@example.com| +----+-----------+-----------------+As you can see, the
idcolumn values are automatically incremented.
Example Using PostgreSQL
-
Creating a Table with SERIAL:
CREATE TABLE users ( id SERIAL PRIMARY KEY, username VARCHAR(255) NOT NULL, email VARCHAR(255) NOT NULL );In PostgreSQL, the
SERIALkeyword is used to create an auto-incrementing integer column. -
Inserting Data into the Table:
INSERT INTO users (username, email) VALUES ('john_doe', 'john@example.com'); INSERT INTO users (username, email) VALUES ('jane_doe', 'jane@example.com'); -
Table Data after Insertions:
SELECT * FROM users;Output:
+----+-----------+-----------------+ | id | username | email | +----+-----------+-----------------+ | 1 | john_doe | john@example.com| | 2 | jane_doe | jane@example.com| +----+-----------+-----------------+
Example Using SQLite
-
Creating a Table with AUTOINCREMENT:
CREATE TABLE users ( id INTEGER PRIMARY KEY AUTOINCREMENT, username VARCHAR(255) NOT NULL, email VARCHAR(255) NOT NULL );In SQLite,
AUTOINCREMENTensures that theidcolumn values are unique and increment automatically. -
Inserting Data into the Table:
INSERT INTO users (username, email) VALUES ('john_doe', 'john@example.com'); INSERT INTO users (username, email) VALUES ('jane_doe', 'jane@example.com'); -
Table Data after Insertions:
SELECT * FROM users;Output:
+----+-----------+-----------------+ | id | username | email | +----+-----------+-----------------+ | 1 | john_doe | john@example.com| | 2 | jane_doe | jane@example.com| +----+-----------+-----------------+
In each case, the id column automatically increments by 1 for each new row inserted, ensuring each row has a unique identifier.
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
