Free Study Material

Building the Database (DDL)

Introduction

Every column you define in a table needs two things: what kind of value it holds, and any rules restricting what values you're actually allowed to put in it. These are data types and constraints.

Concept

Common SQL data types:

  • INT — whole numbers.
  • FLOAT/DECIMAL — numbers with a decimal point.
  • CHAR(n) — a fixed-length text field of exactly n characters, padded with spaces if the actual text is shorter.
  • VARCHAR(n) — a variable-length text field, up to n characters — uses only as much space as the actual text needs. This is the standard choice for names and most text data.
  • DATE — calendar dates.

Common constraints:

  • NOT NULL — the column cannot be left empty.
  • UNIQUE — no two rows may have the same value in this column.
  • DEFAULT — a value used automatically if none is provided.
  • CHECK — restricts values to ones satisfying a condition (e.g., Marks >= 0).

Worked Example

Here's how you'd actually use these together, defining a table for a school's book collection:

CREATE TABLE BOOK (
    BookID INT PRIMARY KEY,
    Title VARCHAR(50) NOT NULL,
    Category CHAR(10) DEFAULT 'General',
    Price INT CHECK (Price >= 0)
);

Title is VARCHAR since book titles vary a lot in length. Category is CHAR(10) — short, fairly fixed-length labels like "Fiction". If you don't specify a Category when adding a book, it DEFAULTs to 'General'. And CHECK (Price >= 0) stops you from ever inserting a negative price by mistake.

Explanation

CHAR vs. VARCHAR is worth understanding precisely: CHAR(10) always reserves exactly 10 bytes, no matter how short the actual text is — storing "SQL" in a CHAR(10) column still uses 10 bytes (padded with spaces). VARCHAR(10) would use only as much as "SQL" actually needs. That's why VARCHAR is generally preferred for names and free text.

Note: UNIQUE is the constraint specifically for "no duplicate values allowed" — it's easy to confuse with NOT NULL (which is about emptiness, not duplication) or Primary Key (which combines both UNIQUE and NOT NULL automatically).

Summary

