πŸŽ“ Velnov

πŸ—„οΈ 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.

Key concepts in this topic

CREATE TABLEDDLPRIMARY KEYConstraintsFOREIGN KEYReferential integrityUNIQUENULLNOT NULLCHECKValidationDEFAULTON DELETE CASCADEForeign keysReferential actionsALTER TABLEMigrationsDROP COLUMNDROP TABLEComposite keyJunction tableAuto-incrementSurrogate keyNatural key

Jump to: Easy Β· Medium Β· Hard

Easy questions (2)

Q1. easy

Which statement creates a new table?

CREATE TABLE students (
  id INT PRIMARY KEY,
  name VARCHAR(50) NOT NULL
);
  1. A CREATE TABLE
  2. B NEW TABLE
  3. C MAKE TABLE
  4. D ADD TABLE

Answer: A β€” CREATE TABLE

CREATE TABLE name (column definitions) defines a table's structure - its columns, types and constraints.

CREATE TABLEDDL

Q13. easy

How do you delete an entire table and its data?

  1. A DROP TABLE t;
  2. B DELETE TABLE t;
  3. C REMOVE TABLE t;
  4. D TRUNCATE t;

Answer: A β€” DROP TABLE t;

DROP TABLE removes the table structure, data, indexes and constraints entirely. TRUNCATE only empties the rows; DELETE removes rows selectively.

DROP TABLE

Medium questions (16)

Q2. medium

What does a PRIMARY KEY constraint guarantee?

  1. A The column(s) are UNIQUE and NOT NULL - uniquely identifying each row
  2. B The column is the first one
  3. C The column is indexed only
  4. 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)
  1. A That the value must exist as a key in the referenced table (referential integrity)
  2. B That the column is unique
  3. C That the column is NOT NULL
  4. 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?

  1. A Ensures no two rows have the same value in that column (but allows NULLs, usually)
  2. B Makes the column the primary key
  3. C Sorts the column
  4. 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?

  1. A The column must always have a value - inserts/updates cannot leave it NULL
  2. B The column cannot be zero
  3. C The column is unique
  4. 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)
  1. A Enforces a custom condition on values, e.g. CHECK (age >= 0)
  2. B Checks spelling
  3. C Indexes the column
  4. 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
  1. A Supplies a value automatically when an insert omits the column
  2. B Sets the primary key
  3. C Makes the column unique
  4. 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?

  1. A ALTER TABLE t ADD COLUMN email VARCHAR(100);
  2. B UPDATE TABLE ADD email
  3. C CREATE COLUMN email
  4. 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?

  1. A ALTER TABLE t DROP COLUMN email;
  2. B DELETE COLUMN email
  3. C REMOVE email
  4. 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
  1. A AUTO_INCREMENT (MySQL), SERIAL / GENERATED AS IDENTITY (PostgreSQL), or IDENTITY (SQL Server)
  2. B AUTO NUMBER everywhere
  3. C INCREMENT BY 1
  4. 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?

  1. A Yes - CONSTRAINT chk_price CHECK (price >= 0) - named constraints are easier to reference and drop
  2. B No, constraints are anonymous
  3. C Only primary keys can be named
  4. 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?

  1. A Creates the table only if it does not already exist - avoiding an error on re-run
  2. B Always recreates the table
  3. C Deletes the table first
  4. 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?

  1. A ALTER TABLE old_name RENAME TO new_name; (syntax varies slightly)
  2. B RENAME COLUMN
  3. C UPDATE TABLE NAME
  4. 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?

  1. A The insert is rejected with a constraint-violation error
  2. B It inserts anyway
  3. C The value is corrected
  4. 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?

  1. A A foreign key that references the same table - e.g. employees.manager_id -> employees.id
  2. B A key that references itself literally
  3. C An invalid key
  4. 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?

  1. A ALTER TABLE t ALTER COLUMN c SET/DROP NOT NULL (or MODIFY in MySQL)
  2. B You cannot change nullability
  3. C DROP the column
  4. 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?

  1. A UNIQUE combined with NOT NULL
  2. B PRIMARY KEY only
  3. C CHECK only
  4. 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?

  1. A In most databases multiple NULLs are allowed (NULL is 'unknown', not equal to another NULL)
  2. B Only one NULL is allowed
  3. C NULLs are forbidden
  4. 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?

  1. A Automatically deletes child rows when the referenced parent row is deleted
  2. B Blocks the delete
  3. C Sets children to NULL
  4. 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?

  1. A RESTRICT blocks deleting a parent that has children; CASCADE deletes the children too
  2. B They are identical
  3. C RESTRICT deletes children
  4. 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?

  1. A PRIMARY KEY (col1, col2) - the combination is unique, though neither column need be alone
  2. B Two separate primary keys
  3. C A foreign key
  4. 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?

  1. A A natural key uses meaningful data (email, ISBN); a surrogate key is a system-generated id with no business meaning
  2. B They are identical
  3. C Natural keys are always integers
  4. 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?

  1. A ALTER TABLE orders ADD CONSTRAINT fk_cust FOREIGN KEY (customer_id) REFERENCES customers(id);
  2. B You must recreate the table
  3. C CREATE FOREIGN KEY
  4. 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?

  1. A The database enforces them for EVERY client and script - a last line of defence that never gets bypassed
  2. B They are faster to write
  3. C Application checks are always enough
  4. 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?

  1. A A relationship between them, e.g. CHECK (end_date >= start_date)
  2. B Only single-column checks are allowed
  3. C It indexes both
  4. 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?

  1. A Joins and cascade checks scan them frequently; without an index those operations are slow
  2. B Foreign keys index automatically everywhere
  3. C It is never needed
  4. 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?

  1. A Its check can be postponed until the transaction commits, allowing temporary violations mid-transaction
  2. B It disables the constraint
  3. C It runs the constraint twice
  4. 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
  1. A A column whose value is derived from other columns by a formula, maintained automatically
  2. B A random column
  3. C A backup column
  4. 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?

  1. A The table starts valid, and adding constraints later can fail on existing bad data or require costly full-table validation
  2. B It is faster to type
  3. C Later constraints are ignored
  4. 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

Practice β€œTables & Constraints” as a quiz