← Interview prep

SQL interview questions

Queries, joins, window functions, and database design.

501 questions · Page 10 of 26

Want the full pack? Interview packs · Mock interview · Mentora

Page 10 of 26

Questions 181–200 of 501 · 0 of 20 on this page marked learned

181.sql-0181Mediummid

What are generated columns, and when would you use one?

A generated column is computed from other columns in the same row, declared with GENERATED ALWAYS AS (expr). VIRTUAL columns are computed on read; STORED columns are computed on write and saved. They keep derived values such as a line total or a lowercased email consistent and can be indexed.

Full answer
sql
CREATE TABLE lines (
  qty        INTEGER NOT NULL,
  unit_price INTEGER NOT NULL,
  total      INTEGER GENERATED ALWAYS AS (qty * unit_price) VIRTUAL
);
INSERT INTO lines (qty, unit_price) VALUES (2, 4), (5, 1);
SELECT qty, unit_price, total FROM lines ORDER BY total;
qtyunit_pricetotal
515
248

total is always qty * unit_price; there is no way to store a wrong value in it. Writing to it directly is an error:

sql
CREATE TABLE l2 (qty INTEGER, unit_price INTEGER, total INTEGER GENERATED ALWAYS AS (qty * unit_price));
INSERT INTO l2 (qty, unit_price, total) VALUES (1, 1, 99);
-- error on purpose
text
Error: cannot INSERT into generated column "total"

SQLite supports VIRTUAL (the default) and STORED. PostgreSQL 12 to 17 supports STORED only:

sql
CREATE TABLE lines (qty int, unit_price int, total int GENERATED ALWAYS AS (qty * unit_price) STORED);
INSERT INTO lines (qty, unit_price) VALUES (2, 4);
SELECT qty, unit_price, total FROM lines;
qtyunit_pricetotal
248

Typical uses: normalized search keys (lower(email)), extracted JSON fields, and totals that reports filter on. The expression must be deterministic and can only use the current row.

sql
CREATE TABLE lines (
  qty        INTEGER NOT NULL,
  unit_price INTEGER NOT NULL,
  total      INTEGER GENERATED ALWAYS AS (qty * unit_price) VIRTUAL
);
INSERT INTO lines (qty, unit_price) VALUES (2, 4), (5, 1);
SELECT qty, unit_price, total FROM lines ORDER BY total;

-- error on purpose
CREATE TABLE l2 (qty INTEGER, unit_price INTEGER, total INTEGER GENERATED ALWAYS AS (qty * unit_price));
INSERT INTO l2 (qty, unit_price, total) VALUES (1, 1, 99);

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • GENERATED ALWAYS AS computes a column from the row
  • VIRTUAL computes on read; STORED saves on write
  • Generated columns cannot be written directly
  • They can be indexed

Common mistakes

  • Using non-deterministic functions such as random() in the expression
  • Expecting a generated column to read other tables

Follow-ups

  • How do generated columns compare with views?
  • Would you index a VIRTUAL column?

Tips

  • Mention the consistency benefit
182.sql-0182Mediummid

How do you add a NOT NULL column to a table that already has rows?

Add the column with a DEFAULT, so existing rows get a value and the constraint holds. Without a default, the ALTER fails because existing rows would contain NULL. For computed values, add the column as nullable, backfill with UPDATE, then add NOT NULL (PostgreSQL) or rebuild the table (SQLite).

Full answer
sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');
sql
ALTER TABLE employees ADD COLUMN level TEXT NOT NULL;  -- error on purpose
text
Error: Cannot add a NOT NULL column with default value NULL
sql
ALTER TABLE employees ADD COLUMN level TEXT NOT NULL;  -- error on purpose
text
Error: column "level" of relation "employees" contains null values

With a default the change succeeds and existing rows show it:

sql
ALTER TABLE employees ADD COLUMN level TEXT NOT NULL DEFAULT 'staff';
SELECT id, name, level FROM employees WHERE id <= 2 ORDER BY id;
idnamelevel
1Ashastaff
2Ravistaff

When the value must be computed per row, a three-step migration works on PostgreSQL:

sql
ALTER TABLE employees ADD COLUMN band TEXT;
UPDATE employees SET band = CASE WHEN salary >= 100000 THEN 'senior' ELSE 'standard' END;
ALTER TABLE employees ALTER COLUMN band SET NOT NULL;
SELECT id, name, band FROM employees WHERE id <= 2 ORDER BY id;
idnameband
1Ashasenior
2Ravistandard

SQLite's ALTER TABLE cannot add NOT NULL to an existing column; the usual path is to create a new table, copy the data and rename it. On large PostgreSQL tables, adding a column with a constant default is fast (since version 11), while a backfill UPDATE rewrites rows and should run in batches.

sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');

-- error on purpose
ALTER TABLE employees ADD COLUMN level TEXT NOT NULL;

ALTER TABLE employees ADD COLUMN level TEXT NOT NULL DEFAULT 'staff';
SELECT id, name, level FROM employees WHERE id <= 2 ORDER BY id;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • NOT NULL without a default fails on a non-empty table
  • A DEFAULT fills existing rows
  • Backfill then SET NOT NULL for computed values
  • SQLite needs a table rebuild to change constraints

Common mistakes

  • Running a huge single backfill UPDATE during peak traffic
  • Adding NOT NULL before backfilling

Follow-ups

  • How would you rename a column safely in a live system?
  • Why are constant defaults fast in PostgreSQL 11+?

Tips

  • Describe the expand and backfill steps
183.sql-0183Hardsenior

How would you allow only one active subscription per user, while allowing any number of cancelled ones?

Create a partial unique index: CREATE UNIQUE INDEX ... ON subscriptions(user_id) WHERE status = 'active'. Only active rows are in the index, so a second active row for the same user is rejected while cancelled rows are unrestricted. SQLite and PostgreSQL both support this.

Full answer
sql
CREATE TABLE subs (id INTEGER PRIMARY KEY, user_id INTEGER, status TEXT);
CREATE UNIQUE INDEX one_active ON subs(user_id) WHERE status = 'active';
INSERT INTO subs VALUES (1, 1, 'cancelled'), (2, 1, 'cancelled'), (3, 1, 'active');
SELECT * FROM subs ORDER BY id;
iduser_idstatus
11cancelled
21cancelled
31active

User 1 has one active and two cancelled subscriptions, which is allowed. A second active one fails:

sql
CREATE TABLE s2 (id INTEGER PRIMARY KEY, user_id INTEGER, status TEXT);
CREATE UNIQUE INDEX one_active2 ON s2(user_id) WHERE status = 'active';
INSERT INTO s2 VALUES (1, 1, 'active'), (2, 1, 'active');
-- error on purpose
text
Error: UNIQUE constraint failed: s2.user_id

A plain UNIQUE (user_id, status) would wrongly block a second cancelled row. Application checks ("select, then insert if none") race under concurrency: two requests can both see no active row and both insert. The index makes the database the referee.

PostgreSQL behaves the same:

sql
CREATE TABLE s2 (id int PRIMARY KEY, user_id int, status text);
CREATE UNIQUE INDEX one_active2 ON s2(user_id) WHERE status = 'active';
INSERT INTO s2 VALUES (1, 1, 'active'), (2, 1, 'active');
-- error on purpose
text
Error: duplicate key value violates unique constraint "one_active2"
sql
CREATE TABLE subs (id INTEGER PRIMARY KEY, user_id INTEGER, status TEXT);
CREATE UNIQUE INDEX one_active ON subs(user_id) WHERE status = 'active';
INSERT INTO subs VALUES (1, 1, 'cancelled'), (2, 1, 'cancelled'), (3, 1, 'active');
SELECT * FROM subs ORDER BY id;

