SQL INSERT INTO
INSERT adds new rows. Use it for single rows, bulk inserts, or insert-from-select.
INSERT in practice
EXAMPLE
-- Single row
INSERT INTO users (email, name, country)
VALUES ('ada@example.com', 'Ada', 'AU');
-- Multi-row (much faster than many single inserts)
INSERT INTO users (email, name, country) VALUES
('a@example.com', 'A', 'AU'),
('b@example.com', 'B', 'NZ'),
('c@example.com', 'C', 'US');
-- INSERT from a query
INSERT INTO audit_log (entity, action, payload)
SELECT 'order', 'created', row_to_json(o)
FROM orders o
WHERE o.created_at > NOW() - INTERVAL '1 day';
-- INSERT ... ON CONFLICT (UPSERT, Postgres + SQLite)
INSERT INTO users (id, email, name)
VALUES (1, 'ada@example.com', 'Ada')
ON CONFLICT (id) DO UPDATE
SET email = EXCLUDED.email,
name = EXCLUDED.name;
-- ON CONFLICT DO NOTHING for idempotent inserts
INSERT INTO tags (name)
VALUES ('graphql'), ('postgres')
ON CONFLICT (name) DO NOTHING;
-- RETURNING the new row (Postgres)
INSERT INTO orders (user_id, total)
VALUES (1, 9990)
RETURNING id, created_at;
-- Always specify column names
-- Without them, your code breaks when the table schema changes
INSERT INTO users (email, name) VALUES (...); -- safe
INSERT INTO users VALUES (...); -- fragile - depends on column order
-- Bulk insert with COPY (Postgres) - fastest for big imports
-- psql -c "COPY users (email, name, country) FROM '/path/users.csv' CSV HEADER;"
-- Transactions for multi-step inserts
BEGIN;
INSERT INTO users (email, name) VALUES ('ada@x', 'Ada') RETURNING id;
-- ... use the id for follow-up inserts ...
COMMIT;
-- Constraints catch bad data at insert time
-- CHECK, NOT NULL, UNIQUE, FOREIGN KEY all prevent garbage rows.
Why it matters
Always specify column names. Use multi-row inserts for batches; reach for COPY when bulk-loading. ON CONFLICT is the cleanest upsert and worth knowing. Constraints are guards - let them reject bad data at the boundary.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Example
Example
INSERT INTO customers (name, email, country)
VALUES ('Ada Lovelace', 'ada@example.com', 'UK');
Try it Yourself »
Exercise
Add a row to the customers table.
INSERT
customers (name) VALUES ('Ada');
Four letters; pairs with INSERT.
Discussion
Loading…