DBMS 📂 SQL · 1 of 1 33 min read

SQL Basics Practice: DDL & DML Commands with Constraints

A hands-on SQL tutorial covering the DDL and DML command families — CREATE TABLE with constraints (primary key, foreign key, UNIQUE, CHECK, DEFAULT), ALTER, DROP, TRUNCATE, INSERT, UPDATE, and DELETE. It pairs animated diagrams and before/after tables with a five-part practice problem set that builds a small database end to end.

Section 01

The Story — Build the House, Then Furnish It

Architecture vs Interior Design
Before anyone can move furniture into a house, an architect must build it — the rooms, the doors, the load-bearing walls. Only then does the moving company bring in furniture, rearrange it, and haul some out.

SQL works the same way. DDL (Data Definition Language) builds the structure: it creates, alters, and drops tables. DML (Data Manipulation Language) is the moving company: it inserts, updates, and deletes the rows inside. And constraints are the building codes — rules like "every apartment needs a unique number" or "the rent must be positive" that keep bad data out.
💡
The Core Distinction

DDL changes the structure (the table itself); DML changes the data (the rows). DDL commands auto-commit and usually can't be rolled back, so always double-check a DROP or TRUNCATE.


Section 02

The SQL Command Families

Every SQL statement belongs to a family. This tutorial focuses on the two you use most — DDL and DML — but it helps to see the whole map.

🏢 The Families of SQL Commands
SQL DDL structure CREATE ALTER DROP TRUNCATE DML data INSERT UPDATE DELETE (SELECT = DQL) DCL / TCL access & transactions GRANT / REVOKE COMMIT ROLLBACK This tutorial: the DDL and DML families

Modern SQL classifies SELECT as DQL (Data Query Language), though older texts group it with DML.

FamilyPurposeCommands
DDLDefine / change structureCREATE, ALTER, DROP, TRUNCATE
DMLManipulate dataINSERT, UPDATE, DELETE
DQLQuery dataSELECT
DCLControl accessGRANT, REVOKE
TCLManage transactionsCOMMIT, ROLLBACK, SAVEPOINT

Section 03

CREATE TABLE — Building the Structure

CREATE TABLE defines a new table: its name, its columns, each column's data type, and the constraints that guard it. This is always the first command when setting up a schema.

🏗️ Definition → Empty Table
CREATE TABLE EMPLOYEE Emp_ID, Name, Age, Salary, Dept_ID… Emp_ID Name Age (empty — structure ready)

CREATE makes an empty, well-defined table — the rows come later, via INSERT.

-- Build two related tables for our company database
CREATE TABLE DEPARTMENT (
    Dept_ID   INT          PRIMARY KEY,
    Dname     VARCHAR(40)  NOT NULL
);

CREATE TABLE EMPLOYEE (
    Emp_ID    INT          PRIMARY KEY,
    Name      VARCHAR(50)  NOT NULL,
    Age       INT          CHECK (Age >= 18),
    Salary    INT          DEFAULT 30000,
    Email     VARCHAR(80)  UNIQUE,
    Dept_ID   INT,
    FOREIGN KEY (Dept_ID) REFERENCES DEPARTMENT(Dept_ID)
);

Section 04

Constraints — The Guardrails of Your Data

Constraints are rules attached to columns that the database enforces automatically. Any insert or update that breaks a rule is rejected, keeping the data clean and consistent.

🛡️ A Bad Row Bounces Off the Constraints
Emp_ID PK Age CHECK≥18 Email UNIQUE 1 30 raj@co.com 2 , Age=15 , raj@co.com Age 15 fails CHECK • email duplicates UNIQUE

The database rejects the row because Age 15 violates the CHECK and the email duplicates an existing UNIQUE value.

ConstraintWhat it enforcesExample
NOT NULLColumn can never be emptyName VARCHAR(50) NOT NULL
UNIQUENo duplicate values (one NULL allowed)Email VARCHAR(80) UNIQUE
PRIMARY KEYUNIQUE + NOT NULL; identifies each rowEmp_ID INT PRIMARY KEY
FOREIGN KEYValue must exist in another table's PKDept_ID REFERENCES DEPARTMENT(Dept_ID)
CHECKValue must satisfy a conditionCHECK (Age >= 18)
DEFAULTValue used when none is givenSalary INT DEFAULT 30000
AUTO_INCREMENTAuto-generate sequential numbersEmp_ID INT AUTO_INCREMENT
🔑
Primary Key vs Unique

A table has exactly one PRIMARY KEY (which forbids NULLs), but it can have many UNIQUE columns, and a UNIQUE column may hold a single NULL. Use the primary key for the main identifier, UNIQUE for other no-duplicate fields like Email.


Section 05

ALTER TABLE — Changing the Structure