-- error on purpose
CREATE TABLE s2 (id INTEGER PRIMARY KEY, user_id INTEGER, status TEXT);
CREATE UNIQUE INDEX one_active2 ON s2(user_id) WHERE status = 'active';
INSERT INTO s2 VALUES (1, 1, 'active'), (2, 1, 'active');

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • A partial unique index enforces uniqueness on a subset of rows
  • Rows outside the WHERE clause are not constrained
  • UNIQUE (user_id, status) is too strict
  • Check-then-insert in the application races

Common mistakes

  • Enforcing the rule only in application code
  • Using a composite unique that blocks repeated cancelled rows

Follow-ups

  • How would you enforce no overlapping booking periods?
  • What happens to the index when a row changes status?

Tips

  • Mention the race condition explicitly
184.sql-0184Mediummid

You need to delete a parent row and its children, but the foreign key has no CASCADE. In what order do you delete, and why does the order matter?

Delete the children first, then the parent, inside one transaction. Deleting the parent first violates the foreign key and fails. In PostgreSQL a constraint declared DEFERRABLE INITIALLY DEFERRED is checked at commit instead, which allows either order within the transaction.

Full answer

Deleting the parent first fails:

sql
PRAGMA foreign_keys = ON;
CREATE TABLE p (id INTEGER PRIMARY KEY);
CREATE TABLE c (id INTEGER PRIMARY KEY, p_id INTEGER REFERENCES p(id));
INSERT INTO p VALUES (1);
INSERT INTO c VALUES (10, 1);
DELETE FROM p WHERE id = 1;
-- error on purpose
text
Error: FOREIGN KEY constraint failed

Children first works:

sql
PRAGMA foreign_keys = ON;
CREATE TABLE p2 (id INTEGER PRIMARY KEY);
CREATE TABLE c2 (id INTEGER PRIMARY KEY, p_id INTEGER REFERENCES p2(id));
INSERT INTO p2 VALUES (1);
INSERT INTO c2 VALUES (10, 1);
BEGIN;
DELETE FROM c2 WHERE p_id = 1;
DELETE FROM p2 WHERE id = 1;
COMMIT;
SELECT (SELECT COUNT(*) FROM p2) AS parents, (SELECT COUNT(*) FROM c2) AS children;
parentschildren
00

Wrapping both statements in a transaction means a failure in the second delete leaves the children in place, not half-deleted.

PostgreSQL can defer the check to commit time when the constraint is declared deferrable:

sql
CREATE TABLE p (id int PRIMARY KEY);
CREATE TABLE c (id int PRIMARY KEY, p_id int REFERENCES p(id) DEFERRABLE INITIALLY DEFERRED);
INSERT INTO p VALUES (1);
INSERT INTO c VALUES (10, 1);
BEGIN;
DELETE FROM p WHERE id = 1;
DELETE FROM c WHERE p_id = 1;
COMMIT;
SELECT (SELECT COUNT(*) FROM p) AS parents, (SELECT COUNT(*) FROM c) AS children;
parentschildren
00

Deferral helps when rows reference each other in a cycle, or when bulk loads arrive in an awkward order. SQLite also supports DEFERRABLE INITIALLY DEFERRED on foreign keys.

sql
-- error on purpose
PRAGMA foreign_keys = ON;
CREATE TABLE p (id INTEGER PRIMARY KEY);
CREATE TABLE c (id INTEGER PRIMARY KEY, p_id INTEGER REFERENCES p(id));
INSERT INTO p VALUES (1);
INSERT INTO c VALUES (10, 1);
DELETE FROM p WHERE id = 1;

PRAGMA foreign_keys = ON;
CREATE TABLE p2 (id INTEGER PRIMARY KEY);
CREATE TABLE c2 (id INTEGER PRIMARY KEY, p_id INTEGER REFERENCES p2(id));
INSERT INTO p2 VALUES (1);
INSERT INTO c2 VALUES (10, 1);
BEGIN;
DELETE FROM c2 WHERE p_id = 1;
DELETE FROM p2 WHERE id = 1;
COMMIT;
SELECT (SELECT COUNT(*) FROM p2) AS parents, (SELECT COUNT(*) FROM c2) AS children;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • Delete children before the parent
  • Use one transaction for related deletes
  • Deferred constraints are checked at commit
  • Both engines support deferrable foreign keys

Common mistakes

  • Disabling foreign keys to force a delete
  • Running the deletes outside a transaction

Follow-ups

  • When would you choose CASCADE instead?
  • How would you handle a cycle of references?

Tips

  • Explain why the order matters
185.sql-0185Easyfresher

Natural key or surrogate key: how do they differ, and when is each a good fit? Give an example of each.

A natural key comes from the data itself, such as an ISO country code or an email address. A surrogate key is a meaningless generated value, such as an auto-increment integer or a UUID. Natural keys can change or turn out not to be unique; surrogate keys are stable but need a separate UNIQUE on the natural attributes.

Full answer

Natural keys work well when the value is stable, short and truly unique: ISO country codes ('IN', 'FR'), currency codes ('EUR') or airport codes. Joins read clearly, and a lookup table needs no extra id.

They cause trouble when reality changes. Emails change, people share names, and national id numbers are not universal and are sensitive data. If a natural key changes, every referencing row must change too.

A surrogate key avoids those updates. The cost is that it does not stop duplicates of the real-world thing, so keep a UNIQUE constraint on the natural attributes:

sql
CREATE TABLE customers (id INTEGER PRIMARY KEY, email TEXT NOT NULL UNIQUE);
INSERT INTO customers (email) VALUES ('ana@example.com');
INSERT INTO customers (email) VALUES ('ana@example.com');
-- error on purpose
text
Error: UNIQUE constraint failed: customers.email

A common pattern is natural keys for small, standard code tables and surrogate keys for business entities such as customers and orders.

sql
-- error on purpose
CREATE TABLE customers (id INTEGER PRIMARY KEY, email TEXT NOT NULL UNIQUE);
INSERT INTO customers (email) VALUES ('ana@example.com');
INSERT INTO customers (email) VALUES ('ana@example.com');

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Natural keys come from the data
  • Surrogate keys are generated and meaningless
  • Natural keys can change or collide
  • Keep a UNIQUE on natural attributes when using surrogates

Common mistakes

  • Using email as a primary key
  • Using a surrogate key without any uniqueness on the real identifier

Follow-ups

  • Would you use a natural key for a country table?
  • How do key changes affect foreign keys?

Tips

  • Give one good and one bad natural key
186.sql-0186Hardsenior

Can a CHECK constraint enforce a rule that involves other rows, such as 'a department may have at most 10 employees'?

No. CHECK constraints see only the current row, and subqueries are not allowed in them on SQLite or PostgreSQL. Cross-row rules need a trigger, a constraint backed by an index (unique, exclusion), or application logic with proper locking. Triggers must handle concurrency, or two inserts can both pass the check.

Full answer

A subquery in a CHECK is rejected:

sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');
sql
CREATE TABLE t (dept_id INTEGER CHECK ((SELECT COUNT(*) FROM employees) < 10));  -- error on purpose
text
Error: subqueries prohibited in CHECK constraints
sql
CREATE TABLE t (dept_id INTEGER CHECK ((SELECT COUNT(*) FROM employees) < 10));  -- error on purpose
text
Error: cannot use subquery in check constraint

