Data Definition Language Define and Manage The Structure
Data Definition Language Define and Manage The Structure
DDL
WHAT: DDL stands for Data Definition Language. It is a part of SQL (Structured Query
Language) used to define and manage the structure of database objects like tables, views,
indexes, and schemas.
1. CREATE – To create new database objects (tables, databases, views, etc.)
2. ALTER – To modify existing database structures (add/remove columns, change data
types, etc.)
3. DROP – To permanently delete database objects.
4. TRUNCATE – To quickly remove all rows from a table (faster than DELETE, and
cannot be rolled back).
5. RENAME – To rename database objects like tables or columns (supported in many
SQL versions).
EXAMPLE:
➡️ This creates a table named "Employees" with 3 columns: ID, Name, and Salary.
2. ALTER is Used to modify the structure of an existing table.
➡️ This completely removes the "Employees" table and all of its data.
4. TRUNCATE is Used to remove all data from a table, but keep the table structure.
TRUNCATE TABLE Employees;
➡️ This deletes all rows in "Employees" but keeps the table itself for future use.
5. RENAME is Used to change the name of a table or column.
✅ 4. Drop a column
ALTER TABLE Employees ADD COLUMN Department VARCHAR(50);
✅ 5. Truncate a table
TRUNCATE TABLE Employees;
✅ 6. Drop a table
DROP TABLE Employees;
✅ 7. Rename a table
ALTER TABLE Employees RENAME TO Staff;
What happens when you Behavior of It quickly deletes all rows, auto-commits,
TRUNCATE a table in DDL in PG and doesn’t activate triggers unless they
PostgreSQL? are AFTER TRUNCATE triggers.
Can you roll back a DROP Transactions No, unless it's inside a transaction and you
command in PostgreSQL? ROLLBACK before commit.
PRACTICE Q2: Here are the most common types of coding examples they might ask, with
examples ready to go:
💻 1. Create a Table
"Write a SQL statement to create a table for storing student data."
🧱 2. Alter a Table
"Add a new column to store the student’s course name."
🗑️ 3. Truncate Table
"Write a command to delete all rows from the table without deleting the table
itself."
🧨 4. Drop Table
"Write a command to completely delete the Students table."
"You created a table but forgot to add an email column. Then you realize the table
name should be 'Users' instead of 'Accounts'. Fix it."
● Use the smallest possible data type that can accommodate the values you need to
store. For example, use SMALLINT instead of INT if the column will only contain
small integers.
● Use numeric data types such as INTEGER or DECIMAL for numeric values. Don't use
character data types to store numbers.
● Use character data types such as VARCHAR or CHAR for character data. Don't use
numeric data types to store character data.
● Use the appropriate data type for dates and times—e.g., DATE, TIME, or TIMESTAMP.
● Avoid using generic data types like VARCHAR without specifying a length, which can
lead to unexpected behavior.
● Be aware of the maximum and minimum values that can be stored in each data type,
and choose a data type that can accommodate the range of values you need to store.
🗓️ 1. DATE
● Stores just the calendar date (year, month, day)
● No time information
birth_date DATE;
-- Example: '2025-04-22'
⏰ 2. TIME
● Stores only the time of day (hours, minutes, seconds)
● No date
● Optionally with TIME WITHOUT TIME ZONE or TIME WITH TIME ZONE (rarely needed
unless you're dealing with different regions)
appointment_time TIME;
-- Example: '14:30:00'
🕒 3. TIMESTAMP
● Stores date + time
● Use TIMESTAMP WITHOUT TIME ZONE by default
● Or TIMESTAMP WITH TIME ZONE (often called timestamptz)
created_at TIMESTAMP;
-- Example: '2025-04-22 14:30:00'
🔄 Cheat Sheet
Type What It Stores Example Value
🔧 Basic Syntax:
EXTRACT(part FROM source)
● part = what you want to pull (like YEAR, MONTH, DAY, HOUR, etc.)
● source = your column or value
📦 Examples:
1. Get the year someone signed up:
SELECT *
FROM paper_world.product
WHERE EXTRACT(MONTH FROM production_date) = 4;
SELECT
EXTRACT(YEAR FROM production_date) AS prod_year,
COUNT(*) AS product_count
FROM paper_world.product
GROUP BY prod_year
ORDER BY prod_year;
⚠️ Note:
EXTRACT returns a double precision number (so you might see 2025.0), but you can cast it
to an integer if you want:
🔧 Example:
SELECT EXTRACT(YEAR FROM production_date)::INT
This means:
“Take the year from production_date and convert it into an integer.”
Because EXTRACT() gives you a double precision number (like 2025.0), if you want a clean
2025 (no decimal), you cast it to an INT (integer).
But most people just go with the :: — it’s shorter and more common in PostgreSQL.
What is VARCHAR(n)?
VARCHAR(2 Common default for text fields Emails, longer names, etc.
55)
● Functionally, VARCHAR(n) and TEXT are almost the same in PostgreSQL — there’s no
performance difference for most use cases.
● Validation: If you know a value shouldn’t be longer than 50 chars (e.g., first name),
use VARCHAR(50).
💡 Pro Tip:
If you’re not sure how long values will be, and length isn't important for validation or logic,
just go with TEXT.
does varchar contain string, how about mixed data with numbers
ChatGPT сказал: Yup — VARCHAR absolutely contains strings, and that includes any mix of:
Values like:
● 'X100'
● '1234-ABCD'
● 'BATCH2025'
All totally valid.
🧠 TL;DR:
Type Max Value Behind the scenes
⚠️ Small Note:
As of newer PostgreSQL versions (v10+), the recommendation is to use GENERATED syntax
instead:
You’ve defined a column that can hold integers... but nothing more:
● No default value ✅😬
😐
● No auto-increment
● No sequence
So when you insert a row, you must manually provide the ID every time:
And now you're the one tracking and avoiding duplicate IDs... which is 😩
🔥 If you use SERIAL:
user_id SERIAL PRIMARY KEY
SEQUENCE:
You're manually setting up a sequence to auto-generate IDs for the employee_role_id column
in the vendue.employee_role table.
🔍 Breakdown:
Creating the sequence:
CREATE SEQUENCE IF NOT EXISTS vendue.employee_role_id_seq START WITH 11000;
○ The START WITH 11000 part tells PostgreSQL to start the sequence at
11,000 (so the first ID generated will be 11000).
2.
○ ALTER TABLE modifies the employee_role table.
🌟 Example Walkthrough:
Step 1: When you insert a new row into employee_role, PostgreSQL will automatically use
nextval('employee_role_id_seq') to get the next number in the sequence.
INSERT INTO vendue.employee_role (employee_role_name) VALUES ('Manager');
● Step 2: PostgreSQL will automatically insert the next value in the sequence (11000
on the first insert, then 11001, 11002, etc.) into the employee_role_id column,
because you've set it as the default for that column.
The DELETE statement is actually part of DML (Data Manipulation Language), not DDL.
● DDL deals with defining, modifying, and dropping database structures like tables,
schemas, indexes, etc. (CREATE, ALTER, DROP)
● DML deals with data inside the tables, like inserting, updating, or deleting rows.
(SELECT, INSERT, UPDATE, DELETE)
That’s a DML statement, and it’s about manipulating the data in the table, not changing the
table structure.
This deletes the row where the employee_id is 5 from the employees table.
DDL CREATE, ALTER, DROP Defines or modifies database objects (e.g., tables)
It’s like the brain of the database 🧠 — holding all the information about:
● Databases
● Tables
● Columns
● Indexes
● Users/Roles
● Schemas
● Permissions
● Functions
● ...and more
🔎 So what's a schema, again?
Think of a schema like a folder or a namespace inside a database.
That’s actually:
But PostgreSQL lets you omit pg_catalog. because it’s in the default search path.
pg_namespac Schemas
e
pg_proc Functions/procedures
🧪 Try This:
-- See all system tables in pg_catalog
SELECT tablename
FROM pg_catalog.pg_tables
WHERE schemaname = 'pg_catalog';
or