PART 3 • SQL MASTERYDefine Structures That Reject Invalid Data
Turn a relational design into clear SQL objects, keys and constraints—and evolve the schema without treating production data carelessly.
Level 10 of 18Core SQL130–170 minutesLevel 9 recommended
BY THE END, YOU CAN- Create tables with suitable types.
- Choose column- and table-level constraints.
- Define composite and foreign keys.
- Explain referential actions.
- Plan safe ALTER operations.
- Distinguish DELETE, TRUNCATE and DROP.
CREATEIntroduce an object
Create schemas, tables, views, indexes and other database objects.
→ALTEREvolve an object
Add, change, rename or remove columns and constraints.
→TRUNCATERemove table rows
Quickly empties a table while retaining its definition.
→DROPRemove the object
Deletes the definition and normally its stored data.
02 • CREATE A RELATIONCREATE TABLE Combines Names, Domains and Constraints
CREATE TABLE students (
student_id INTEGER,
name VARCHAR(100) NOT NULL,
email VARCHAR(255),
cgpa DECIMAL(3,2) DEFAULT 0.00,
dept_id INTEGER,
CONSTRAINT pk_students
PRIMARY KEY (student_id),
CONSTRAINT uq_students_email
UNIQUE (email),
CONSTRAINT ck_students_cgpa
CHECK (cgpa BETWEEN 0 AND 10),
CONSTRAINT fk_students_department
FOREIGN KEY (dept_id)
REFERENCES departments(dept_id)
);
Table identitystudents names the relation.
Column definitionsEach column has a name, domain and optional rules.
Named constraintsNames make future error diagnosis and ALTER operations clearer.
Schema qualificationacademic.students can identify an owning namespace.
GOOD NAMINGstudent_idcourse_titleenrolmentsUse consistent, descriptive identifiers; avoid spaces, punctuation, vague abbreviations and reserved words.
03 • ENFORCE VALID STATESConstraints Place Rules at the Data Boundary
NOT NULLValue is required
name VARCHAR(100) NOT NULLPrevents missing values in the column.
UNIQUENo repeated key value
UNIQUE (email)NULL treatment can differ by DBMS.
PRIMARY KEYChosen row identity
PRIMARY KEY (student_id)Combines uniqueness and non-null identity.
FOREIGN KEYValid reference
REFERENCES departments(dept_id)Protects referential integrity.
CHECKRow-level condition
CHECK (cgpa BETWEEN 0 AND 10)Rejects rows when the condition is FALSE; understand target NULL behavior.
DEFAULTValue when omitted
DEFAULT CURRENT_DATEDoes not replace an explicitly supplied NULL unless other logic exists.
COLUMN LEVELemail VARCHAR(255) UNIQUEConvenient for a rule involving one column.
TABLE LEVELPRIMARY KEY (student_id, course_id)Required for composite constraints and often clearer when naming rules.
04 • DEFINE RELATIONSHIPSA Foreign Key Requires a Matching Parent Key
PARENTdepartmentsdept_id, dept_name
1 ─── ∞CHILDstudentsstudent_id, name, dept_id (FK)
RESTRICT / NO ACTIONReject a parent delete while child references exist. Timing details can differ.
CASCADEPropagate parent DELETE or UPDATE to child rows. Powerful and potentially broad.
SET NULLReplace the child FK with NULL; the child column must allow NULL.
SET DEFAULTUse the child default where supported; that value must satisfy the reference.
Choose referential actions from business meaningDo not add CASCADE merely for convenience. Deleting a department should rarely delete every historical student record automatically.
05 • EVOLVE A LIVE SCHEMAALTER TABLE Must Respect Existing Rows
ADDALTER TABLE students ADD COLUMN phone VARCHAR(20);A nullable column is usually compatible with existing rows.
BACKFILL THEN REQUIREADD status ...; UPDATE ...; ALTER ... SET NOT NULL;Populate valid values before applying a strict constraint.
RENAMEALTER TABLE students RENAME COLUMN name TO full_name;Update queries, views, application code and reports together.
CHANGE TYPEALTER COLUMN cgpa TYPE DECIMAL(4,2);Confirm conversion, range, locking and dialect syntax.
DROP COLUMNALTER TABLE students DROP COLUMN legacy_code;Check dependencies and backups before irreversible removal.
SAFER PRODUCTION PATTERN1. ExpandAdd the new structure without breaking old code.
2. MigrateBackfill, validate and switch reads/writes.
3. ContractRemove old structure only after dependants are updated.
06 • KNOW THE BLAST RADIUSDELETE, TRUNCATE and DROP Are Not Interchangeable
| Statement | Removes | WHERE? | Structure remains? | Main use |
|---|
| DELETE | Selected or all rows | Yes | Yes | Controlled row removal |
|---|
| TRUNCATE | All rows | No | Yes | Fast complete table clearing |
|---|
| DROP TABLE | Object and its data | No | No | Remove an obsolete table |
|---|
Before destructive DDLConfirm environmentInspect dependenciesTake or verify backupReview permissionsPlan recoverySchedule impact
Choose a preset or define columns to generate SQL.
09 • CHECK YOUR UNDERSTANDINGTen Formative Concept Checks
1. Which statement defines a new table?
2. A primary key guarantees:
3. Which is needed for a composite primary key?
4. A foreign key primarily enforces:
5. DEFAULT is used when:
6. Safest common way to add a required column to populated data?
7. Which statement removes all rows but retains the table definition?
8. DROP TABLE removes:
9. ON DELETE CASCADE should be chosen based on:
10. DDL rollback behavior is:
Answered correctly: 0 of 10
10 • EXPLAIN & PREPAREUniversity and Interview Questions
2-MARK QUESTIONS- Define DDL.
- PRIMARY KEY versus UNIQUE?
- What is a CHECK constraint?
- Define referential integrity.
- TRUNCATE versus DROP?
5-MARK / PRACTICAL- Create STUDENT with all major constraints.
- Create ENROLMENT with a composite key.
- Explain referential actions.
- Plan a safe required-column migration.
INTERVIEW QUESTIONS- Why name constraints?
- Can UNIQUE contain NULL?
- When is CASCADE dangerous?
- How do you change a type safely?
- What is expand-and-contract?
Show the table-design answer format
- State the relation purpose and grain.
- Choose stable column names and domains.
- Declare a minimal primary key.
- Add required, uniqueness and range constraints.
- Define foreign keys and justified actions.
- Name important constraints.
- Provide representative valid and invalid rows.
- Mention dialect assumptions and migration impact.
LEVEL 10 SUMMARYYou Can Now Turn a Design into Enforced SQL
- DDL defines and evolves database objects.
- Types and constraints form the schema contract.
- Composite constraints belong at table level.
- Foreign-key actions follow business lifecycle.
- ALTER must account for existing rows and dependent code.
- DELETE, TRUNCATE and DROP have different scopes.
- Production changes need validation, backup and recovery planning.
COURSE CHECKPOINTMark this level when you can create a constrained schema and explain how to evolve or remove it safely.
Saved in this browser only.