A trigger can enforce the limit. The sample uses a limit of 3 so that Engineering, which already has three people, is full:

sql
CREATE TRIGGER dept_limit BEFORE INSERT ON employees
WHEN (SELECT COUNT(*) FROM employees WHERE dept_id = NEW.dept_id) >= 3
BEGIN
  SELECT RAISE(ABORT, 'department is full');
END;
INSERT INTO employees (id, name, dept_id) VALUES (9, 'Nia', 1);
-- error on purpose
text
Error: department is full

Under concurrency the trigger is not enough on its own in PostgreSQL. Two transactions can each count 9, insert, and commit 11. Fixes include locking the parent department row (SELECT ... FOR UPDATE) before inserting, using SERIALIZABLE isolation, or keeping a counter column on the department with a CHECK on it. SQLite allows only one writer at a time, which avoids this specific race.

sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');

-- error on purpose
CREATE TABLE t (dept_id INTEGER CHECK ((SELECT COUNT(*) FROM employees) < 10));

-- error on purpose
CREATE TRIGGER dept_limit BEFORE INSERT ON employees
WHEN (SELECT COUNT(*) FROM employees WHERE dept_id = NEW.dept_id) >= 3
BEGIN
  SELECT RAISE(ABORT, 'department is full');
END;
INSERT INTO employees (id, name, dept_id) VALUES (9, 'Nia', 1);

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • CHECK constraints are row-local
  • Subqueries in CHECK are rejected
  • Triggers can enforce cross-row rules
  • Concurrency needs locking or serializable isolation

Common mistakes

  • Trusting a count-then-insert trigger under concurrent writes
  • Trying to put subqueries in CHECK

Follow-ups

  • How would a counter column with a CHECK work?
  • What is an exclusion constraint?

Tips

  • Raise the concurrency issue unprompted
187.sql-0187Mediummid

Write an UPDATE that sets each order's status to 'vip' when its customer is from Spain, using data from another table.

Use UPDATE ... FROM, supported by PostgreSQL and SQLite 3.33+: UPDATE orders SET status = 'vip' FROM customers c WHERE c.id = orders.customer_id AND c.country = 'Spain'. A portable alternative is WHERE customer_id IN (SELECT id FROM customers WHERE country = 'Spain').

Full answer
sql
CREATE TABLE customers (
  id      INTEGER PRIMARY KEY,
  name    TEXT NOT NULL,
  country TEXT
);
CREATE TABLE orders (
  id          INTEGER PRIMARY KEY,
  customer_id INTEGER REFERENCES customers(id),
  order_date  TEXT NOT NULL,
  status      TEXT NOT NULL
);
CREATE TABLE order_items (
  order_id   INTEGER REFERENCES orders(id),
  product    TEXT NOT NULL,
  qty        INTEGER NOT NULL,
  unit_price INTEGER NOT NULL
);
INSERT INTO customers VALUES (1,'Ana','Spain'),(2,'Bilal','UAE'),(3,'Chloe','France'),(4,'Dev','India');
INSERT INTO orders VALUES
  (101,1,'2026-01-05','shipped'),(102,1,'2026-02-11','shipped'),
  (103,2,'2026-02-14','cancelled'),(104,3,'2026-03-01','shipped'),
  (105,2,'2026-03-09','pending'),(106,NULL,'2026-03-12','shipped');
INSERT INTO order_items VALUES
  (101,'Notebook',2,4),(101,'Pen',5,1),(102,'Bag',1,30),(103,'Pen',10,1),
  (104,'Notebook',3,4),(104,'Bag',1,30),(105,'Lamp',1,25),(106,'Pen',2,1);
sql
UPDATE orders SET status = 'vip'
FROM customers c
WHERE c.id = orders.customer_id AND c.country = 'Spain';
SELECT id, customer_id, status FROM orders ORDER BY id;
idcustomer_idstatus
1011vip
1021vip
1032cancelled
1043shipped
1052pending
106NULLshipped

Ana's two orders changed; the rest did not. The FROM clause joins the other table, and the WHERE carries both the join condition and the filter.

The subquery form works on every engine and older SQLite versions:

sql
UPDATE orders SET status = 'vip'
WHERE customer_id IN (SELECT id FROM customers WHERE country = 'Spain');
SELECT COUNT(*) AS vip_orders FROM orders WHERE status = 'vip';
vip_orders
2

With UPDATE ... FROM, if one target row matches several rows in the joined table, the row is updated once with an arbitrary match. When the new value comes from the joined table, make sure the join is one-to-one, or aggregate first. MySQL uses UPDATE orders JOIN customers ... syntax instead (not run here).

sql
CREATE TABLE customers (
  id      INTEGER PRIMARY KEY,
  name    TEXT NOT NULL,
  country TEXT
);
CREATE TABLE orders (
  id          INTEGER PRIMARY KEY,
  customer_id INTEGER REFERENCES customers(id),
  order_date  TEXT NOT NULL,
  status      TEXT NOT NULL
);
CREATE TABLE order_items (
  order_id   INTEGER REFERENCES orders(id),
  product    TEXT NOT NULL,
  qty        INTEGER NOT NULL,
  unit_price INTEGER NOT NULL
);
INSERT INTO customers VALUES (1,'Ana','Spain'),(2,'Bilal','UAE'),(3,'Chloe','France'),(4,'Dev','India');
INSERT INTO orders VALUES
  (101,1,'2026-01-05','shipped'),(102,1,'2026-02-11','shipped'),
  (103,2,'2026-02-14','cancelled'),(104,3,'2026-03-01','shipped'),
  (105,2,'2026-03-09','pending'),(106,NULL,'2026-03-12','shipped');
INSERT INTO order_items VALUES
  (101,'Notebook',2,4),(101,'Pen',5,1),(102,'Bag',1,30),(103,'Pen',10,1),
  (104,'Notebook',3,4),(104,'Bag',1,30),(105,'Lamp',1,25),(106,'Pen',2,1);

UPDATE orders SET status = 'vip'
FROM customers c
WHERE c.id = orders.customer_id AND c.country = 'Spain';
SELECT id, customer_id, status FROM orders ORDER BY id;

UPDATE orders SET status = 'vip'
WHERE customer_id IN (SELECT id FROM customers WHERE country = 'Spain');
SELECT COUNT(*) AS vip_orders FROM orders WHERE status = 'vip';

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • UPDATE ... FROM joins another table into an update
  • Supported in PostgreSQL and SQLite 3.33+
  • WHERE ... IN (subquery) is the portable form
  • Multiple matches per target row give an arbitrary value

Common mistakes

  • Forgetting the join condition and updating every row
  • Joining one-to-many and getting unpredictable values

Follow-ups

  • How would you set each order's total from its order lines?
  • How would you preview which rows will change?

Tips

  • Run the same WHERE as a SELECT first
188.sql-0188Mediummid

How do you insert a row, or update it if the key already exists, in one statement?

Use INSERT ... ON CONFLICT (key) DO UPDATE SET col = excluded.col in PostgreSQL and SQLite 3.24+. excluded refers to the row that was proposed for insertion, and DO NOTHING skips the row instead. The conflict target must match a unique constraint or index.

Full answer
sql
CREATE TABLE stock (sku TEXT PRIMARY KEY, qty INTEGER NOT NULL);
INSERT INTO stock VALUES ('pen', 10);
INSERT INTO stock VALUES ('pen', 3)
  ON CONFLICT (sku) DO UPDATE SET qty = stock.qty + excluded.qty;