INT, FLOAT, CHAR(n), VARCHAR(n), and DATE are the core SQL data types — CHAR is fixed-length (always reserves its full size), VARCHAR is variable-length (uses only what's needed). NOT NULL, UNIQUE, DEFAULT, and CHECK are the constraints that restrict what values a column may actually hold.

1. SQL Data Types

When creating a table, you must define what kind of data each column will hold.

Type Syntax Description & Usage
Integer INT or INTEGER Stores whole numbers without decimals.
(e.g., RollNo, Age, Quantity).
Floating Point FLOAT or DECIMAL(p,s) Stores numbers with decimal points.
(e.g., Price, Percentage, Salary).
Date DATE Stores dates in YYYY-MM-DD format.
(e.g., DOB, JoiningDate).
String (Variable) VARCHAR(n) Stores text of variable length. Saves memory.
(e.g., Name, City, Address).
String (Fixed) CHAR(n) Stores text of fixed length. Faster but wastes memory.
(e.g., Gender 'M'/'F', Pincode).

CHAR vs. VARCHAR

Why do we have two types for text? It's about Memory vs. Speed.

Feature CHAR (Fixed Length) VARCHAR (Variable Length)
Full Form Character Variable Character
Memory Allocates fixed memory regardless of input.
CHAR(10) always takes 10 bytes.
Allocates memory based on input.
VARCHAR(10) with "Hi" takes only 2 bytes.
Best Use Data with fixed size (Gender, Pincode, Grade). Data with varying size (Names, Emails, Addresses).

2. Constraints

NOT NULL

Ensures that a column cannot be left blank.
Example: A Student MUST have a Name.

UNIQUE

Ensures that all values in a column are different.
Example: Aadhar Number or Email ID.

PRIMARY KEY

A combination of NOT NULL and UNIQUE.
Uniquely identifies each record.

DEFAULT

Sets a default value for a column if no value is specified.
Example: If "Country" is left blank, automatically fill "India".

Introduction

CREATE TABLE and DROP TABLE are the two commands that bring a table into existence and remove it entirely — the very first and potentially last commands you'll run against any table.

Concept

CREATE TABLE defines a table's name, its columns, each column's data type, and any constraints, all in one statement:

CREATE TABLE STUDENT (
    AdmNo INT PRIMARY KEY,
    Name VARCHAR(20) NOT NULL,
    Marks INT
);

DROP TABLE removes a table completely — both its structure and every row of data inside it, permanently:

DROP TABLE OLD_DATA;

Explanation

DROP TABLE is one of the most dangerous commands in SQL specifically because of what it removes: not just the rows (which DELETE would do), but the table's entire structure too — its columns, its constraints, everything. Once dropped, the table doesn't exist to query at all; a SELECT * FROM it afterward fails with an error like "no such table", not an empty result.

Warning: DROP TABLE cannot be undone by any SQL command — there's no "UNDROP". In a real system, only a full backup restore can bring the data back.

Summary

CREATE TABLE name (column type constraints, ...) defines a new table's structure. DROP TABLE name permanently deletes both the table's structure and all its data — the most destructive DDL command, with no built-in way to reverse it.

The CREATE Command

Before we can store any data, we must build a container. In SQL, this container is called a Table.

Analogy: Think of CREATE TABLE as drawing the Blueprint of a house. You decide where the walls go (Columns) and what materials to use (Data Types). You haven't moved any furniture (Data) in yet.

Syntax & Rules (MySQL)

CREATE TABLE table_name (
  column1 datatype constraint,
  column2 datatype constraint,
  PRIMARY KEY (column1)
);

Common Constraints (Rules):

  • PRIMARY KEY: Uniquely identifies each row (e.g., Admission Number).
  • NOT NULL: The column cannot be left empty (e.g., Student Name).
  • UNIQUE: No duplicates allowed (e.g., Email ID).

Challenge 1: Build the 'Student' Table

Write a MySQL query to create a table named STUDENT with the following structure:

Column Type Constraint
AdmNo INT PRIMARY KEY
Name VARCHAR(20) NOT NULL
Marks INT -

↓ Write your code below ↓

/* ==================================================
   TASK: Create the STUDENT table
   1. AdmNo (INT PRIMARY KEY)
   2. Name (VARCHAR(20) NOT NULL)
   3. Marks (INT)
   ================================================== */

-- Write your CREATE TABLE command here:
-- Example: CREATE TABLE STUDENT (...);



/* ==================================================
   SYSTEM VERIFICATION (Do not delete)
   This checks if your table was created correctly.
   ================================================== */
-- In MySQL we use: DESC STUDENT;
-- Since this lab runs on a browser engine, we use:
PRAGMA table_info(STUDENT);

The DROP Command (Danger Zone)

If you want to delete an entire table (including its structure and all data inside it), use the DROP command.

DROP TABLE table_name;
DELETE Command

Removes rows (data). The table structure remains.

DROP Command

Removes EVERYTHING. The table ceases to exist.

Challenge 2: Drop the Table

We have created a temporary table named OLD_DATA for you.
Your Task: Write a query to completely destroy this table.

↓ Run the code below ↓

/* ==================================================
   SYSTEM SETUP: Creating a dummy table
   (We create it so you can destroy it!)
   ================================================== */
DROP TABLE IF EXISTS OLD_DATA;
CREATE TABLE OLD_DATA (ID INT, Info VARCHAR(50));
INSERT INTO OLD_DATA VALUES (1, 'Useless Data');

/* ==================================================
   YOUR TASK STARTS HERE
   Write the command to DROP the 'OLD_DATA' table
   ================================================== */

-- Type your DROP TABLE command here:



/* ==================================================
   VERIFICATION
   This query checks if the table still exists.
   If successful, it should say "no such table: OLD_DATA"
   ================================================== */
SELECT * FROM OLD_DATA;

Introduction

Sometimes a table's structure needs to change after you've already created it — you need a new column, or an existing one needs a different size. ALTER TABLE is the command for exactly that: changing structure, not data.

Concept

-- Add a new column
ALTER TABLE STUDENT ADD City VARCHAR(20);

-- Change an existing column's definition
ALTER TABLE STUDENT MODIFY Name VARCHAR(50);

ADD introduces a brand-new column; MODIFY changes the definition (typically the size or data type) of a column that already exists.

Explanation

ALTER TABLE only ever touches the table's structure — its columns and their definitions. It's never the right tool if you want to change or remove actual row data; that's UPDATE's and DELETE's job specifically. This distinction — structure vs. data — is exactly what separates DDL commands (CREATE, ALTER, DROP) from DML commands (INSERT, UPDATE, DELETE), which you'll meet in the next chapter.

Note: ALTER TABLE cannot delete a row of data — if a question asks how to remove data (not a column), the answer is DELETE, never ALTER.

Summary

ALTER TABLE ... ADD adds a new column; ALTER TABLE ... MODIFY changes an existing column's definition. ALTER TABLE only changes structure — never row data, which stays the job of DML commands like UPDATE and DELETE.

The ALTER Command

Real-world databases change. You might need to add a new column (like 'Email') or change a data type.

CRITICAL BOARD EXAM CONCEPT:
  • ALTER changes the Structure (Columns).
  • UPDATE changes the Data (Rows/Values).

Challenge: Add a New Column

We have created a STUDENT table with AdmNo and Name.
Your Task: Add a new column named City (Type: VARCHAR(20)).

Syntax: ALTER TABLE table_name ADD column_name datatype;

↓ Write your code below ↓

-- SETUP (Do not edit)
DROP TABLE IF EXISTS STUDENT;
CREATE TABLE STUDENT (AdmNo INT, Name VARCHAR(20));

-- TASK: Write the ALTER command to ADD 'City'
-- Example: ALTER TABLE STUDENT ADD ...


-- VERIFY (Shows the new columns)
SELECT * FROM STUDENT;

Other ALTER Operations

Memorize these syntaxes for 1-mark questions.

1. Modify a Column

Used to change the data type or size of an existing column.

ALTER TABLE STUDENT
MODIFY Name VARCHAR(50);

2. Drop a Column

Used to remove an unwanted column completely.

ALTER TABLE STUDENT
DROP COLUMN City;

Introduction

ALTER TABLE doesn't just add or resize columns — it can also add or remove the constraints attached to them, including a table's own Primary Key, after the table already exists.

Concept

-- Add a Primary Key to a table that doesn't already have one
ALTER TABLE BOOK ADD PRIMARY KEY (BookID);

-- Remove a Primary Key
ALTER TABLE STUDENT DROP PRIMARY KEY;

Adding a Primary Key requires naming exactly which column(s) it applies to — BOOK was created without one, so BookID needs to be named explicitly here. Dropping one doesn't need a column name — since a table can only ever have one Primary Key, there's nothing to specify. STUDENT already has AdmNo as its Primary Key from when it was created, which is what the DROP example removes.

Explanation

Dropping a Primary Key doesn't delete any data — the rows and their values stay exactly as they were. What changes is the rule: with no Primary Key enforcing uniqueness, the column that used to require unique values can now silently accept duplicates.

Warning: After DROP PRIMARY KEY, the column's existing data is untouched, but the uniqueness guarantee is gone — new duplicate values become possible where they weren't before.

Summary

ALTER TABLE ... ADD PRIMARY KEY (column) attaches a Primary Key to an existing table; ALTER TABLE ... DROP PRIMARY KEY removes it. Adding requires naming the column; dropping doesn't. Neither operation deletes data — only the constraint rule changes.

Adding Keys to Existing Tables

Sometimes we create a table but forget to assign a Primary Key. We don't need to delete the table; we can simply "Add" the constraint using ALTER.

MySQL Syntax (Memorize This)

1. Add Primary Key

Scenario: You want to make `AdmNo` the Primary Key.

ALTER TABLE STUDENT
ADD PRIMARY KEY (AdmNo);

2. Add Foreign Key

Scenario: Link `ClassID` in Student table to `ID` in Classes table.

ALTER TABLE STUDENT
ADD FOREIGN KEY (ClassID) REFERENCES CLASSES(ID);

3. Add Unique Constraint

Scenario: Ensure `Email` has no duplicates.

ALTER TABLE STUDENT
ADD UNIQUE (Email);

Removing Constraints

1. Drop Primary Key

To remove the Primary Key status (but keep the column data), use this specific command.
Note: You don't need to specify the column name because a table has only one PK.

ALTER TABLE STUDENT
DROP PRIMARY KEY;

Challenge: Write the Command

Assume you have a table EMPLOYEE with a column EmpID.
Write the MySQL command to make EmpID the Primary Key.

↓ Type the command below (Syntax Practice) ↓

/* ==================================================
   SYNTAX PRACTICE
   Write the command below.
   (Note: This is a design exercise. It will not run 
   in this browser preview, but is required for Exams)
   ================================================== */

-- Your Answer:
-- ALTER TABLE ...

Want the full course?

Unlock all chapters, video lectures, and SQL practice exercises.

Get Full Access