ποΈ SQL Β· Topic 17 of 20
Tables & Constraints β SQL Questions with Answers
30 practice questions on Tables & Constraints, 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.
2 easy Β· 16 medium Β· 12 hard Β· Part of SQL: Databases from basics to window functions - 20 topics.
Medium questions (16)
Q2. medium
What does a PRIMARY KEY constraint guarantee?
- A The column(s) are UNIQUE and NOT NULL - uniquely identifying each row
- B The column is the first one
- C The column is indexed only
- D The column is encrypted
Answer: A β The column(s) are UNIQUE and NOT NULL - uniquely identifying each row
A primary key combines UNIQUE + NOT NULL and is automatically indexed. Every table should normally have one to identify rows unambiguously.
PRIMARY KEYConstraints
Q3. medium
What does a FOREIGN KEY constraint enforce?
FOREIGN KEY (customer_id) REFERENCES customers(id)
- A That the value must exist as a key in the referenced table (referential integrity)
- B That the column is unique
- C That the column is NOT NULL
- D Encryption
Answer: A β That the value must exist as a key in the referenced table (referential integrity)
A foreign key prevents orphan rows: you cannot insert an order for a customer_id that does not exist, and (with RESTRICT) cannot delete a referenced customer.
FOREIGN KEYReferential integrity
Q4. medium
What does a UNIQUE constraint do?
- A Ensures no two rows have the same value in that column (but allows NULLs, usually)
- B Makes the column the primary key
- C Sorts the column
- D Encrypts values
Answer: A β Ensures no two rows have the same value in that column (but allows NULLs, usually)
UNIQUE enforces distinct values - ideal for emails or usernames. Unlike PRIMARY KEY, a table can have several UNIQUE constraints, and they typically permit one (or more) NULLs.
UNIQUEConstraints
Q6. medium
What does NOT NULL enforce?
- A The column must always have a value - inserts/updates cannot leave it NULL
- B The column cannot be zero
- C The column is unique
- D The column is a key
Answer: A β The column must always have a value - inserts/updates cannot leave it NULL
NOT NULL rejects missing values, guaranteeing the data is present. Pair it with a DEFAULT so inserts that omit the column still succeed.
NOT NULLConstraints
Q7. medium
What does a CHECK constraint do?
price DECIMAL(10,2) CHECK (price >= 0)
- A Enforces a custom condition on values, e.g. CHECK (age >= 0)
- B Checks spelling
- C Indexes the column
- D Runs a query
Answer: A β Enforces a custom condition on values, e.g. CHECK (age >= 0)
CHECK validates data at write time: prices non-negative, status in a set, end date after start date. The database rejects any row that fails the condition.
CHECKValidation
Q8. medium
What does a DEFAULT do?
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
- A Supplies a value automatically when an insert omits the column
- B Sets the primary key
- C Makes the column unique
- D Deletes old values
Answer: A β Supplies a value automatically when an insert omits the column
DEFAULT 'pending' or DEFAULT CURRENT_TIMESTAMP fills in a value so callers need not specify it. Combined with NOT NULL, it guarantees a usable value in every row.
DEFAULT
Q11. medium
How do you ADD a column to an existing table?
- A ALTER TABLE t ADD COLUMN email VARCHAR(100);
- B UPDATE TABLE ADD email
- C CREATE COLUMN email
- D INSERT COLUMN email
Answer: A β ALTER TABLE t ADD COLUMN email VARCHAR(100);
ALTER TABLE changes structure. You can add, drop or modify columns and constraints. On large tables, adding a column can lock or rewrite the table, so plan migrations carefully.
ALTER TABLEMigrations
Q12. medium
How do you remove a column?
- A ALTER TABLE t DROP COLUMN email;
- B DELETE COLUMN email
- C REMOVE email
- D DROP email FROM t
Answer: A β ALTER TABLE t DROP COLUMN email;
DROP COLUMN permanently removes the column and its data. This is irreversible without a backup, so confirm it is truly unused first.
ALTER TABLEDROP COLUMN
Q15. medium
How do you make a column auto-increment?
id INT AUTO_INCREMENT PRIMARY KEY -- MySQL
- A AUTO_INCREMENT (MySQL), SERIAL / GENERATED AS IDENTITY (PostgreSQL), or IDENTITY (SQL Server)
- B AUTO NUMBER everywhere
- C INCREMENT BY 1
- D It is automatic
Answer: A β AUTO_INCREMENT (MySQL), SERIAL / GENERATED AS IDENTITY (PostgreSQL), or IDENTITY (SQL Server)
These generate a unique increasing value for each new row, typically for surrogate primary keys. Syntax varies by database, but the concept is universal.
Auto-incrementSurrogate key
Q17. medium
Can you name a constraint?
- A Yes - CONSTRAINT chk_price CHECK (price >= 0) - named constraints are easier to reference and drop
- B No, constraints are anonymous
- C Only primary keys can be named
- D Names are random
Answer: A β Yes - CONSTRAINT chk_price CHECK (price >= 0) - named constraints are easier to reference and drop
Naming constraints gives clearer error messages and lets you drop or alter a specific one later: ALTER TABLE ... DROP CONSTRAINT chk_price.
Named constraints
Q19. medium
What does CREATE TABLE IF NOT EXISTS do?
- A Creates the table only if it does not already exist - avoiding an error on re-run
- B Always recreates the table
- C Deletes the table first
- D Nothing
Answer: A β Creates the table only if it does not already exist - avoiding an error on re-run
Useful in setup scripts and migrations so re-running them does not fail. Similarly, DROP TABLE IF EXISTS avoids errors when the table is absent.
IF NOT EXISTSIdempotency
Q21. medium
How do you rename a table?
- A ALTER TABLE old_name RENAME TO new_name; (syntax varies slightly)
- B RENAME COLUMN
- C UPDATE TABLE NAME
- D Tables cannot be renamed
Answer: A β ALTER TABLE old_name RENAME TO new_name; (syntax varies slightly)
Most databases support renaming via ALTER TABLE ... RENAME TO (MySQL also has RENAME TABLE). Be aware that views and code referencing the old name will break.
ALTER TABLERENAME
Q23. medium
What happens if you insert a row that violates a CHECK constraint?
- A The insert is rejected with a constraint-violation error
- B It inserts anyway
- C The value is corrected
- D The constraint is dropped
Answer: A β The insert is rejected with a constraint-violation error
Constraints reject invalid data rather than silently accepting it - exactly the protection you want. Handle the error gracefully in the application.
CHECKErrors
Q25. medium
What is a self-referencing foreign key?
- A A foreign key that references the same table - e.g. employees.manager_id -> employees.id
- B A key that references itself literally
- C An invalid key
- D A primary key
Answer: A β A foreign key that references the same table - e.g. employees.manager_id -> employees.id
It models hierarchies within one table. The top of the hierarchy (a CEO) has a NULL in the self-referencing column since they have no parent.
Self-referenceHierarchies
Q27. medium
How do you change a column to allow (or disallow) NULL?
- A ALTER TABLE t ALTER COLUMN c SET/DROP NOT NULL (or MODIFY in MySQL)
- B You cannot change nullability
- C DROP the column
- D Recreate the table only
Answer: A β ALTER TABLE t ALTER COLUMN c SET/DROP NOT NULL (or MODIFY in MySQL)
Adding NOT NULL requires that no existing rows are NULL, or the change fails. Syntax differs: PostgreSQL uses SET/DROP NOT NULL; MySQL uses MODIFY COLUMN.
ALTER TABLENOT NULL
Q29. medium
Which constraint would ensure an email column has no duplicates and is always provided?
- A UNIQUE combined with NOT NULL
- B PRIMARY KEY only
- C CHECK only
- D DEFAULT only
Answer: A β UNIQUE combined with NOT NULL
UNIQUE stops duplicates and NOT NULL stops missing values. Together they guarantee every row has a distinct, present email - without making it the primary key.
UNIQUENOT NULL
Hard questions (12)
Q5. hard
How does UNIQUE treat NULL values?
- A In most databases multiple NULLs are allowed (NULL is 'unknown', not equal to another NULL)
- B Only one NULL is allowed
- C NULLs are forbidden
- D NULLs cause errors
Answer: A β In most databases multiple NULLs are allowed (NULL is 'unknown', not equal to another NULL)
Because NULL != NULL, a UNIQUE column usually permits many NULLs (SQL Server allows only one). If you need every row to have a distinct real value, combine UNIQUE with NOT NULL.
UNIQUENULL
Q9. hard
What does ON DELETE CASCADE do on a foreign key?
- A Automatically deletes child rows when the referenced parent row is deleted
- B Blocks the delete
- C Sets children to NULL
- D Nothing
Answer: A β Automatically deletes child rows when the referenced parent row is deleted
CASCADE keeps data consistent by removing dependents (deleting an order deletes its order_items). Use carefully - it can remove more than you expect. Alternatives: RESTRICT (block) and SET NULL.
ON DELETE CASCADEForeign keys
Q10. hard
What is the difference between ON DELETE RESTRICT and CASCADE?
- A RESTRICT blocks deleting a parent that has children; CASCADE deletes the children too
- B They are identical
- C RESTRICT deletes children
- D CASCADE blocks the delete
Answer: A β RESTRICT blocks deleting a parent that has children; CASCADE deletes the children too
RESTRICT (and NO ACTION) protect data by refusing the delete. CASCADE propagates it. SET NULL orphans children by nulling their foreign key. Choose based on business rules.
Referential actions
Q14. hard
What is a composite primary key defined in DDL?
- A PRIMARY KEY (col1, col2) - the combination is unique, though neither column need be alone
- B Two separate primary keys
- C A foreign key
- D An index
Answer: A β PRIMARY KEY (col1, col2) - the combination is unique, though neither column need be alone
Common in junction tables: PRIMARY KEY (student_id, course_id) means a student can enrol in a course only once, though each id repeats across rows.
Composite keyJunction table
Q16. hard
What is the difference between a natural key and a surrogate key?
- A A natural key uses meaningful data (email, ISBN); a surrogate key is a system-generated id with no business meaning
- B They are identical
- C Natural keys are always integers
- D Surrogate keys must be text
Answer: A β A natural key uses meaningful data (email, ISBN); a surrogate key is a system-generated id with no business meaning
Surrogate keys (auto-increment ids) are stable and simple, so they are the common default. Natural keys carry meaning but can change, which complicates foreign keys.
Surrogate keyNatural key
Q18. hard
How do you add a foreign key to an EXISTING table?
- A ALTER TABLE orders ADD CONSTRAINT fk_cust FOREIGN KEY (customer_id) REFERENCES customers(id);
- B You must recreate the table
- C CREATE FOREIGN KEY
- D It is impossible
Answer: A β ALTER TABLE orders ADD CONSTRAINT fk_cust FOREIGN KEY (customer_id) REFERENCES customers(id);
ALTER TABLE ... ADD CONSTRAINT adds it after the fact. The database first checks that all existing values satisfy the constraint, or the ALTER fails.
ALTER TABLEFOREIGN KEY
Q20. hard
Why are constraints better than validating only in application code?
- A The database enforces them for EVERY client and script - a last line of defence that never gets bypassed
- B They are faster to write
- C Application checks are always enough
- D Constraints are optional decoration
Answer: A β The database enforces them for EVERY client and script - a last line of defence that never gets bypassed
Multiple apps, admin scripts and manual edits all touch a database. Constraints guarantee integrity regardless of how the data arrives, whereas app validation can be skipped.
Data integrityDefence in depth
Q22. hard
What does a CHECK constraint referencing two columns enforce?
- A A relationship between them, e.g. CHECK (end_date >= start_date)
- B Only single-column checks are allowed
- C It indexes both
- D Nothing
Answer: A β A relationship between them, e.g. CHECK (end_date >= start_date)
Multi-column CHECKs validate cross-field rules at the database level - ensuring, for instance, that a booking's end is never before its start.
CHECKCross-column
Q24. hard
Why index foreign key columns?
- A Joins and cascade checks scan them frequently; without an index those operations are slow
- B Foreign keys index automatically everywhere
- C It is never needed
- D To save space
Answer: A β Joins and cascade checks scan them frequently; without an index those operations are slow
Primary keys are indexed automatically, but foreign keys often are not (except in some databases). Indexing them speeds joins and makes ON DELETE checks efficient.
IndexesForeign keys
Q26. hard
What is the effect of a DEFERRABLE constraint?
- A Its check can be postponed until the transaction commits, allowing temporary violations mid-transaction
- B It disables the constraint
- C It runs the constraint twice
- D Nothing
Answer: A β Its check can be postponed until the transaction commits, allowing temporary violations mid-transaction
Deferrable foreign keys (PostgreSQL, Oracle) let you insert rows in an order that would momentarily violate the constraint, as long as everything is consistent at COMMIT - useful for circular references.
Deferrable constraintsTransactions
Q28. hard
What is a generated (computed) column?
total DECIMAL(12,2) GENERATED ALWAYS AS (price * qty) STORED
- A A column whose value is derived from other columns by a formula, maintained automatically
- B A random column
- C A backup column
- D An index
Answer: A β A column whose value is derived from other columns by a formula, maintained automatically
GENERATED ALWAYS AS (price * quantity) STORED computes and stores a value from other columns. Great for search or indexing on derived data without app-side maintenance.
Generated columns
Q30. hard
Why prefer defining constraints at table creation over adding them later?
- A The table starts valid, and adding constraints later can fail on existing bad data or require costly full-table validation
- B It is faster to type
- C Later constraints are ignored
- D There is no difference
Answer: A β The table starts valid, and adding constraints later can fail on existing bad data or require costly full-table validation
Constraints defined upfront prevent bad data from ever entering. Adding them to a populated table forces a validation scan and may fail if pre-existing rows violate the rule.
DesignMigrations