SELECT * FROM stock;
skuqty
pen13

The second insert for 'pen' hit the primary key, so the DO UPDATE ran and added the new quantity to the existing one. excluded.qty is the 3 from the failed insert; stock.qty is the stored 10.

DO NOTHING ignores the duplicate:

sql
CREATE TABLE stock2 (sku TEXT PRIMARY KEY, qty INTEGER NOT NULL);
INSERT INTO stock2 VALUES ('pen', 10);
INSERT INTO stock2 VALUES ('pen', 3) ON CONFLICT (sku) DO NOTHING;
SELECT * FROM stock2;
skuqty
pen10

PostgreSQL uses identical syntax:

sql
CREATE TABLE stock (sku text PRIMARY KEY, qty int NOT NULL);
INSERT INTO stock VALUES ('pen', 10);
INSERT INTO stock VALUES ('pen', 3)
  ON CONFLICT (sku) DO UPDATE SET qty = stock.qty + excluded.qty;
SELECT * FROM stock;
skuqty
pen13

An upsert is atomic: unlike "select, then insert or update", two concurrent requests cannot both decide to insert.

sql
CREATE TABLE stock (sku TEXT PRIMARY KEY, qty INTEGER NOT NULL);
INSERT INTO stock VALUES ('pen', 10);
INSERT INTO stock VALUES ('pen', 3)
  ON CONFLICT (sku) DO UPDATE SET qty = stock.qty + excluded.qty;
SELECT * FROM stock;

CREATE TABLE stock2 (sku TEXT PRIMARY KEY, qty INTEGER NOT NULL);
INSERT INTO stock2 VALUES ('pen', 10);
INSERT INTO stock2 VALUES ('pen', 3) ON CONFLICT (sku) DO NOTHING;
SELECT * FROM stock2;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • INSERT ... ON CONFLICT (key) DO UPDATE performs an upsert
  • excluded holds the proposed row
  • DO NOTHING skips conflicting rows
  • The conflict target needs a unique constraint

Common mistakes

  • Writing check-then-insert logic that races
  • Overwriting a counter instead of adding excluded's value

Follow-ups

  • How does INSERT OR REPLACE differ in SQLite?
  • How would you upsert many rows from a staging table?

Tips

  • Explain excluded clearly
189.sql-0189Hardsenior

Why can SQLite's INSERT OR REPLACE lose data compared with ON CONFLICT DO UPDATE?

INSERT OR REPLACE deletes the conflicting row and inserts a new one. Columns not listed in the INSERT fall back to their defaults or NULL, ON DELETE actions on child rows fire if foreign keys are on, and delete triggers run when recursive triggers are enabled. ON CONFLICT DO UPDATE changes only the named columns of the existing row.

Full answer
sql
CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT);
INSERT INTO users VALUES (1, 'Ana', 'ana@example.com');
INSERT OR REPLACE INTO users (id, name) VALUES (1, 'Ana R');
SELECT * FROM users;
idnameemail
1Ana RNULL

The REPLACE wiped email, because the new row did not include it. With foreign keys enabled, the delete also cascades:

sql
PRAGMA foreign_keys = ON;
CREATE TABLE u2 (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE notes (user_id INTEGER REFERENCES u2(id) ON DELETE CASCADE, body TEXT);
INSERT INTO u2 VALUES (1, 'Ana');
INSERT INTO notes VALUES (1, 'hello');
INSERT OR REPLACE INTO u2 VALUES (1, 'Ana R');
SELECT (SELECT COUNT(*) FROM notes) AS notes_left, (SELECT name FROM u2) AS name;
notes_leftname
0Ana R

The note attached to user 1 was deleted, even though "user 1" still exists afterwards. The upsert keeps both:

sql
PRAGMA foreign_keys = ON;
CREATE TABLE u3 (id INTEGER PRIMARY KEY, name TEXT, email TEXT);
CREATE TABLE notes3 (user_id INTEGER REFERENCES u3(id) ON DELETE CASCADE, body TEXT);
INSERT INTO u3 VALUES (1, 'Ana', 'ana@example.com');
INSERT INTO notes3 VALUES (1, 'hello');
INSERT INTO u3 (id, name) VALUES (1, 'Ana R') ON CONFLICT (id) DO UPDATE SET name = excluded.name;
SELECT u.name, u.email, (SELECT COUNT(*) FROM notes3) AS notes_left FROM u3 u;
nameemailnotes_left
Ana Rana@example.com1

REPLACE is fine for cache-like tables where the new row fully defines the old one. For anything with references or partial updates, use ON CONFLICT DO UPDATE.

sql
CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT);
INSERT INTO users VALUES (1, 'Ana', 'ana@example.com');
INSERT OR REPLACE INTO users (id, name) VALUES (1, 'Ana R');
SELECT * FROM users;

