SQL Tutorial chapters (5)
  1. 01Introduction to SQL
  2. 02SQL Database & Tables (DDL)
  3. 03SQL SELECT, WHERE & Clauses
  4. 04SQL Joins & Subqueries
  5. 05SQL Views, Indexes & Practice

Chapter 02

SQL Database & Tables (DDL)

6 topics · 1 sections · beginner-friendly study notes · Updated

Share with friends:WhatsAppTelegram

Embed on your site

Free for teachers, schools and blogs. Please keep the attribution link.

Preview

DDL commands build and manage the structure of a database.

We use CREATE to make a database or table, ALTER to change it, DROP to remove it and constraints to keep the data correct.

A good table design avoids wrong and duplicate data.

Constraints work like rules at the college gate: only valid entries are allowed in.

Every project starts with creating tables for users, orders, students, products and so on.

1

CREATE DATABASE

CREATE DATABASE is a DDL command that makes a new empty database on the server.

In short: It makes a new cupboard where we will keep our tables.

DDL: define and change structure

Think about it

Different projects need separate spaces. A college database should not mix with a shop database. Making a new folder named "College" on your computer before saving files.

A database is a container for tables, views and other objects.

After creating it, we must select it with USE (in MySQL) before making tables inside it.

We can also see all databases using SHOW DATABASES.

If a database with the same name already exists, we get an error.

To avoid the error we can write IF NOT EXISTS.

Key points

  • Schema: In many databases, another word for a database or a group of tables.
  • USE: Selects which database we want to work in (MySQL).
  • Database names should be simple, without spaces.
  • Use IF NOT EXISTS to avoid errors on repeated runs.

Read more

Example

Code
Create and use a database:
CREATE DATABASE IF NOT EXISTS college_db;

USE college_db;

SHOW DATABASES;
2

CREATE TABLE

CREATE TABLE makes a new table with column names, data types and optional rules.

In short: We tell the database the column names and what kind of data each column keeps.

Think about it

Tables are the heart of a relational database. Without a table we cannot store anything. Designing the columns of the admission form: Roll No, Name, City, Marks.

The basic form is CREATE TABLE table_name (column1 type, column2 type, ...

).

Each column needs a name and a data type.

We can add constraints at the end of each column or at the end of the table.

We can check the result using DESCRIBE table_name (or DESC) in MySQL.

We can also copy a table structure and data with CREATE TABLE new AS SELECT ....

Key points

  • Column definition: Column name + data type + optional constraint.
  • DESCRIBE: Shows the structure of a table.
  • Table names are usually singular or plural by team rule: student or students.
  • Always choose the smallest suitable data type.

Example

Code
Create department and student tables:
CREATE TABLE department (
  dept_id   INT PRIMARY KEY,
  dept_name VARCHAR(50) NOT NULL
);

CREATE TABLE student (
  roll_no  INT PRIMARY KEY,
  name     VARCHAR(50) NOT NULL,
  city     VARCHAR(50),
  marks    INT,
  dept_id  INT
);

DESCRIBE student;
3

ALTER TABLE

ALTER TABLE changes the structure of an existing table. We can add, modify, rename or drop columns.

In short: If we forgot a column, we do not delete the table. We just alter it.

Think about it

Requirements change. Today we need only name and city, tomorrow we need an email too. Adding a new column "Email" to the paper admission register without throwing away the old pages.

ADD COLUMN adds a new column at the end.

MODIFY (MySQL) or ALTER COLUMN (SQL Server, PostgreSQL) changes the data type or size.

DROP COLUMN removes a column and its data.

RENAME COLUMN or CHANGE changes the column name.

RENAME TO changes the table name.

Adding a NOT NULL column to a table that already has rows needs a default value, because old rows must get some value.

Altering big tables can be slow, so plan it carefully.

Key points

  • ADD COLUMN: Adds a new column.
  • MODIFY: Changes type or size of a column (MySQL).
  • DROP COLUMN: Deletes a column with its data.
  • Dropping a column deletes its data permanently.
  • Syntax for MODIFY and RENAME differs between databases.

Example

Code
Common ALTER TABLE commands:
-- Add a column
ALTER TABLE student ADD COLUMN email VARCHAR(100);

-- Change the size of a column (MySQL)
ALTER TABLE student MODIFY name VARCHAR(80);

-- Rename a column
ALTER TABLE student RENAME COLUMN city TO home_city;

-- Remove a column
ALTER TABLE student DROP COLUMN email;

-- Rename the table
ALTER TABLE student RENAME TO students;
4

DROP & TRUNCATE

DROP removes a whole table or database, including its structure. TRUNCATE removes all rows from a table but keeps the empty table.

In short: DROP throws away the box and everything in it. TRUNCATE only empties the box.

Think about it

Choosing the wrong command can destroy data. Knowing the difference saves you from serious mistakes. DROP = demolish the classroom. TRUNCATE = remove all students and chairs but keep the room. DELETE = ask selected students to leave.

DROP TABLE student removes the table, its data, its indexes and its structure.

