ποΈ SQL Β· Topic 16 of 20
INSERT, UPDATE, DELETE β SQL Questions with Answers
30 practice questions on INSERT, UPDATE, DELETE, each with the correct answer and a clear explanation of why it is right. Read through them as revision notes, or take this topic as an interactive quiz to test yourself.
3 easy Β· 13 medium Β· 14 hard Β· Part of SQL: Databases from basics to window functions - 20 topics.
Medium questions (13)
Q2. medium
Why list column names in an INSERT?
- A It makes the insert robust to column additions/reordering and documents intent
- B It is required syntax
- C It is faster
- D No reason
Answer: A β It makes the insert robust to column additions/reordering and documents intent
INSERT INTO t VALUES (...) relies on exact column order and count. Naming columns lets you omit ones with defaults and survives schema changes.
INSERTBest practices
Q3. medium
How do you insert MULTIPLE rows in one statement?
- A INSERT INTO t (a, b) VALUES (1, 2), (3, 4), (5, 6);
- B Three separate INSERTs only
- C INSERT MANY
- D It is not possible
Answer: A β INSERT INTO t (a, b) VALUES (1, 2), (3, 4), (5, 6);
A multi-row VALUES list inserts several rows at once - far faster than many single inserts because it is one statement and one round trip.
INSERTBulk insert
Q7. medium
How do you update multiple columns at once?
- A SET col1 = v1, col2 = v2 - comma-separated assignments
- B SET col1 = v1 AND col2 = v2
- C SET (col1, col2)
- D Two UPDATE statements only
Answer: A β SET col1 = v1, col2 = v2 - comma-separated assignments
One UPDATE can change many columns: SET status = 'shipped', shipped_at = NOW(). Use AND only in the WHERE clause, never in SET.
UPDATESET
Q12. medium
What is the safest habit before running a DELETE or UPDATE?
- A Run a SELECT with the SAME WHERE clause first to preview affected rows
- B Run it immediately
- C Disable indexes
- D Delete a backup
Answer: A β Run a SELECT with the SAME WHERE clause first to preview affected rows
Previewing shows exactly which rows will change. Combined with a transaction (BEGIN ... ROLLBACK if wrong), it prevents most accidental data loss.
SafetySELECT
Q14. medium
How do you increment a column's value?
- A UPDATE t SET views = views + 1 WHERE id = 5;
- B UPDATE t SET views++
- C INCREMENT views
- D It cannot be done
Answer: A β UPDATE t SET views = views + 1 WHERE id = 5;
Reference the column in its own SET expression. The database reads the current value and writes the new one atomically within the statement.
UPDATEExpressions
Q16. medium
What does the RETURNING clause do (PostgreSQL)?
INSERT INTO users (name) VALUES ('Ana') RETURNING id;
- A Returns the inserted/updated/deleted rows - e.g. to get an auto-generated id
- B Rolls back the change
- C Returns nothing
- D Repeats the statement
Answer: A β Returns the inserted/updated/deleted rows - e.g. to get an auto-generated id
INSERT ... RETURNING id gives back the new primary key in one round trip. SQL Server uses the OUTPUT clause for the same purpose.
RETURNINGOUTPUT
Q18. medium
How do you insert a row using DEFAULT values?
INSERT INTO orders (customer_id) VALUES (5); -- status uses its default
- A Omit those columns from the INSERT, or use the keyword DEFAULT
- B You must specify every column
- C Insert NULL always
- D It is impossible
Answer: A β Omit those columns from the INSERT, or use the keyword DEFAULT
Columns with a DEFAULT (or that allow NULL, or auto-increment) can be left out of the column list. The database fills them in automatically.
DEFAULTINSERT
Q20. medium
What does INSERT do if a UNIQUE constraint is violated?
- A It fails with a unique-constraint error unless you handle it (e.g. with ON CONFLICT)
- B It overwrites silently
- C It inserts a duplicate
- D It updates the row
Answer: A β It fails with a unique-constraint error unless you handle it (e.g. with ON CONFLICT)
Constraints protect integrity by rejecting the insert. UPSERT syntax lets you decide to update instead, or IGNORE to skip the conflicting row.
UNIQUEConstraints
Q22. medium
How do you delete duplicate rows keeping one copy?
DELETE FROM t WHERE id IN (
SELECT id FROM (SELECT id, ROW_NUMBER() OVER (PARTITION BY email ORDER BY id) rn FROM t) x WHERE rn > 1
);
- A Use a window function (ROW_NUMBER) or a self join to identify extras, then DELETE them
- B DELETE DISTINCT
- C TRUNCATE the table
- D It is impossible
Answer: A β Use a window function (ROW_NUMBER) or a self join to identify extras, then DELETE them
Number the duplicates with ROW_NUMBER() OVER (PARTITION BY key) and delete those with rn > 1. A very common data-cleaning task.
DuplicatesROW_NUMBER
Q24. medium
What does DELETE return or affect besides removing rows?
- A It reports the number of rows affected and can fire triggers and cascade to related tables
- B Only removes rows silently
- C It returns the rows
- D Nothing else
Answer: A β It reports the number of rows affected and can fire triggers and cascade to related tables
The affected-row count confirms the scope of the operation. Foreign key cascades and triggers may perform additional work - worth knowing before running big deletes.
DELETETriggersCascade
Q26. medium
How do you empty a table but keep its structure quickly?
- A TRUNCATE TABLE t;
- B DROP TABLE t;
- C DELETE TABLE t;
- D CLEAR t;
Answer: A β TRUNCATE TABLE t;
TRUNCATE removes all rows almost instantly and resets auto-increment counters (in most databases), while leaving the table definition intact.
TRUNCATE
Q28. medium
How do you set a column to NULL?
- A UPDATE t SET middle_name = NULL WHERE id = 5;
- B DELETE middle_name
- C SET middle_name = ''
- D REMOVE middle_name
Answer: A β UPDATE t SET middle_name = NULL WHERE id = 5;
Assigning NULL clears a value (if the column allows NULL). This differs from '' (empty string) - NULL means 'no value', empty string means 'a known blank'.
NULLUPDATE
Q30. medium
Which clause limits how many rows an UPDATE or DELETE affects (MySQL)?
- A LIMIT - e.g. DELETE FROM logs WHERE ... LIMIT 1000 for batching
- B TOP only
- C FETCH only
- D You cannot limit them
Answer: A β LIMIT - e.g. DELETE FROM logs WHERE ... LIMIT 1000 for batching
MySQL allows LIMIT on DELETE/UPDATE for batch processing. SQL Server uses DELETE TOP (n). Batching large modifications reduces locking and log growth.
BatchingLIMIT
Hard questions (14)
Q4. hard
How do you insert rows from a SELECT (copying data)?
- A INSERT INTO archive (id, total) SELECT id, total FROM orders WHERE year < 2020;
- B COPY orders TO archive
- C INSERT SELECT INTO
- D It cannot be done
Answer: A β INSERT INTO archive (id, total) SELECT id, total FROM orders WHERE year < 2020;
INSERT ... SELECT populates a table from a query - used for archiving, summarising and ETL. The SELECT's columns must line up with the target columns.
INSERT SELECTETL
Q6. hard
What is the danger of UPDATE without a WHERE clause?
- A It updates EVERY row in the table
- B It errors
- C It updates nothing
- D It updates one row
Answer: A β It updates EVERY row in the table
UPDATE students SET marks = 0 with no WHERE sets every student's marks to 0. Always double-check the WHERE - and wrap risky changes in a transaction you can roll back.
- The classic 'I forgot the WHERE' disaster.
UPDATESafety
Q8. hard
How do you UPDATE using values from another table?
UPDATE orders o SET total = s.amt
FROM summary s WHERE s.order_id = o.id; -- PostgreSQL
- A UPDATE ... SET col = (SELECT ...) or a JOIN-based update (UPDATE ... FROM in PostgreSQL)
- B You cannot reference other tables
- C Use INSERT
- D Use UNION
Answer: A β UPDATE ... SET col = (SELECT ...) or a JOIN-based update (UPDATE ... FROM in PostgreSQL)
A correlated subquery or a JOIN in the UPDATE lets you set values based on related data - for example, updating a cached total from a summary table.
UPDATEJOIN
Q10. hard
What is the difference between DELETE and TRUNCATE?
- A DELETE removes rows one by one (logged, can have WHERE, fires triggers); TRUNCATE instantly empties the whole table
- B They are identical
- C TRUNCATE can use WHERE
- D DELETE is faster for whole tables
Answer: A β DELETE removes rows one by one (logged, can have WHERE, fires triggers); TRUNCATE instantly empties the whole table
TRUNCATE is much faster for clearing an entire table because it deallocates data pages instead of deleting rows individually, but it cannot filter and usually cannot be rolled back the same way.
DELETETRUNCATE
Q11. hard
What is the difference between DELETE, TRUNCATE and DROP?
- A DELETE removes rows (optionally filtered), TRUNCATE empties the table, DROP removes the table itself
- B They are the same
- C DROP keeps the structure
- D TRUNCATE removes the table
Answer: A β DELETE removes rows (optionally filtered), TRUNCATE empties the table, DROP removes the table itself
DELETE and TRUNCATE keep the table (its columns and indexes remain); DROP TABLE deletes the entire object. Choose based on whether you need the empty table afterward.
DELETETRUNCATEDROP
Q13. hard
What is an UPSERT?
INSERT INTO counters (id, n) VALUES (1, 1)
ON CONFLICT (id) DO UPDATE SET n = counters.n + 1;
- A Insert a row, but UPDATE it instead if it already exists (INSERT ... ON CONFLICT / ON DUPLICATE KEY / MERGE)
- B A faster insert
- C Deleting then inserting
- D An error type
Answer: A β Insert a row, but UPDATE it instead if it already exists (INSERT ... ON CONFLICT / ON DUPLICATE KEY / MERGE)
UPSERT handles 'insert or update' atomically. PostgreSQL uses INSERT ... ON CONFLICT DO UPDATE; MySQL uses ON DUPLICATE KEY UPDATE; the standard is MERGE.
UPSERTON CONFLICT
Q15. hard
What happens to child rows when you DELETE a parent with a foreign key?
- A It depends on the FK's ON DELETE rule: RESTRICT blocks it, CASCADE deletes children, SET NULL nulls the reference
- B Children are always deleted
- C Nothing happens
- D It always errors
Answer: A β It depends on the FK's ON DELETE rule: RESTRICT blocks it, CASCADE deletes children, SET NULL nulls the reference
Referential actions defined on the foreign key control this. RESTRICT/NO ACTION protects data, CASCADE cleans up dependents, SET NULL orphans them safely.
Foreign keysON DELETE CASCADE
Q17. hard
Why can a large single DELETE be problematic?
- A It can lock rows, bloat the transaction log, and run long - batching (delete in chunks) is often safer
- B It is always fine
- C It never locks
- D It deletes too little
Answer: A β It can lock rows, bloat the transaction log, and run long - batching (delete in chunks) is often safer
Deleting millions of rows in one transaction holds locks and grows the log. Deleting in batches (e.g. 10,000 rows at a time) reduces contention and log pressure.
DELETEBatchingLocks
Q19. hard
What does a conditional UPDATE with CASE achieve?
- A Sets different values per row based on conditions in a single statement
- B It filters rows
- C It deletes rows
- D Nothing
Answer: A β Sets different values per row based on conditions in a single statement
UPDATE t SET tier = CASE WHEN spend > 1000 THEN 'gold' ELSE 'silver' END updates every row with the appropriate value in one pass.
UPDATECASE
Q21. hard
What is a soft delete?
- A Marking a row as deleted (e.g. deleted_at timestamp) instead of physically removing it
- B A slow DELETE
- C DELETE without WHERE
- D TRUNCATE
Answer: A β Marking a row as deleted (e.g. deleted_at timestamp) instead of physically removing it
Soft deletes preserve history and allow recovery: queries add WHERE deleted_at IS NULL. The trade-off is extra filtering and eventual cleanup of old rows.
Soft deleteAuditing
Q23. hard
Why should DML changes often be wrapped in a transaction?
- A So a multi-step change is all-or-nothing and can be rolled back if something goes wrong
- B To make it faster
- C Transactions are required for INSERT
- D No reason
Answer: A β So a multi-step change is all-or-nothing and can be rolled back if something goes wrong
BEGIN ... COMMIT groups related changes; ROLLBACK undoes them if an error occurs. This keeps data consistent - for example, debit one account and credit another together.
TransactionsAtomicity
Q25. hard
How do you copy a table's structure AND data into a new table?
- A CREATE TABLE new AS SELECT * FROM old; (CTAS)
- B COPY TABLE
- C INSERT INTO new
- D It is impossible
Answer: A β CREATE TABLE new AS SELECT * FROM old; (CTAS)
CREATE TABLE AS SELECT (CTAS) creates and fills a table in one step - handy for backups and staging. Note it usually does NOT copy indexes or constraints.
CTASCREATE TABLE
Q27. hard
What is the risk of updating a column used in the WHERE of the same statement?
- A Generally SQL applies the change atomically per the original match set, but semantics can surprise you - test carefully
- B It always loops forever
- C It is a syntax error
- D It never works
Answer: A β Generally SQL applies the change atomically per the original match set, but semantics can surprise you - test carefully
SQL evaluates the WHERE against the pre-update state within the statement, so it does not re-match rows mid-update. Still, such statements deserve careful testing on sample data.
UPDATESemantics
Q29. hard
Why is INSERT ... SELECT preferred over row-by-row inserts for bulk loads?
- A It is a single set-based operation - far fewer round trips and log entries than thousands of individual inserts
- B It is slower but safer
- C It skips constraints
- D There is no difference
Answer: A β It is a single set-based operation - far fewer round trips and log entries than thousands of individual inserts
Set-based operations let the database work in bulk. Looping single inserts from application code is dramatically slower due to per-statement overhead.
Bulk insertPerformance