PRAGMA foreign_keys = ON;
CREATE TABLE u2 (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE notes (user_id INTEGER REFERENCES u2(id) ON DELETE CASCADE, body TEXT);
INSERT INTO u2 VALUES (1, 'Ana');
INSERT INTO notes VALUES (1, 'hello');
INSERT OR REPLACE INTO u2 VALUES (1, 'Ana R');
SELECT (SELECT COUNT(*) FROM notes) AS notes_left, (SELECT name FROM u2) AS name;

PRAGMA foreign_keys = ON;
CREATE TABLE u3 (id INTEGER PRIMARY KEY, name TEXT, email TEXT);
CREATE TABLE notes3 (user_id INTEGER REFERENCES u3(id) ON DELETE CASCADE, body TEXT);
INSERT INTO u3 VALUES (1, 'Ana', 'ana@example.com');
INSERT INTO notes3 VALUES (1, 'hello');
INSERT INTO u3 (id, name) VALUES (1, 'Ana R') ON CONFLICT (id) DO UPDATE SET name = excluded.name;
SELECT u.name, u.email, (SELECT COUNT(*) FROM notes3) AS notes_left FROM u3 u;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • REPLACE is delete plus insert
  • Unlisted columns lose their values
  • Delete actions on child rows can fire
  • ON CONFLICT DO UPDATE changes only named columns

Common mistakes

  • Using REPLACE for partial updates
  • Losing child rows through cascades

Follow-ups

  • When is REPLACE acceptable?
  • What does REPLACE do to a rowid?

Tips

  • Show the lost column concretely
190.sql-0190Mediummid

What does RETURNING do, and how would you use it after an INSERT?

RETURNING makes INSERT, UPDATE or DELETE return columns from the affected rows, such as a generated id or the new value, without a second query. PostgreSQL has long supported it; SQLite added it in 3.35. It avoids race-prone patterns like inserting and then selecting MAX(id).

Full answer
sql
CREATE TABLE tags (id INTEGER PRIMARY KEY, name TEXT);
INSERT INTO tags (name) VALUES ('sql'), ('joins') RETURNING id, name;
idname
1sql
2joins

Both generated ids come back from the insert itself. RETURNING works with UPDATE and DELETE too:

sql
CREATE TABLE t2 (id INTEGER PRIMARY KEY, qty INTEGER);
INSERT INTO t2 VALUES (1, 5), (2, 7);
UPDATE t2 SET qty = qty + 1 WHERE id = 2 RETURNING id, qty;
idqty
28

PostgreSQL:

sql
CREATE TABLE tags (id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name text);
INSERT INTO tags (name) VALUES ('sql'), ('joins') RETURNING id, name;
idname
1sql
2joins

Selecting MAX(id) after an insert is wrong under concurrency, because another session may insert in between. RETURNING (or last_insert_rowid() in SQLite, which is per connection) avoids that.

sql
CREATE TABLE tags (id INTEGER PRIMARY KEY, name TEXT);
INSERT INTO tags (name) VALUES ('sql'), ('joins') RETURNING id, name;

CREATE TABLE t2 (id INTEGER PRIMARY KEY, qty INTEGER);
INSERT INTO t2 VALUES (1, 5), (2, 7);
UPDATE t2 SET qty = qty + 1 WHERE id = 2 RETURNING id, qty;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • RETURNING returns columns from affected rows
  • Works with INSERT, UPDATE and DELETE
  • PostgreSQL and SQLite 3.35+ support it
  • Avoids SELECT MAX(id) after insert

Common mistakes

  • Reading MAX(id) to find a new row's id
  • Running a second query to see updated values

Follow-ups

  • How would you return old values from an UPDATE?
  • What is last_insert_rowid()?

Tips

  • Mention the concurrency problem it solves
191.sql-0191Easyfresher

Write a statement that copies shipped orders from 2026 into an archive table.

Use INSERT INTO archive (cols) SELECT cols FROM orders WHERE ...; it inserts every row the SELECT returns in one statement. List the target columns explicitly so a later column change does not shift values. Combine it with a DELETE in one transaction to move rows instead of copying them.

Full answer
sql
CREATE TABLE customers (
  id      INTEGER PRIMARY KEY,
  name    TEXT NOT NULL,
  country TEXT
);
CREATE TABLE orders (
  id          INTEGER PRIMARY KEY,
  customer_id INTEGER REFERENCES customers(id),
  order_date  TEXT NOT NULL,
  status      TEXT NOT NULL
);
CREATE TABLE order_items (
  order_id   INTEGER REFERENCES orders(id),
  product    TEXT NOT NULL,
  qty        INTEGER NOT NULL,
  unit_price INTEGER NOT NULL
);
INSERT INTO customers VALUES (1,'Ana','Spain'),(2,'Bilal','UAE'),(3,'Chloe','France'),(4,'Dev','India');
INSERT INTO orders VALUES
  (101,1,'2026-01-05','shipped'),(102,1,'2026-02-11','shipped'),
  (103,2,'2026-02-14','cancelled'),(104,3,'2026-03-01','shipped'),
  (105,2,'2026-03-09','pending'),(106,NULL,'2026-03-12','shipped');
INSERT INTO order_items VALUES
  (101,'Notebook',2,4),(101,'Pen',5,1),(102,'Bag',1,30),(103,'Pen',10,1),
  (104,'Notebook',3,4),(104,'Bag',1,30),(105,'Lamp',1,25),(106,'Pen',2,1);
sql
CREATE TABLE orders_archive (id INTEGER PRIMARY KEY, customer_id INTEGER, order_date TEXT, status TEXT);
INSERT INTO orders_archive (id, customer_id, order_date, status)
SELECT id, customer_id, order_date, status FROM orders
WHERE status = 'shipped' AND order_date >= '2026-01-01';
SELECT id, status FROM orders_archive ORDER BY id;
idstatus
101shipped
102shipped
104shipped
106shipped

Four shipped orders were copied. No VALUES list is needed; the SELECT supplies the rows.

To move rather than copy, delete with the same condition inside a transaction, so a failure cannot leave rows in both places or in neither:

sql
CREATE TABLE arch2 (id INTEGER PRIMARY KEY, status TEXT);
BEGIN;
INSERT INTO arch2 (id, status) SELECT id, status FROM orders WHERE status = 'shipped';
DELETE FROM orders WHERE status = 'shipped';
COMMIT;
SELECT (SELECT COUNT(*) FROM orders) AS left_in_orders, (SELECT COUNT(*) FROM arch2) AS archived;
left_in_ordersarchived
24

CREATE TABLE archive AS SELECT ... creates and fills a table in one step, but it copies no constraints or indexes, so it suits one-off snapshots more than permanent tables.

sql
CREATE TABLE customers (
  id      INTEGER PRIMARY KEY,
  name    TEXT NOT NULL,
  country TEXT
);
CREATE TABLE orders (
  id          INTEGER PRIMARY KEY,
  customer_id INTEGER REFERENCES customers(id),
  order_date  TEXT NOT NULL,
  status      TEXT NOT NULL
);
CREATE TABLE order_items (
  order_id   INTEGER REFERENCES orders(id),
  product    TEXT NOT NULL,
  qty        INTEGER NOT NULL,
  unit_price INTEGER NOT NULL
);
INSERT INTO customers VALUES (1,'Ana','Spain'),(2,'Bilal','UAE'),(3,'Chloe','France'),(4,'Dev','India');
INSERT INTO orders VALUES
  (101,1,'2026-01-05','shipped'),(102,1,'2026-02-11','shipped'),
  (103,2,'2026-02-14','cancelled'),(104,3,'2026-03-01','shipped'),
  (105,2,'2026-03-09','pending'),(106,NULL,'2026-03-12','shipped');
INSERT INTO order_items VALUES
  (101,'Notebook',2,4),(101,'Pen',5,1),(102,'Bag',1,30),(103,'Pen',10,1),
  (104,'Notebook',3,4),(104,'Bag',1,30),(105,'Lamp',1,25),(106,'Pen',2,1);

CREATE TABLE orders_archive (id INTEGER PRIMARY KEY, customer_id INTEGER, order_date TEXT, status TEXT);
INSERT INTO orders_archive (id, customer_id, order_date, status)
SELECT id, customer_id, order_date, status FROM orders
WHERE status = 'shipped' AND order_date >= '2026-01-01';
SELECT id, status FROM orders_archive ORDER BY id;

CREATE TABLE arch2 (id INTEGER PRIMARY KEY, status TEXT);
BEGIN;
INSERT INTO arch2 (id, status) SELECT id, status FROM orders WHERE status = 'shipped';
DELETE FROM orders WHERE status = 'shipped';
COMMIT;
SELECT (SELECT COUNT(*) FROM orders) AS left_in_orders, (SELECT COUNT(*) FROM arch2) AS archived;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • INSERT ... SELECT inserts the query's rows
  • List target columns explicitly
  • Wrap copy plus delete in one transaction to move rows
  • CREATE TABLE AS copies data but not constraints

Common mistakes

  • Relying on column order without a column list
  • Moving rows with two statements outside a transaction

Follow-ups

  • How would you archive in batches of 1000?
  • How would PostgreSQL do the move in one statement?

Tips

  • Mention the transaction for moves
192.sql-0192Mediummid

A table has duplicate rows for the same email. Write a statement that deletes the duplicates and keeps the row with the lowest id.

Delete every row whose id is not the minimum id for its email: DELETE FROM t WHERE id NOT IN (SELECT MIN(id) FROM t GROUP BY email). A window version ranks rows per email with ROW_NUMBER and deletes those ranked above 1. Add a UNIQUE constraint afterwards so duplicates cannot return.

Full answer
sql
CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT);
INSERT INTO users VALUES (1,'a@x.com'),(2,'a@x.com'),(3,'b@x.com'),(4,'a@x.com');
DELETE FROM users WHERE id NOT IN (SELECT MIN(id) FROM users GROUP BY email);
SELECT * FROM users ORDER BY id;
idemail
1a@x.com
3b@x.com

The subquery keeps one id per email (1 and 3); everything else goes. NOT IN is safe here because MIN(id) over a non-NULL id never returns NULL.