It cannot be undone in most databases.

TRUNCATE TABLE student deletes all rows quickly and resets auto-increment counters, but the table stays.

TRUNCATE has no WHERE clause.

DELETE FROM student also removes rows but can use WHERE, and it is slower because it logs each row.

In MySQL both DROP and TRUNCATE are DDL, so they commit automatically.

DELETE is DML and can be rolled back before COMMIT.

Key points

  • DROP: Removes table structure and data.
  • TRUNCATE: Removes all rows, keeps structure.
  • DELETE: Removes chosen rows using WHERE.
  • DROP and TRUNCATE are DDL. DELETE is DML.
  • TRUNCATE cannot use WHERE.
  • Take a backup before running DROP.

Example

Code
DELETE vs TRUNCATE vs DROP:
-- Remove selected rows only
DELETE FROM student WHERE city = "Pune";

-- Remove all rows, keep the table
TRUNCATE TABLE student;

-- Remove the table completely
DROP TABLE IF EXISTS student;

-- Remove the whole database
DROP DATABASE IF EXISTS college_db;
5

SQL Data Types

A data type tells the database what kind of value a column can store, such as a number, text or date.

In short: Data type is the type of box. A number box keeps numbers, a text box keeps words.

Variable → value in memory

Think about it

The right data type saves space, speeds up queries and stops wrong data like writing "abc" in a marks column. A form with a box for age (number only), a box for name (letters) and a box for date of birth (date picker).

Numbers: INT for whole numbers, BIGINT for very large whole numbers, DECIMAL(p,s) for exact decimals like money, FLOAT and DOUBLE for approximate decimals.

Text: CHAR(n) keeps fixed length, VARCHAR(n) keeps variable length up to n, TEXT keeps long text.

Date and time: DATE (2026-11-16), TIME, DATETIME and TIMESTAMP.

Other: BOOLEAN (true or false) and BLOB for files.

Choose DECIMAL for money, because FLOAT can give tiny rounding errors.

Use VARCHAR for names, and DATE for birth dates instead of text.

Key points

  • INT: Whole number like 25.
  • DECIMAL(10,2): Number with up to 10 digits and 2 after the decimal point.
  • VARCHAR(n): Text up to n characters.
  • DATE: Calendar date.
  • CHAR is fixed length. VARCHAR is variable length.
  • Use DECIMAL for money values.
  • Names of types vary slightly between databases.

Example

Code
Table using many data types:
CREATE TABLE employees (
  emp_id     INT PRIMARY KEY,
  emp_name   VARCHAR(60) NOT NULL,
  gender     CHAR(1),
  salary     DECIMAL(10,2),
  join_date  DATE,
  is_active  BOOLEAN
);
6

Constraints (PRIMARY KEY, FOREIGN KEY, UNIQUE, CHECK)

Constraints are rules placed on columns to keep data correct. Common ones are PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL, CHECK and DEFAULT.

In short: Constraints are the gate rules of a table. They stop wrong data from entering.

Constraints protect table quality

Think about it

Constraints protect data quality inside the database, even if the app has a bug. In a college, roll number is unique for each student (primary key). Every student must belong to a real department (foreign key). Marks must be between 0 and 100 (check).

PRIMARY KEY: identifies each row uniquely.

It cannot be NULL and cannot repeat.

A table has only one primary key, but it may use more than one column.

FOREIGN KEY: a column that points to the primary key of another table.

It keeps links valid, so a student cannot belong to a department that does not exist.

UNIQUE: no two rows can have the same value, but NULL is usually allowed and a table can have many UNIQUE columns.

NOT NULL: the column cannot be empty.

CHECK: the value must satisfy a condition, such as marks between 0 and 100.

DEFAULT: gives a value when none is supplied.

We can also set ON DELETE CASCADE so child rows are removed when the parent row is removed.

Key points

  • Primary key: Unique and not NULL identifier of a row.
  • Foreign key: Column that refers to the primary key of another table.
  • Unique: No duplicate values allowed.
  • Check: Value must satisfy a condition.
  • Default: Value used when none is given.
  • One primary key per table. Many unique columns are allowed.
  • Foreign key values must exist in the parent table (or be NULL).
  • Create the parent table before the child table.

Read more

Example

Code
Table with all main constraints:
CREATE TABLE department (
  dept_id   INT PRIMARY KEY,
  dept_name VARCHAR(50) NOT NULL UNIQUE
);

CREATE TABLE student (
  roll_no  INT PRIMARY KEY,
  name     VARCHAR(50) NOT NULL,
  email    VARCHAR(100) UNIQUE,
  marks    INT CHECK (marks BETWEEN 0 AND 100),
  city     VARCHAR(50) DEFAULT "Unknown",
  dept_id  INT,
  FOREIGN KEY (dept_id) REFERENCES department(dept_id)
    ON DELETE SET NULL
);

Solved examples

Example 01 · Basic

Create an employees table with emp_id (primary key), name, salary and department.

