SQL INSERT INTO VALUES — Adding Rows to a Table
How to insert single and multiple rows with INSERT INTO ... VALUES, including UPSERT patterns for PostgreSQL, MySQL, and SQLite.
DML Commands
Detailed Explanation
Inserting Data with INSERT
The INSERT INTO statement adds new rows to a table. You can insert a single row, multiple rows, or rows derived from a subquery.
Single Row Insert
INSERT INTO employees (name, email, department_id, salary)
VALUES ('Alice Smith', 'alice@example.com', 3, 95000);
Multi-Row Insert
INSERT INTO employees (name, email, department_id, salary)
VALUES
('Bob Jones', 'bob@example.com', 2, 87000),
('Carol White', 'carol@example.com', 3, 82000),
('Dave Brown', 'dave@example.com', 1, 76000);
INSERT from SELECT
INSERT INTO archived_employees (name, email, salary)
SELECT name, email, salary
FROM employees
WHERE is_active = false;
UPSERT (Insert or Update)
PostgreSQL:
INSERT INTO employees (email, name, salary)
VALUES ('alice@example.com', 'Alice S.', 96000)
ON CONFLICT (email)
DO UPDATE SET name = EXCLUDED.name, salary = EXCLUDED.salary;
MySQL:
INSERT INTO employees (email, name, salary)
VALUES ('alice@example.com', 'Alice S.', 96000)
ON DUPLICATE KEY UPDATE name = VALUES(name), salary = VALUES(salary);
SQLite:
INSERT OR REPLACE INTO employees (email, name, salary)
VALUES ('alice@example.com', 'Alice S.', 96000);
Returning Inserted Data (PostgreSQL)
INSERT INTO employees (name, email, salary)
VALUES ('New Hire', 'new@example.com', 60000)
RETURNING id, name, created_at;
This is particularly useful when you need the auto-generated id of the newly inserted row.
Use Case
You are building an API endpoint that creates new records in the database, and you need to handle both initial inserts and upsert scenarios where a record may already exist.