ALTER TABLE modifies an existing table without losing the data already in it. You can add or drop columns, change a column's type, or add and remove constraints.

➕ A New Column Slides In
Emp_ID Name Salary 1 Raj 50000 Joining_Date NULL ADD COLUMN

Existing rows get NULL (or the DEFAULT) in the new column — no data is lost.

-- Add a column
ALTER TABLE EMPLOYEE ADD Joining_Date DATE;

-- Change a column's data type
ALTER TABLE EMPLOYEE MODIFY Name VARCHAR(80);

-- Add a constraint to an existing table
ALTER TABLE EMPLOYEE ADD CONSTRAINT chk_sal CHECK (Salary > 0);

-- Remove a column
ALTER TABLE EMPLOYEE DROP COLUMN Joining_Date;

Section 06

DROP vs TRUNCATE vs DELETE — A Crucial Comparison

These three commands all "remove" something, but they are very different — and confusing them is the single most common SQL exam mistake.

🧹 Three Levels of Removal
DELETE (some rows) EMPLOYEE row 1 row 2 row 3 TRUNCATE (all rows) EMPLOYEE (empty — structure stays) DROP (whole table) table gone entirely

DELETE removes chosen rows, TRUNCATE empties the table, DROP destroys the table itself.

FeatureDELETETRUNCATEDROP
FamilyDMLDDLDDL
RemovesChosen rowsAll rowsWhole table
WHERE clauseYesNoNo
Can roll backYesUsually noNo
Structure afterRemainsRemainsGone
SpeedSlower (row by row)FastFast
DELETE FROM EMPLOYEE WHERE Age < 21;   -- removes matching rows only
TRUNCATE TABLE EMPLOYEE;              -- empties the table, keeps structure
DROP TABLE EMPLOYEE;                  -- deletes the table completely

Section 07

INSERT — Adding Rows

INSERT adds new rows. You can list all values in column order, name specific columns, or insert several rows at once. Columns you skip take their DEFAULT (or NULL).

➡️ A New Row Drops Into the Table
Emp_ID Name Salary 1 Raj 50000 2 Sara 40000 new row

The inserted row must satisfy every constraint, or the database rejects it.

-- Departments first (parent table, for the foreign key)
INSERT INTO DEPARTMENT VALUES (10, 'Sales'), (20, 'Tech');

-- Full row, values in column order
INSERT INTO EMPLOYEE VALUES (1, 'Raj', 30, 50000, 'raj@co.com', 10);

-- Named columns; Salary defaults to 30000, Email becomes NULL
INSERT INTO EMPLOYEE (Emp_ID, Name, Age, Dept_ID) VALUES (3, 'Amit', 19, 10);

-- Multiple rows at once
INSERT INTO EMPLOYEE VALUES
    (2, 'Sara', 25, 40000, 'sara@co.com', 20);
EMPLOYEE after the inserts
Emp_IDNameAgeSalaryEmailDept_ID
1Raj3050000raj@co.com10
2Sara2540000sara@co.com20
3Amit1930000NULL10

Section 08

UPDATE — Changing Existing Rows

UPDATE modifies values in rows that match a WHERE condition. The WHERE clause is critical: omit it and every row is changed.

✎ A Salary Cell Changes Value
Name Salary Raj 50000 55000 SET Salary = Salary * 1.10 WHERE Dept_ID = 10

Only rows matching the WHERE condition are touched; the rest stay exactly as they were.

-- Give everyone in department 10 a 10% raise
UPDATE EMPLOYEE SET Salary = Salary * 1.10 WHERE Dept_ID = 10;
After the UPDATE (Dept 10 rows changed)
NameDept_IDSalary
Raj1055000
Sara2040000
Amit1033000
⚠️
The Most Expensive Missing Word in SQL

UPDATE EMPLOYEE SET Salary = 0; with no WHERE zeroes out every salary in the table. Always write (and double-check) the WHERE clause before running an UPDATE or DELETE.


Section 09

DELETE — Removing Rows

DELETE removes rows that match a condition. Unlike TRUNCATE, it is a DML command: it works row by row, supports a WHERE clause, and can be rolled back inside a transaction.

➖ A Row Is Struck Out and Removed
Name Age Raj 30 Amit 19 Age < 21 → removed

Amit (age 19) matches Age < 21 and is deleted; the table structure is untouched.

-- Remove employees younger than 21
DELETE FROM EMPLOYEE WHERE Age < 21;

-- Remove everyone (rows only) -- structure stays, but prefer TRUNCATE for speed
DELETE FROM EMPLOYEE;
EMPLOYEE after DELETE WHERE Age < 21
NameAge
Raj30
Sara25

Section 10

Practice Problems — Solve Them Yourself First