Given Data:
  • Columns: emp_id, name, salary, department
Required To Find:

CREATE TABLE statement

Formula Applied:—
Step-by-Step Solution:
Step 1: Choose INT for emp_id and mark it PRIMARY KEY.
Step 2: Use VARCHAR for name and department.
Step 3: Use DECIMAL for salary because it is money.
Final Answer: CREATE TABLE employees ( emp_id INT PRIMARY KEY, name VARCHAR(60) NOT NULL, salary DECIMAL(10,2), department VARCHAR(40) );

Approach note: Pick the type from the kind of value: whole number, money, text or date.

Example 02 · Intermediate

Add an email column to employees, then remove the department column.

Given Data:
  • Table: employees
Required To Find:

Two ALTER TABLE statements

Formula Applied:—
Step-by-Step Solution:
Step 1: Use ADD COLUMN to add the email column.
Step 2: Use DROP COLUMN to remove department.
Final Answer: ALTER TABLE employees ADD COLUMN email VARCHAR(100); ALTER TABLE employees DROP COLUMN department;

Approach note: ALTER keeps the table and its rows. Only the structure changes.

Example 03 · Intermediate

A table has 500 rows. You want to remove all rows but keep the table for new data. Which command do you use and why?

Given Data:
  • Table with 500 rows
Required To Find:

Best command

Formula Applied:—
Step-by-Step Solution:
Step 1: DROP would remove the table itself, so it is wrong.
Step 2: DELETE without WHERE works but is slower on big tables.
Step 3: TRUNCATE empties the table quickly and keeps the structure.
Final Answer: TRUNCATE TABLE table_name;

Approach note: Need to remove only some rows? Use DELETE with WHERE.

Example 04 · Intermediate

Create an orders table linked to customers so that an order cannot exist for a missing customer.

Given Data:
  • customers(customer_id)
  • orders(order_id, customer_id, amount)
Required To Find:

CREATE TABLE with FOREIGN KEY

Formula Applied:—
Step-by-Step Solution:
Step 1: Create customers first with PRIMARY KEY customer_id.
Step 2: In orders add a customer_id column.
Step 3: Add FOREIGN KEY (customer_id) REFERENCES customers(customer_id).
Final Answer: CREATE TABLE customers ( customer_id INT PRIMARY KEY, name VARCHAR(60) ); CREATE TABLE orders ( order_id INT PRIMARY KEY, customer_id INT NOT NULL, amount DECIMAL(10,2) CHECK (amount > 0), FOREIGN KEY (customer_id) REFERENCES customers(customer_id) );

Approach note: Parent table first, child table second.

Real-world applications

SQL

Using SQL Database and Tables (DDL) in real projects

Every project starts with creating tables for users, orders, students, products and so on.

Mechanism: Write small programs, read errors carefully, then grow complexity only after the basics are solid.

Common mistakes

❌ Myth: TRUNCATE and DELETE are exactly the same.

Why this is wrong: Both remove rows.

✅ Verified Truth: DELETE can use WHERE and can be rolled back before commit. TRUNCATE removes all rows at once, cannot use WHERE and is faster.

⚠️ Exam Tip: Mention: DELETE = DML, TRUNCATE = DDL.

❌ Myth: UNIQUE and PRIMARY KEY are the same.

Why this is wrong: Both stop duplicate values.

✅ Verified Truth: A table has one PRIMARY KEY that cannot be NULL. It can have many UNIQUE columns, and they usually allow NULL.

⚠️ Exam Tip: Primary key = unique + not null.

❌ Myth: A foreign key must have the same name as the primary key it points to.

Why this is wrong: Examples usually use the same name.

✅ Verified Truth: Names can be different. Only the data type and the values must match.

⚠️ Exam Tip: Matching names are only a good habit.

Revision notes

DDL commands build and manage the structure of a database. We use CREATE to make a database or table, ALTER to change it, DROP to remove it and constraints to keep the data correct.

High-Yield Quick Revision Points

  1. CREATE DATABASE makes a database. USE selects it.
  2. CREATE TABLE needs column name and data type.
  3. ALTER TABLE: ADD, MODIFY, RENAME, DROP column.
  4. DROP removes table. TRUNCATE empties it. DELETE removes chosen rows.
  5. Use DECIMAL for money, VARCHAR for text, DATE for dates.
  6. PRIMARY KEY = unique + not null. Only one per table.
  7. FOREIGN KEY links to another table. UNIQUE stops duplicates. CHECK tests a condition.

Practice questions

Question 1 · MCQ (Interview / semester)

Which command removes a table and its structure completely?

Question 2 · MCQ (Interview / semester)

Which constraint makes sure a column never stays empty?

Question 3 · MCQ (Interview / semester)

How many primary keys can one table have?

Question 4 · MCQ (Interview / semester)

Which data type is best for storing money?

Question 5 · MCQ (Interview / semester)

Which command can use a WHERE clause?

Question 6 · MCQ (Interview / semester)

A FOREIGN KEY refers to which key of another table?