Unit 3: Relational Query Languages




What is a Relational Query Language?

When we store data in a database, we need a way to talk to the database — to create, read, update, or delete data.
This communication happens through a query language.

A Relational Query Language helps us to:

  • Ask questions (queries) from a relational database (like MySQL, Oracle, MS SQL Server, etc.).
  • Get the required information in an organized form (like a table).

What is SQL (Structured Query Language)?

SQL stands for Structured Query Language.
It is the standard language used to manage and manipulate databases.

In simple words:

SQL is like the language you use to “talk” to your database.

You can use SQL to:

  • Create a new table
  • Insert data
  • Update existing data
  • Delete data
  • Retrieve (view) data

Two Main Parts of SQL

SQL has many components, but two of the most important are:

  1. DDL – Data Definition Language
  2. DML – Data Manipulation Language

Let’s understand both in easy terms 

1. DDL (Data Definition Language)

DDL is used to define the structure of the database — such as tables, fields, and their data types.

It deals with how data is stored.

Think of DDL as setting up the foundation of your database.

Common DDL Commands:

CommandFull FormPurposeExample
CREATECreate a new table or databaseDefines structureCREATE TABLE students (id INT, name VARCHAR(50));
ALTERModify an existing tableAdd or remove columnsALTER TABLE students ADD age INT;
DROPDelete a table or database permanentlyRemoves structureDROP TABLE students;
TRUNCATEDelete all data but keep table structureRemoves data quicklyTRUNCATE TABLE students;
RENAMEChange the name of a tableUpdates nameRENAME TABLE students TO learners;

Key Point

  • DDL commands change the structure, not the actual data.
  • Changes made by DDL are automatically saved (no need for COMMIT).

2. DML (Data Manipulation Language)

DML is used to manipulate or manage the actual data inside tables.

Think of DML as working with the data that lives inside your database tables.

Common DML Commands:

CommandFull FormPurposeExample
INSERTAdd new data into a tableAdds a new rowINSERT INTO students VALUES (1, 'Jay', 22);
UPDATEChange existing dataModify rowsUPDATE students SET age = 23 WHERE id = 1;
DELETERemove data from a tableDeletes rowsDELETE FROM students WHERE id = 1;
SELECTRetrieve data from tableView informationSELECT * FROM students;

Key Point:

  • DML deals with data inside tables, not the table structure.
  • Changes made by DML are not permanent until you COMMIT them.

Example

Let’s say we are managing a Student Database.

Step 1: Create a Table (DDL)

CREATE TABLE Students ( Student_ID INT, Name VARCHAR(50), Age INT );

Step 2: Insert Data (DML)

INSERT INTO Students VALUES (1, 'Jay', 22);

Step 3: View Data (DML)

SELECT * FROM Students;

Step 4: Update Data (DML)

UPDATE Students SET Age = 23 WHERE Student_ID = 1;

Step 5: Delete Data (DML)

DELETE FROM Students WHERE Student_ID = 1;

Difference Between DDL and DML

BasisDDLDML
Full FormData Definition LanguageData Manipulation Language
PurposeDefines database structureManages data inside tables
ExamplesCREATE, ALTER, DROP, TRUNCATEINSERT, UPDATE, DELETE, SELECT
Type of OperationStructuralData-related
COMMIT Required?No (auto saved)Yes (manual save)

In Short:

  • DDL = “Design the table”
  • DML = “Work with the data in the table”

Structured Query Language (SQL) and Relational Algebra

Creating, Altering, and Deleting Tables (DDL Commands)

CREATE TABLE

Used to create a new table in the database.

Syntax:

CREATE TABLE table_name ( column1 datatype constraint, column2 datatype constraint, ... );

Example:

CREATE TABLE Employees ( EmpID INT PRIMARY KEY, Name VARCHAR(50), Salary DECIMAL(10,2), Department VARCHAR(30) );

ALTER TABLE

Used to add, modify, or delete a column in an existing table.

PurposeSyntax Example
Add a columnALTER TABLE Employees ADD Age INT;
Modify columnALTER TABLE Employees MODIFY Salary DECIMAL(12,2);
Delete a columnALTER TABLE Employees DROP COLUMN Age;

DROP TABLE

Used to delete the table permanently from the database.

DROP TABLE Employees;

Data Types in SQL

Data TypeDescriptionExample
INTWhole numbers100, -20
DECIMAL(p, q)Decimal numbers (p = total digits, q = digits after decimal)12.50
VARCHAR(n)Variable-length text'Jay'
CHAR(n)Fixed-length text'UP'
DATEStores date'2025-11-06'
BOOLEANTrue/False valuesTRUE