The window version is easier to adapt when "keep" means something else, such as the most recent row:

sql
CREATE TABLE u2 (id INTEGER PRIMARY KEY, email TEXT);
INSERT INTO u2 VALUES (1,'a@x.com'),(2,'a@x.com'),(3,'b@x.com'),(4,'a@x.com');
DELETE FROM u2 WHERE id IN (
  SELECT id FROM (SELECT id, ROW_NUMBER() OVER (PARTITION BY email ORDER BY id DESC) AS rn FROM u2) WHERE rn > 1
);
SELECT * FROM u2 ORDER BY id;
idemail
3b@x.com
4a@x.com

Run the same logic as a SELECT first to see what will be deleted, then add the constraint:

text
CREATE UNIQUE INDEX users_email_unique ON users(email);

Without that, the next import will create duplicates again. Watch case and spaces too: 'Ana@x.com' and 'ana@x.com ' count as different values unless normalized.

sql
CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT);
INSERT INTO users VALUES (1,'a@x.com'),(2,'a@x.com'),(3,'b@x.com'),(4,'a@x.com');
DELETE FROM users WHERE id NOT IN (SELECT MIN(id) FROM users GROUP BY email);
SELECT * FROM users ORDER BY id;

CREATE TABLE u2 (id INTEGER PRIMARY KEY, email TEXT);
INSERT INTO u2 VALUES (1,'a@x.com'),(2,'a@x.com'),(3,'b@x.com'),(4,'a@x.com');
DELETE FROM u2 WHERE id IN (
  SELECT id FROM (SELECT id, ROW_NUMBER() OVER (PARTITION BY email ORDER BY id DESC) AS rn FROM u2) WHERE rn > 1
);
SELECT * FROM u2 ORDER BY id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Keep MIN(id) per group and delete the rest
  • ROW_NUMBER per group handles other keep rules
  • Preview with SELECT before deleting
  • Add a UNIQUE constraint afterwards

Common mistakes

  • Deleting all copies including the one to keep
  • Cleaning duplicates without preventing new ones

Follow-ups

  • How would you keep the most recent row instead?
  • How would you merge child rows that point at the deleted duplicates?

Tips

  • Mention the follow-up constraint
193.sql-0193Easyfresher

How do DELETE without WHERE, TRUNCATE and DROP TABLE differ?

DELETE without WHERE removes all rows one by one, fires row triggers and can be rolled back. TRUNCATE (PostgreSQL, not SQLite) empties the table quickly without scanning rows and does not fire DELETE triggers, but is still transactional in PostgreSQL. DROP TABLE removes the table and its definition entirely.

Full answer

SQLite has no TRUNCATE; a DELETE without WHERE uses an internal fast path when no triggers or foreign keys need row-by-row work:

sql
CREATE TABLE customers (
  id      INTEGER PRIMARY KEY,
  name    TEXT NOT NULL,
  country TEXT
);
CREATE TABLE orders (
  id          INTEGER PRIMARY KEY,
  customer_id INTEGER REFERENCES customers(id),
  order_date  TEXT NOT NULL,
  status      TEXT NOT NULL
);
CREATE TABLE order_items (
  order_id   INTEGER REFERENCES orders(id),
  product    TEXT NOT NULL,
  qty        INTEGER NOT NULL,
  unit_price INTEGER NOT NULL
);
INSERT INTO customers VALUES (1,'Ana','Spain'),(2,'Bilal','UAE'),(3,'Chloe','France'),(4,'Dev','India');
INSERT INTO orders VALUES
  (101,1,'2026-01-05','shipped'),(102,1,'2026-02-11','shipped'),
  (103,2,'2026-02-14','cancelled'),(104,3,'2026-03-01','shipped'),
  (105,2,'2026-03-09','pending'),(106,NULL,'2026-03-12','shipped');
INSERT INTO order_items VALUES
  (101,'Notebook',2,4),(101,'Pen',5,1),(102,'Bag',1,30),(103,'Pen',10,1),
  (104,'Notebook',3,4),(104,'Bag',1,30),(105,'Lamp',1,25),(106,'Pen',2,1);
sql
TRUNCATE TABLE order_items;  -- error on purpose
text
Error: near "TRUNCATE": syntax error
sql
DELETE FROM order_items;
SELECT COUNT(*) AS rows_left FROM order_items;
rows_left
0

In PostgreSQL, TRUNCATE can be rolled back like other statements:

sql
BEGIN;
TRUNCATE order_items;
ROLLBACK;
SELECT COUNT(*) AS rows_after_rollback FROM order_items;
rows_after_rollback
8

Points interviewers look for:

  • TRUNCATE takes a stronger lock than DELETE.
  • TRUNCATE refuses tables referenced by foreign keys unless CASCADE is given.
  • TRUNCATE ... RESTART IDENTITY resets identity sequences; DELETE does not.
  • DROP removes indexes, constraints and grants as well; recreating it needs the full DDL.
sql
CREATE TABLE customers (
  id      INTEGER PRIMARY KEY,
  name    TEXT NOT NULL,
  country TEXT
);
CREATE TABLE orders (
  id          INTEGER PRIMARY KEY,
  customer_id INTEGER REFERENCES customers(id),
  order_date  TEXT NOT NULL,
  status      TEXT NOT NULL
);
CREATE TABLE order_items (
  order_id   INTEGER REFERENCES orders(id),
  product    TEXT NOT NULL,
  qty        INTEGER NOT NULL,
  unit_price INTEGER NOT NULL
);
INSERT INTO customers VALUES (1,'Ana','Spain'),(2,'Bilal','UAE'),(3,'Chloe','France'),(4,'Dev','India');
INSERT INTO orders VALUES
  (101,1,'2026-01-05','shipped'),(102,1,'2026-02-11','shipped'),
  (103,2,'2026-02-14','cancelled'),(104,3,'2026-03-01','shipped'),
  (105,2,'2026-03-09','pending'),(106,NULL,'2026-03-12','shipped');
INSERT INTO order_items VALUES
  (101,'Notebook',2,4),(101,'Pen',5,1),(102,'Bag',1,30),(103,'Pen',10,1),
  (104,'Notebook',3,4),(104,'Bag',1,30),(105,'Lamp',1,25),(106,'Pen',2,1);

-- error on purpose
TRUNCATE TABLE order_items;

DELETE FROM order_items;
SELECT COUNT(*) AS rows_left FROM order_items;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • DELETE removes rows and fires triggers
  • TRUNCATE empties a table fast without row triggers
  • TRUNCATE is transactional in PostgreSQL
  • DROP removes the table definition
  • SQLite has no TRUNCATE

Common mistakes

  • Assuming TRUNCATE can never be rolled back
  • Using DROP to empty a table and losing grants and indexes

Follow-ups

  • Why does TRUNCATE need a stronger lock?
  • What does RESTART IDENTITY do?

Tips

  • Mention locks and triggers
194.sql-0194Mediummid

How do you swap the values of two columns in every row with a single UPDATE?

Write UPDATE t SET a = b, b = a. In standard SQL, SQLite and PostgreSQL, every expression on the right side sees the row's old values, so the swap works without a temporary variable. MySQL evaluates assignments left to right and would set both columns to the old b (not run here).

Full answer
sql
CREATE TABLE pairs (id INTEGER PRIMARY KEY, a INTEGER, b INTEGER);
INSERT INTO pairs VALUES (1, 10, 20), (2, 30, 40);
UPDATE pairs SET a = b, b = a;
SELECT * FROM pairs ORDER BY id;
idab
12010
24030

