INSERT INTO
INSERT INTO statement is how you add new rows to a table. Every application that lets a user sign up, place an order, or submit a form is running an INSERT statement somewhere behind the scenes. The basic form names the table, lists the columns you are supplying values for, and then supplies those values in the same order.Basic INSERT syntax
INSERT INTO employees (first_name, last_name, department, salary)
VALUES ('Ada', 'Lovelace', 'Engineering', 95000);VALUES clause supplies one value per listed column, matched up positionally. Columns you leave out are simply not part of this statement at all.Inserting without naming columns
SQL also allows you to omit the column list entirely, in which case the values are matched against every column in the table, in the table’s physical column order:
INSERT without a column list
INSERT INTO employees VALUES (101, 'Ada', 'Lovelace', 'Engineering', 95000);
INSERT silently depends on the exact physical order of every column in the table. If a teammate later adds a column, reorders one, or you run this same statement against a table in another environment with a slightly different schema, the values can shift into the wrong columns without any error at all — or the statement simply breaks. Always list the columns explicitly. It costs a few extra keystrokes and makes the statement immune to schema changes elsewhere in the table.Omitted columns
When you use an explicit column list, any column you don’t mention is left out of the statement. What ends up in that column depends on how it was defined:
If the column has a DEFAULT value defined, that default is used
Otherwise, if the column allows NULLs, it is set to NULL
If the column is NOT NULL with no default, the whole INSERT fails with an error
Relying on defaults
CREATE TABLE employees (
id SERIAL PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
is_active BOOLEAN DEFAULT TRUE,
hired_at TIMESTAMP DEFAULT NOW()
);
-- is_active and hired_at are not mentioned, so they take their defaults
INSERT INTO employees (first_name, last_name)
VALUES ('Grace', 'Hopper');Getting the inserted row back
RETURNING clause that hands back columns from the row you just inserted, in the same statement:INSERT ... RETURNING (PostgreSQL)
INSERT INTO employees (first_name, last_name)
VALUES ('Grace', 'Hopper')
RETURNING id, hired_at;RETURNING is a PostgreSQL (and Oracle/SQLite) extension, not part of every dialect. SQL Server uses an OUTPUT clause with similar intent, while MySQL has no direct equivalent — the usual workaround there is calling LAST_INSERT_ID() in a follow-up statement to retrieve an auto-increment key. Always check your database’s documentation before relying on this kind of feature across environments.Dialect | Getting the generated ID back |
|---|---|
PostgreSQL / SQLite / Oracle |
|
SQL Server |
|
MySQL / MariaDB |
|