Constraints in SQL

Constraints are rules applied to table columns to maintain data accuracy and reliability.

ConstraintMeaningExample
PRIMARY KEYUnique & not nullEmpID INT PRIMARY KEY
FOREIGN KEYLinks two tablesDeptID INT FOREIGN KEY REFERENCES Department(DeptID)
NOT NULLCannot be emptyName VARCHAR(30) NOT NULL
UNIQUENo duplicate valuesEmail VARCHAR(50) UNIQUE
CHECKAdds a conditionCHECK (Salary > 10000)
DEFAULTSets a default valueSalary DECIMAL(10,2) DEFAULT 15000

Aggregate Functions

Aggregate functions are used to perform calculations on a group of values and return a single value.

FunctionDescriptionExample
COUNT()Counts number of rowsSELECT COUNT(*) FROM Employees;
SUM()Adds all valuesSELECT SUM(Salary) FROM Employees;
AVG()Finds average valueSELECT AVG(Salary) FROM Employees;
MAX()Finds highest valueSELECT MAX(Salary) FROM Employees;
MIN()Finds lowest valueSELECT MIN(Salary) FROM Employees;

Joins in SQL

A JOIN combines data from two or more tables based on a related column.

TypeDescriptionExample
INNER JOINReturns only matching records from both tablesSELECT E.Name, D.DeptName FROM Employees E INNER JOIN Department D ON E.DeptID = D.DeptID;
LEFT JOINReturns all records from left table + matched from rightSELECT E.Name, D.DeptName FROM Employees E LEFT JOIN Department D ON E.DeptID = D.DeptID;
RIGHT JOINReturns all records from right table + matched from leftSELECT E.Name, D.DeptName FROM Employees E RIGHT JOIN Department D ON E.DeptID = D.DeptID;
FULL JOINReturns all records when there is a match in either table(Some databases: FULL OUTER JOIN)

Sub-Queries

A Sub-query is a query inside another query.

Example:

SELECT Name, Salary FROM Employees WHERE Salary > (SELECT AVG(Salary) FROM Employees);

🟢 This shows employees earning more than the average salary.

Views

A View is a virtual table created using a SQL query.
It does not store data physically — it displays data from one or more tables.

Syntax:

CREATE VIEW HighSalary AS SELECT Name, Salary FROM Employees WHERE Salary > 50000;

Now you can use:

SELECT * FROM HighSalary;

Transaction Control Commands (TCL)

Used to manage changes made by DML (INSERT, UPDATE, DELETE) commands.

CommandPurposeExample
COMMITSaves the changes permanentlyCOMMIT;
ROLLBACKCancels the recent changesROLLBACK;
SAVEPOINTSets a point to which you can rollbackSAVEPOINT sp1;

Relational Algebra

Relational Algebra is a theoretical language for querying databases.
It uses operators to get results from relations (tables).

OperatorSymbol / CommandDescriptionExample
Selection (σ)σ condition (Table)Selects specific rowsσ Dept='HR' (Employees)
Projection (π)π column_list (Table)Selects specific columnsπ Name, Salary (Employees)
Join (⋈)Table1 ⋈ Table2Combines related tablesEmployees ⋈ Department
Union (∪)Table1 ∪ Table2Combines results (no duplicates)SELECT Name FROM TableA UNION SELECT Name FROM TableB;
Intersection (∩)Table1 ∩ Table2Returns common rowsSELECT Name FROM TableA INTERSECT SELECT Name FROM TableB;
Difference (−)Table1 − Table2Rows in first table, not in secondSELECT Name FROM TableA MINUS SELECT Name FROM TableB;

Relational Calculus

Relational Calculus is a non-procedural language
it focuses on what to get, not how to get it.

There are two types:

  1. Tuple Relational Calculus (TRC) → works on rows
  2. Domain Relational Calculus (DRC) → works on columns/attributes

Example (TRC):

{ t.Name | t ∈ Employees AND t.Salary > 50000 }

Means: Get the names of employees whose salary is greater than 50,000.

Summary Table

TopicKey PurposeExample
DDLDefine structureCREATE, ALTER, DROP
DMLManage dataINSERT, UPDATE, DELETE
AggregateSummarize dataSUM(), AVG()
JoinsCombine tablesINNER JOIN
Sub-queryQuery inside a queryWHERE Salary > (SELECT AVG(Salary))
ViewVirtual tableCREATE VIEW
TCLManage transactionsCOMMIT, ROLLBACK
Relational AlgebraTheoretical operationsSelection, Projection, Join
Relational CalculusNon-procedural queryTRC/DRC expressions