Both assignments read the values from before the update, so the two columns trade places.

PostgreSQL agrees:

sql
CREATE TABLE pairs (id int PRIMARY KEY, a int, b int);
INSERT INTO pairs VALUES (1, 10, 20), (2, 30, 40);
UPDATE pairs SET a = b, b = a;
SELECT * FROM pairs ORDER BY id;
idab
12010
24030

The same rule makes SET qty = qty + 1, total = qty * price use the old qty in the second expression. Write such updates with that in mind, or compute from the new value explicitly (total = (qty + 1) * price).

sql
CREATE TABLE pairs (id INTEGER PRIMARY KEY, a INTEGER, b INTEGER);
INSERT INTO pairs VALUES (1, 10, 20), (2, 30, 40);
UPDATE pairs SET a = b, b = a;
SELECT * FROM pairs ORDER BY id;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • Right-hand expressions see old row values
  • SET a = b, b = a swaps in one statement
  • Later assignments do not see earlier ones
  • MySQL differs and evaluates left to right

Common mistakes

  • Using a temporary column for a swap that one UPDATE can do
  • Expecting a second assignment to use the first one's new value

Follow-ups

  • How would you swap two rows' values, such as ranks 1 and 2?
  • What does SET qty = qty + 1, total = qty * price compute?

Tips

  • State the old-values rule
195.sql-0195Hardsenior

What does MERGE do in PostgreSQL 15+, and how does it compare with INSERT ... ON CONFLICT?

MERGE compares a source with a target on a join condition and runs different actions for matched and unmatched rows: UPDATE, DELETE, INSERT or DO NOTHING. It can delete as part of the sync, which ON CONFLICT cannot. ON CONFLICT relies on a unique index and handles concurrent inserts more safely. SQLite does not support MERGE.

Full answer
sql
CREATE TABLE stock (sku text PRIMARY KEY, qty int);
CREATE TABLE incoming (sku text, qty int);
INSERT INTO stock VALUES ('pen', 10), ('lamp', 2);
INSERT INTO incoming VALUES ('pen', 15), ('lamp', 0), ('bag', 4);
MERGE INTO stock s USING incoming i ON s.sku = i.sku
WHEN MATCHED AND i.qty = 0 THEN DELETE
WHEN MATCHED THEN UPDATE SET qty = i.qty
WHEN NOT MATCHED THEN INSERT (sku, qty) VALUES (i.sku, i.qty);
SELECT * FROM stock ORDER BY sku;
skuqty
bag4
pen15

'pen' matched and was updated, 'lamp' matched with qty 0 and was deleted, and 'bag' did not match and was inserted. One statement applied the whole change set from incoming.

SQLite rejects the syntax:

sql
CREATE TABLE stock (sku TEXT PRIMARY KEY, qty INTEGER);
CREATE TABLE incoming (sku TEXT, qty INTEGER);
MERGE INTO stock s USING incoming i ON s.sku = i.sku
WHEN MATCHED THEN UPDATE SET qty = i.qty;
-- error on purpose
text
Error: near "MERGE": syntax error

Choosing between them:

  • ON CONFLICT for single-row or batch upserts keyed by a unique constraint, especially under concurrent writers.
  • MERGE for syncing a staging table into a target, with deletes or several conditional branches.

PostgreSQL's documentation notes that MERGE can still raise unique violations when concurrent sessions insert the same key, which ON CONFLICT is designed to handle.

sql
-- error on purpose
CREATE TABLE stock (sku TEXT PRIMARY KEY, qty INTEGER);
CREATE TABLE incoming (sku TEXT, qty INTEGER);
MERGE INTO stock s USING incoming i ON s.sku = i.sku
WHEN MATCHED THEN UPDATE SET qty = i.qty;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • MERGE runs actions for matched and unmatched rows
  • It can UPDATE, DELETE or INSERT in one statement
  • PostgreSQL 15+ supports it; SQLite does not
  • ON CONFLICT handles concurrent inserts more safely

Common mistakes

  • Assuming MERGE is concurrency-safe like ON CONFLICT
  • Matching on a non-unique column and updating a row twice

Follow-ups

  • How would you sync a nightly price file into a products table?
  • What does WHEN NOT MATCHED BY SOURCE do in PostgreSQL 17?

Tips

  • Describe the sync use case
196.sql-0196Easyfresher

An UPDATE meant for one customer changed every row. What usually causes this, and how do you protect against it?

The WHERE clause was missing, or it was always true, for example WHERE id = id or a condition on a joined table that did not filter the target. Protect yourself by running the WHERE as a SELECT first, wrapping manual changes in a transaction and checking the affected row count before COMMIT.

Full answer
sql
CREATE TABLE customers (
  id      INTEGER PRIMARY KEY,
  name    TEXT NOT NULL,
  country TEXT
);
CREATE TABLE orders (
  id          INTEGER PRIMARY KEY,
  customer_id INTEGER REFERENCES customers(id),
  order_date  TEXT NOT NULL,
  status      TEXT NOT NULL
);
CREATE TABLE order_items (
  order_id   INTEGER REFERENCES orders(id),
  product    TEXT NOT NULL,
  qty        INTEGER NOT NULL,
  unit_price INTEGER NOT NULL
);
INSERT INTO customers VALUES (1,'Ana','Spain'),(2,'Bilal','UAE'),(3,'Chloe','France'),(4,'Dev','India');
INSERT INTO orders VALUES
  (101,1,'2026-01-05','shipped'),(102,1,'2026-02-11','shipped'),
  (103,2,'2026-02-14','cancelled'),(104,3,'2026-03-01','shipped'),
  (105,2,'2026-03-09','pending'),(106,NULL,'2026-03-12','shipped');
INSERT INTO order_items VALUES
  (101,'Notebook',2,4),(101,'Pen',5,1),(102,'Bag',1,30),(103,'Pen',10,1),
  (104,'Notebook',3,4),(104,'Bag',1,30),(105,'Lamp',1,25),(106,'Pen',2,1);

Here the statement runs without a WHERE inside a transaction. Before ROLLBACK, every customer in this session reads Portugal; after it, the final SELECT shows the original countries again:

sql
BEGIN;
UPDATE customers SET country = 'Portugal';
SELECT id, country FROM customers ORDER BY id;
ROLLBACK;
SELECT id, country FROM customers ORDER BY id;
idcountry
1Spain
2UAE
3France
4India

Had it run in autocommit mode, the change would already be permanent, and the only way back would be a backup or a manual repair.