Here is a full mini-scenario. Try each problem before revealing the logic in the solution. We build a small college database from scratch.

Problem 1 — Create the tables

Task

Create a COURSE table (Course_ID primary key, Title not null) and a STUDENT table with Roll (PK), Name (not null), Marks (must be 0–100), a Grade defaulting to 'NA', and Course_ID as a foreign key to COURSE.

-- Solution 1
CREATE TABLE COURSE (
    Course_ID  INT          PRIMARY KEY,
    Title      VARCHAR(50)  NOT NULL
);

CREATE TABLE STUDENT (
    Roll       INT          PRIMARY KEY,
    Name       VARCHAR(50)  NOT NULL,
    Marks      INT          CHECK (Marks >= 0 AND Marks <= 100),
    Grade      CHAR(2)      DEFAULT 'NA',
    Course_ID  INT,
    FOREIGN KEY (Course_ID) REFERENCES COURSE(Course_ID)
);

Problem 2 — Insert data

Task

Add course 101 "DBMS", then add three students. Leave one student's Grade unset to test the DEFAULT.

-- Solution 2
INSERT INTO COURSE VALUES (101, 'DBMS');

INSERT INTO STUDENT VALUES (1, 'Raj', 82, 'A', 101);
INSERT INTO STUDENT VALUES (2, 'Sara', 55, 'C', 101);
INSERT INTO STUDENT (Roll, Name, Marks, Course_ID) VALUES (3, 'Amit', 91, 101);
RollNameMarksGradeCourse_ID
1Raj82A101
2Sara55C101
3Amit91NA101

Problem 3 — Alter the table

Task

Add an Age column to STUDENT, then add a CHECK constraint so Age must be at least 17.

-- Solution 3
ALTER TABLE STUDENT ADD Age INT;
ALTER TABLE STUDENT ADD CONSTRAINT chk_age CHECK (Age >= 17);

Problem 4 — Update with a rule

Task

Set Grade to 'A' for every student scoring more than 90 marks.

-- Solution 4  (this promotes Amit, 91 marks, to grade A)
UPDATE STUDENT SET Grade = 'A' WHERE Marks > 90;

Problem 5 — Delete, then clean up

Task

Remove students scoring below 60. Then write the commands to (a) empty STUDENT keeping its structure, and (b) delete the table entirely.

-- Solution 5
DELETE FROM STUDENT WHERE Marks < 60;   -- removes Sara (55)

TRUNCATE TABLE STUDENT;   -- (a) empties rows, keeps the table
DROP TABLE STUDENT;       -- (b) removes the table completely
What These Five Problems Covered

You used CREATE with five constraint types, INSERT (including a DEFAULT), ALTER (add column + add constraint), UPDATE with a condition, and DELETE / TRUNCATE / DROP — the entire DDL + DML core in one workflow.


Section 11

Command Cheat Sheet

CommandFamilyJobSkeleton
CREATE TABLEDDLBuild a tableCREATE TABLE t (col type constraint, …)
ALTER TABLEDDLChange structureALTER TABLE t ADD / MODIFY / DROP …
DROP TABLEDDLDelete table + dataDROP TABLE t
TRUNCATE TABLEDDLEmpty all rowsTRUNCATE TABLE t
INSERTDMLAdd rowsINSERT INTO t VALUES (…)
UPDATEDMLChange rowsUPDATE t SET col = v WHERE …
DELETEDMLRemove rowsDELETE FROM t WHERE …

Section 12

Common Mistakes to Avoid

⚠️
Mistake 1 — UPDATE or DELETE without WHERE

No WHERE means the command hits every row. Always confirm the condition first — there is no undo for an auto-committed change.

⚠️
Mistake 2 — Confusing DELETE, TRUNCATE, and DROP

DELETE removes chosen rows (DML, reversible); TRUNCATE empties the table (DDL, fast); DROP destroys the table itself (DDL, gone for good).

⚠️
Mistake 3 — Inserting a child before its parent

A foreign key value must already exist in the parent table. Insert DEPARTMENT (or COURSE) rows before the EMPLOYEE (or STUDENT) rows that reference them.


Section 13

Golden Rules of DDL & DML

🏆 SQL Basics — Non-Negotiable Rules
1
DDL changes structure; DML changes data. Know which family a command belongs to before you run it.
2
Define constraints at CREATE time. They are the guardrails that keep invalid data out forever.
3
Every table needs exactly one primary key. Add UNIQUE for other no-duplicate columns.
4
Never run UPDATE or DELETE without a WHERE clause unless you truly mean "all rows".
5
DDL auto-commits — there is no undo. Double-check DROP and TRUNCATE on a real database.
6
Respect foreign keys. Insert parents before children, and delete children before parents.
You have completed SQL. View all sections →