Habits that prevent this:

  • Write the WHERE first, as a SELECT, and check the row count.
  • Start manual sessions with BEGIN, and COMMIT only after checking.
  • Use RETURNING to see exactly which rows changed.
  • Some clients have a safe-updates mode that rejects UPDATE without WHERE (for example MySQL's --safe-updates, not run here).
sql
CREATE TABLE customers (
  id      INTEGER PRIMARY KEY,
  name    TEXT NOT NULL,
  country TEXT
);
CREATE TABLE orders (
  id          INTEGER PRIMARY KEY,
  customer_id INTEGER REFERENCES customers(id),
  order_date  TEXT NOT NULL,
  status      TEXT NOT NULL
);
CREATE TABLE order_items (
  order_id   INTEGER REFERENCES orders(id),
  product    TEXT NOT NULL,
  qty        INTEGER NOT NULL,
  unit_price INTEGER NOT NULL
);
INSERT INTO customers VALUES (1,'Ana','Spain'),(2,'Bilal','UAE'),(3,'Chloe','France'),(4,'Dev','India');
INSERT INTO orders VALUES
  (101,1,'2026-01-05','shipped'),(102,1,'2026-02-11','shipped'),
  (103,2,'2026-02-14','cancelled'),(104,3,'2026-03-01','shipped'),
  (105,2,'2026-03-09','pending'),(106,NULL,'2026-03-12','shipped');
INSERT INTO order_items VALUES
  (101,'Notebook',2,4),(101,'Pen',5,1),(102,'Bag',1,30),(103,'Pen',10,1),
  (104,'Notebook',3,4),(104,'Bag',1,30),(105,'Lamp',1,25),(106,'Pen',2,1);

BEGIN;
UPDATE customers SET country = 'Portugal';
SELECT id, country FROM customers ORDER BY id;
ROLLBACK;
SELECT id, country FROM customers ORDER BY id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • A missing or always-true WHERE updates all rows
  • Preview with SELECT using the same WHERE
  • Use a transaction and check the count before COMMIT
  • RETURNING shows the affected rows

Common mistakes

  • Running ad hoc updates in autocommit mode
  • Copying a WHERE that refers to the wrong alias

Follow-ups

  • How would you recover if the change was already committed?
  • What does a point-in-time restore involve?

Tips

  • Describe a safe manual-change routine
197.sql-0197Easyfresher

What is normalization, and which problems does it solve?

Normalization organizes tables so each fact is stored once, by splitting data according to its dependencies. It prevents update anomalies (changing a fact in one row but not another), insert anomalies (being unable to record a fact without an unrelated one) and delete anomalies (losing a fact when deleting another).

Full answer

Picture one wide table of enrolments that also repeats the student's city and the course title on every row.

  • Update anomaly: Asha moves, and the city must be changed on every one of her enrolment rows. Miss one and the data contradicts itself.
  • Insert anomaly: a new course cannot be recorded until someone enrols, because the row needs a student.
  • Delete anomaly: removing the last enrolment in Ethics also deletes the only record that Ethics exists.

Splitting into students, courses and enrolments stores each fact once and connects them by keys, which is how the SCHOOL sample schema in this bank is laid out.

The normal forms (1NF, 2NF, 3NF, BCNF) are a checklist for this process. Each removes one kind of redundant dependency. Most transactional systems aim for 3NF or BCNF and denormalize selectively for read performance.

Key points

  • Normalization stores each fact once
  • It prevents update, insert and delete anomalies
  • Tables are split by functional dependencies
  • Most OLTP schemas target 3NF or BCNF

Common mistakes

  • Defining normalization as 'splitting tables' without saying why
  • Normalizing so far that simple reads need many joins without need

Follow-ups

  • What does 1NF require?
  • When is denormalization justified?

Tips

  • Give one example of each anomaly
198.sql-0198Easyfresher

What does first normal form (1NF) require? Is a column holding 'sql,joins,cte' a violation?

1NF requires that each column holds a single atomic value per row and that there are no repeating groups such as tag1, tag2, tag3 columns. A comma-separated list in one column violates 1NF because the database cannot index, constrain or join the individual values. Store one row per value in a child table instead.

Full answer

With a list in a column, simple questions get hard. "Which posts have the tag joins?" turns into a LIKE search that also matches 'self-joins', cannot use an index, and cannot enforce that tags exist.

A child table fixes it:

sql
CREATE TABLE post_tags (post_id INTEGER, tag TEXT, PRIMARY KEY (post_id, tag));
INSERT INTO post_tags VALUES (1,'sql'),(1,'joins'),(1,'cte'),(2,'self-joins');
SELECT post_id FROM post_tags WHERE tag = 'joins';
post_id
1

Now each tag is a row, a primary key prevents duplicates per post, and a foreign key could reference a tags table.

Atomic depends on how the data is used. A full address stored as one text value is fine if it is only ever printed; it is a problem if reports group by city. JSON and array columns are allowed by modern engines and are a deliberate trade-off, not automatically wrong, but they lose the protections listed above.

sql
CREATE TABLE post_tags (post_id INTEGER, tag TEXT, PRIMARY KEY (post_id, tag));
INSERT INTO post_tags VALUES (1,'sql'),(1,'joins'),(1,'cte'),(2,'self-joins');
SELECT post_id FROM post_tags WHERE tag = 'joins';

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • One atomic value per column per row
  • No repeating groups like tag1, tag2, tag3
  • Lists in a column cannot be indexed, constrained or joined
  • Atomicity depends on how the data is queried

Common mistakes

  • Storing comma-separated ids and joining with LIKE
  • Adding numbered columns whenever more values are needed

Follow-ups

  • How would you migrate a comma-separated column to a child table?
  • When is a JSON column a reasonable choice?

Tips

  • Show the child-table version
199.sql-0199Mediummid

Explain second normal form with an example of a partial dependency.

A table is in 2NF when it is in 1NF and no non-key column depends on only part of a composite key. In enrolments(student_id, course_id, marks, course_title), course_title depends on course_id alone, which is a partial dependency. Move course_title into a courses table keyed by course_id.

Full answer

Take a table keyed by (student_id, course_id):

text
student_id | course_id | marks | course_title
1          | 10        | 88    | Databases
2          | 10        | 75    | Databases

marks depends on the whole key: it is one student's mark in one course. course_title depends only on course_id, so it repeats for every student in the course. Renaming the course means updating many rows, which is the update anomaly again.

The 2NF fix splits the table: enrolments(student_id, course_id, marks) and courses(course_id, title).

2NF only matters for composite keys. A table with a single-column key that is in 1NF is automatically in 2NF, because there is no "part" of the key to depend on.

Key points

  • 2NF removes partial dependencies on a composite key
  • Every non-key column must depend on the whole key
  • Move partially dependent columns into their own table
  • Single-column keys cannot have partial dependencies

Common mistakes

  • Confusing partial dependencies with transitive ones
  • Claiming a single-column key table can violate 2NF

Follow-ups

  • What does 3NF add?
  • Is a surrogate id a way to avoid 2NF?

Tips

  • Point at the key part each column depends on
200.sql-0200Mediummid

What is a transitive dependency, and how does third normal form remove it?

A transitive dependency is when a non-key column depends on another non-key column rather than on the key directly, for example employees(id, dept_id, dept_name), where dept_name depends on dept_id. 3NF requires 2NF plus no transitive dependencies, so dept_name moves to a departments table.

Full answer

In employees(id, name, dept_id, dept_name), the chain is id → dept_id → dept_name. Every Engineering employee repeats 'Engineering'; renaming the department means updating all of them, and a department with no employees cannot be stored.

The fix keeps dept_id in employees and moves the name:

text
employees(id, name, dept_id)
departments(id, name)

This is the STAFF sample schema used throughout this bank. A short way to remember 3NF: every non-key column depends on "the key, the whole key, and nothing but the key". 1NF gives a key, 2NF covers "the whole key", and 3NF covers "nothing but the key".

Key points

  • Transitive: key → non-key → another non-key
  • 3NF = 2NF plus no transitive dependencies
  • Move the dependent columns to a table keyed by the middle column
  • 'The key, the whole key, and nothing but the key'

Common mistakes

  • Calling every repeated value a 3NF violation
  • Removing a needed foreign key along with the dependent column

Follow-ups

  • How does BCNF differ from 3NF?
  • Is storing a city and a postal code together a 3NF problem?

Tips

  • Use the employees and departments example