0% found this document useful (0 votes)
2 views18 pages

SQL

This document is a chapter from a Class 12 Informatics Practices curriculum focusing on SQL and querying data in relational databases. It covers the basics of databases, SQL commands, and functions, including single-row and aggregate functions, with practical examples using sample EMPLOYEES and PROJECTS tables. The chapter aims to equip students with the skills to retrieve and manipulate data effectively using SQL.

Uploaded by

ANE: Thundres
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views18 pages

SQL

This document is a chapter from a Class 12 Informatics Practices curriculum focusing on SQL and querying data in relational databases. It covers the basics of databases, SQL commands, and functions, including single-row and aggregate functions, with practical examples using sample EMPLOYEES and PROJECTS tables. The chapter aims to equip students with the skills to retrieve and manipulate data effectively using SQL.

Uploaded by

ANE: Thundres
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Date- 26/06/2025

Class 12 Informatics Practices (IP) - Code 065


Chapter: Querying and SQL Functions
Objective: This chapter focuses on retrieving and manipulating data stored in Relational Database Management
Systems (RDBMS) using SQL. You will learn how to ask specific questions (queries) to the database, use built-in
functions to process data, group data for summaries, and combine data from multiple tables.

1. Introduction to Relational Databases and SQL


What is a Database?
A database is an organized collection of data, typically stored and accessed electronically from a computer system.
It's like a highly structured and efficient digital filing cabinet designed to store vast amounts of information and allow
quick retrieval, modification, and management.
Real-Life Example:
Think of your school's student records system. It stores data like student names, admission numbers, classes, marks,
attendance, etc. All this information is organized in a database.
What is a Relational Database?
A relational database organizes data into one or more tables (relations) of rows and columns. Each row is a record,
and each column represents an attribute. Tables are related to each other through common columns, allowing you to
link and combine data.
Key Terms:
●​ Table (Relation): A collection of related data organized in rows and columns.
●​ Row (Tuple/Record): A single entry in a table, representing a complete set of data for one item.
●​ Column (Attribute/Field): A vertical entity in a table that contains all information associated with a specific field.
●​ Primary Key: A column (or set of columns) that uniquely identifies each row in a table. No two rows can have the
same primary key value.
●​ Foreign Key: A column (or set of columns) in one table that refers to the Primary Key in another table. It
establishes a link between tables.

What is SQL?
SQL (Structured Query Language) is the standard language used to communicate with and manage relational
databases. It allows you to create databases, define their structure, insert data, update data, delete data, and most
importantly for this chapter, retrieve data.
Key Categories of SQL Commands:
●​ DDL (Data Definition Language): Used to define and manage database structures (e.g., CREATE TABLE, ALTER
TABLE, DROP TABLE).
●​ DML (Data Manipulation Language): Used to manage data within database objects (e.g., INSERT, UPDATE,
DELETE, SELECT).
●​ DCL (Data Control Language): Used to control access to data (e.g., GRANT, REVOKE).
●​ TCL (Transaction Control Language): Used to manage transactions (e.g., COMMIT, ROLLBACK).

This chapter primarily focuses on the SELECT statement, which is part of DML, along with its various clauses
and functions for querying data.
2. Our Sample Database for Demonstrations
To make the practical demonstrations clear and relatable, we will use the following two tables. Imagine this is a
database for a small company.

1. EMPLOYEES Table: Stores information about company employees.

Column Name Data Type Description Key

EmpID INT Unique Employee Primary


Identification
Number

EmpName VARCHAR(50) Employee's Full


Name

Department VARCHAR(50) Department


Employee Belongs
To

Salary DECIMAL(10,2) Employee's


Monthly Salary

HireDate DATE Date Employee was


Hired

City VARCHAR(50) City Employee


Resides In

EMPLOYEES Table Data:

EmpID EmpName Departme Salary HireDate City


nt

101 Alice Smith HR 60000.00 2020-01-15 New York

102 Bob IT 75000.00 2019-03-2 London


Johnson 0

103 Carol White Sales 62000.00 2021-06-10 New York

104 David IT 80000.00 2018-11-01 London


Green
105 Eve Black HR 58000.00 2022-02-28 Paris

106 Frank Sales 70000.00 2019-09-0 New York


Brown 5

107 Grace Lee IT 78000.00 2020-07-12 New York

108 Henry HR 65000.00 2021-04-25 London


Wilson

2. PROJECTS Table: Stores information about projects and the employees leading them.

Column Name Data Type Description Key

ProjectID INT Unique Project Primary


Identification
Number

ProjectName VARCHAR(100) Name of the


Project

EmpID INT Employee ID Foreign


leading the project

StartDate DATE Project Start Date

EndDate DATE Project End Date

Budget DECIMAL(12,2) Project Budget

PROJECTS Table Data:

ProjectID ProjectNa EmpID StartDate EndDate Budget


me

1 HR Portal 101 2023-01-01 2023-06-3 150000.00


0

2 E-commerc 102 2022-10-15 2023-05-31 300000.0


e Site 0

3 Mobile App 104 2023-03-0 2023-09-3 250000.00


Dev 1 0
4 Sales CRM 103 2023-02-0 2023-07-15 100000.00
Update 1

5 Data 107 2023-04-0 2023-08-31 180000.00


Migration 1

6 New 105 2023-05-0 2023-10-31 80000.00


Employee 1
Onboarding

3. Functions in SQL
SQL functions are powerful tools that perform specific operations on data and return a single value. They can be
used in SELECT, WHERE, ORDER BY, and HAVING clauses. Functions are categorized into Single-Row Functions and
Aggregate (Multi-Row) Functions.

3.1 Single-Row Functions (Scalar Functions)


These functions operate on a single row at a time and return a single value for each row processed. They modify the
data item on which they operate.

Real-Life Example:
If you have a list of student names and want to capitalize the first letter of each name or find out how many
characters are in each name, you would use single-row functions. Each student's name is processed independently.
Table of Common Single-Row Functions:

Category Function Syntax Description


(Example)

Numeric ROUND(number, Rounds a number to a


decimal_places) specified number of
decimal places.

TRUNCATE(number, Truncates (cuts off) a


decimal_places) number to a specified
number of decimal places,
without rounding.

ABS(number) Returns the absolute


(non-negative) value of a
number.

MOD(dividend, divisor) Returns the remainder of a


division.

POWER(base, exponent) Returns the result of a


number raised to a power.

SQRT(number) Returns the square root of


a non-negative number.

String UPPER(string) Converts a string to


uppercase.

LOWER(string) Converts a string to


lowercase.

LENGTH(string) Returns the length (number


of characters) of a string.

SUBSTRING(string, start, Extracts a substring from a


length) string. start is the starting
position (1-indexed), length
is the number of characters
to extract.

CONCAT(string1, string2, Concatenates (joins) two or


...) more strings into one.

TRIM(string) Removes leading and


trailing spaces from a
string.

LEFT(string, length) Extracts a specified


number of characters from
the left side of a string.

RIGHT(string, length) Extracts a specified


number of characters from
the right side of a string.

Date/Time CURDATE() / Returns the current date


CURRENT_DATE() (YYYY-MM-DD).

CURTIME() / Returns the current time


CURRENT_TIME() (HH:MM:SS).

NOW() / Returns the current date


CURRENT_TIMESTAMP() and time (YYYY-MM-DD
HH:MM:SS).
YEAR(date) Extracts the year part from
a date.

MONTH(date) Extracts the month part


(1-12) from a date.

DAY(date) Extracts the day of the


month (1-31) from a date.

DATEDIFF(date1, date2) Calculates the difference in


days between two dates
(date1 - date2).

DATE_FORMAT(date, Formats a date value into a


format_string) string based on the
specified format. (e.g.,
%Y-%m-%d for
'2024-06-27')

Practical Demonstration (Single-Row Functions):

a) Numeric Functions:
●​ Query: Display employee name, salary, and salary rounded to the nearest whole number.​
SQL​
SELECT EmpName, Salary, ROUND(Salary, 0) AS RoundedSalary​
FROM EMPLOYEES;​

Output:​
| EmpName | Salary | RoundedSalary |​
| :------------ | :------- | :------------ |​
| Alice Smith | 60000.00 | 60000 |​
| Bob Johnson | 75000.00 | 75000 |​
| Carol White | 62000.00 | 62000 |​
| David Green | 80000.00 | 80000 |​
| Eve Black | 58000.00 | 58000 |​
| Frank Brown | 70000.00 | 70000 |​
| Grace Lee | 78000.00 | 78000 |​
| Henry Wilson | 65000.00 | 65000 |
●​ Query: Display the square root of the budget for each project.​
SQL​
SELECT ProjectName, Budget, SQRT(Budget) AS BudgetSqrt​
FROM PROJECTS;​

Output:​
| ProjectName | Budget | BudgetSqrt |​
| :---------------------- | :---------- | :-------------- |​
| HR Portal | 150000.00 | 387.29833462074 |​
| E-commerce Site | 300000.00 | 547.722557505166|​
| Mobile App Dev | 250000.00 | 500 |​
| Sales CRM Update | 100000.00 | 316.227766016838|​
| Data Migration | 180000.00 | 424.264068711928|​
| New Employee Onboarding | 80000.00 | 282.842712474619|

b) String Functions:
●​ Query: Display employee names in uppercase and their length.​
SQL​
SELECT EmpName, UPPER(EmpName) AS UppercaseName, LENGTH(EmpName) AS NameLength​
FROM EMPLOYEES;​

Output:​
| EmpName | UppercaseName | NameLength |​
| :------------ | :------------ | :--------- |​
| Alice Smith | ALICE SMITH | 11 |​
| Bob Johnson | BOB JOHNSON | 11 |​
| Carol White | CAROL WHITE | 11 |​
| David Green | DAVID GREEN | 11 |​
| Eve Black | EVE BLACK | 9 |​
| Frank Brown | FRANK BROWN | 11 |​
| Grace Lee | GRACE LEE | 9 |​
| Henry Wilson | HENRY WILSON | 12 |
●​ Query: Concatenate employee name and their department.​
SQL​
SELECT EmpName, Department, CONCAT(EmpName, ' (', Department, ')') AS EmployeeDepartment​
FROM EMPLOYEES;​

Output:​
| EmpName | Department | EmployeeDepartment |​
| :------------ | :---------- | :-------------------- |​
| Alice Smith | HR | Alice Smith (HR) |​
| Bob Johnson | IT | Bob Johnson (IT) |​
| Carol White | Sales | Carol White (Sales) |​
| David Green | IT | David Green (IT) |​
| Eve Black | HR | Eve Black (HR) |​
| Frank Brown | Sales | Frank Brown (Sales) |​
| Grace Lee | IT | Grace Lee (IT) |​
| Henry Wilson | HR | Henry Wilson (HR) |
●​ Query: Get the first 3 characters of each department name.​
SQL​
SELECT Department, SUBSTRING(Department, 1, 3) AS DeptCode​
FROM EMPLOYEES;​

Output:​
| Department | DeptCode |​
| :---------- | :------- |​
| HR | HR |​
| IT | IT |​
| Sales | Sal |​
| IT | IT |​
| HR | HR |​
| Sales | Sal |​
| IT | IT |​
| HR | HR |

c) Date/Time Functions:
●​ Query: Display employee name, hire date, and the year they were hired.​
SQL​
SELECT EmpName, HireDate, YEAR(HireDate) AS JoiningYear​
FROM EMPLOYEES;​

Output:​
| EmpName | HireDate | JoiningYear |​
| :------------ | :--------- | :---------- |​
| Alice Smith | 2020-01-15 | 2020 |​
| Bob Johnson | 2019-03-20 | 2019 |​
| Carol White | 2021-06-10 | 2021 |​
| David Green | 2018-11-01 | 2018 |​
| Eve Black | 2022-02-28 | 2022 |​
| Frank Brown | 2019-09-05 | 2019 |​
| Grace Lee | 2020-07-12 | 2020 |​
| Henry Wilson | 2021-04-25 | 2021 |
●​ Query: Calculate the number of days a project lasted.​
SQL​
SELECT ProjectName, StartDate, EndDate, DATEDIFF(EndDate, StartDate) AS DurationInDays​
FROM PROJECTS;​

Output:​
| ProjectName | StartDate | EndDate | DurationInDays |​
| :---------------------- | :--------- | :--------- | :------------- |​
| HR Portal | 2023-01-01 | 2023-06-30 | 180 |​
| E-commerce Site | 2022-10-15 | 2023-05-31 | 228 |​
| Mobile App Dev | 2023-03-01 | 2023-09-30 | 213 |​
| Sales CRM Update | 2023-02-01 | 2023-07-15 | 164 |​
| Data Migration | 2023-04-01 | 2023-08-31 | 152 |​
| New Employee Onboarding | 2023-05-01 | 2023-10-31 | 183 |
●​ Query: Display the current date and time.​
SQL​
SELECT CURDATE() AS CurrentDate, CURTIME() AS CurrentTime, NOW() AS CurrentDateTime;​

Output (will vary based on execution time):​
| CurrentDate | CurrentTime | CurrentDateTime |​
| :---------- | :---------- | :------------------ |​
| 2024-06-27 | 10:25:26 | 2024-06-27 10:25:26 |

3.2 Aggregate Functions (Multi-Row Functions / Group Functions)


These functions operate on a set of rows (a group) and return a single summary value for the entire group. They
are commonly used with the GROUP BY clause.

Real-Life Example:
If you have a list of marks for all students in a class and want to find the average mark of the class, the highest mark,
or the total number of students, you would use aggregate functions.
Table of Common Aggregate Functions:

Function Syntax (Example) Description

COUNT(column_name) Counts the number of non-NULL values in


a specified column.

COUNT(*) Counts the total number of rows in a table


or a group, including NULLs.

SUM(numeric_column) Calculates the sum of values in a numeric


column.

AVG(numeric_column) Calculates the average of values in a


numeric column.

MIN(column_name) Finds the minimum value in a column


(numeric, string, or date).

MAX(column_name) Finds the maximum value in a column


(numeric, string, or date).

Practical Demonstration (Aggregate Functions):


●​ Query: Count the total number of employees in the company.​
SQL​
SELECT COUNT(*) AS TotalEmployees​
FROM EMPLOYEES;​

Output:

TotalEmployees

| :------------- |​
|8 |​

●​ Query: Calculate the total and average salary of all employees.​


SQL​
SELECT SUM(Salary) AS TotalSalary, AVG(Salary) AS AverageSalary​
FROM EMPLOYEES;​

Output:​
| TotalSalary | AverageSalary |​
| :---------- | :------------ |​
| 548000.00 | 68500.0000 |
●​ Query: Find the minimum and maximum salary paid in the company.​
SQL​
SELECT MIN(Salary) AS MinimumSalary, MAX(Salary) AS MaximumSalary​
FROM EMPLOYEES;​

Output:​
| MinimumSalary | MaximumSalary |​
| :------------ | :------------ |​
| 58000.00 | 80000.00 |
●​ Query: Find the earliest and latest hire dates.​
SQL​
SELECT MIN(HireDate) AS EarliestHire, MAX(HireDate) AS LatestHire​
FROM EMPLOYEES;​

Output:​
| EarliestHire | LatestHire |​
| :----------- | :--------- |​
| 2018-11-01 | 2022-02-28 |

4. Group By in SQL
The GROUP BY clause is used in conjunction with aggregate functions to group rows that have the same values in
specified columns into summary rows. For each group, the aggregate function then calculates a single value.

Real-Life Example:
If your school wants to know the total number of students in each class, or the average marks obtained by students in
each section of a class, you would use GROUP BY. You are summarizing data per group.
Syntax:

SQL

SELECT column1, aggregate_function(column2)​


FROM table_name​
WHERE condition -- Filters individual rows BEFORE grouping​
GROUP BY column1, column3, ... -- Specifies columns to group by​
HAVING aggregate_condition -- Filters groups AFTER grouping and aggregation​
ORDER BY column1; -- Sorts the final result set​
●​ Important Rule for SELECT with GROUP BY: Any column in the SELECT list that is not an aggregate function
must also be present in the GROUP BY clause. This is because you are asking for a single value per group, and
non-aggregated columns must define those groups.
●​ HAVING vs. WHERE:
○​ WHERE filters individual rows before grouping and aggregation.
○​ HAVING filters groups after grouping and aggregation, based on the result of an aggregate function.

Practical Demonstration (GROUP BY):


●​ Query: Count the number of employees in each department.​
SQL​
SELECT Department, COUNT(*) AS NumberOfEmployees​
FROM EMPLOYEES​
GROUP BY Department;​

Output:​
| Department | NumberOfEmployees |​
| :---------- | :---------------- |​
| HR | 3 |​
| IT | 3 |​
| Sales | 2 |
●​ Query: Calculate the average salary for each city.​
SQL​
SELECT City, AVG(Salary) AS AverageSalaryPerCity​
FROM EMPLOYEES​
GROUP BY City;​

Output:​
| City | AverageSalaryPerCity |​
| :--------- | :------------------- |​
| London | 73333.3333 |​
| New York | 67500.0000 |​
| Paris | 58000.0000 |
●​ Query: Find departments where the average salary is greater than $65,000.​
SQL​
SELECT Department, AVG(Salary) AS AverageSalary​
FROM EMPLOYEES​
GROUP BY Department​
HAVING AVG(Salary) > 65000;​

Output:​
| Department | AverageSalary |​
| :---------- | :------------ |​
| IT | 77666.6666 |​
| Sales | 66000.0000 |
●​ Query: Count the number of employees for each Department and City combination.​
SQL​
SELECT Department, City, COUNT(*) AS NumberOfEmployees​
FROM EMPLOYEES​
GROUP BY Department, City​
ORDER BY Department, City;​

Output:​
| Department | City | NumberOfEmployees |​
| :---------- | :--------- | :---------------- |​
| HR | London | 1 |​
| HR | New York | 1 |​
| HR | Paris | 1 |​
| IT | London | 1 |​
| IT | New York | 2 |​
| Sales | New York | 2 |

5. Operations on Relations (Set Operations)


Set operations combine the results of two or more SELECT statements. For these operations to work correctly, the
SELECT statements must return the same number of columns, and the corresponding columns must have compatible
data types.

Real-Life Example:
Imagine you have a list of all students participating in the "Annual Sports Day" and another list of students
participating in the "Science Exhibition."
●​ UNION: Would give you a single list of all unique students participating in either event.
●​ UNION ALL: Would give you a list of all students from both events, including duplicates (if a student is in both
lists, they appear twice).
●​ INTERSECT: Would give you only the students who participated in both the Sports Day and the Science
Exhibition.
●​ EXCEPT: Would give you students who participated in Sports Day but not the Science Exhibition.

Table of Set Operations:

Operation Description

UNION Combines the result sets of two or more


SELECT statements, returning only distinct
rows.

UNION ALL Combines the result sets of two or more


SELECT statements, returning all rows,
including duplicates.

INTERSECT Returns only the rows that are common to


all the combined SELECT statements. (Not
directly supported in MySQL, common in
other RDBMS like PostgreSQL, SQL Server).

EXCEPT Returns rows from the first SELECT


statement that are not present in the
second SELECT statement. (Some SQL
dialects use MINUS. Not directly supported
in MySQL).

Practical Demonstration (Operations on Relations):

To demonstrate, let's create a temporary hypothetical scenario.

Scenario: We want to find common cities or different cities where employees work or where projects are being led by
employees.
●​ UNION Example: Find all unique cities where employees reside OR where projects are being led (based on the
project lead's city).
○​ First part: Cities where employees live.
○​ Second part: Cities where employees leading projects live.
<!-- end list -->SQL​
SELECT City FROM EMPLOYEES​
UNION​
SELECT E.City​
FROM EMPLOYEES E​
INNER JOIN PROJECTS P ON E.EmpID = P.EmpID;​
Explanation: The first SELECT gets all cities from the EMPLOYEES table. The second SELECT identifies the cities of
employees who are leading projects. UNION combines these two sets, removing duplicate city names.Output:
City

| :--------- |​
| New York |​
| London |​
| Paris |​

●​ UNION ALL Example: Get all cities where employees reside, including duplicates, and also the cities of
employees leading projects.​
SQL​
SELECT City FROM EMPLOYEES​
UNION ALL​
SELECT E.City​
FROM EMPLOYEES E​
INNER JOIN PROJECTS P ON E.EmpID = P.EmpID;​

Output:

City

| :--------- |​
| New York |​
| London |​
| New York |​
| London |​
| Paris |​
| New York |​
| New York |​
| London |​
| New York | -- From EmpID 101, Project 1​
| London | -- From EmpID 102, Project 2​
| London | -- From EmpID 104, Project 3​
| New York | -- From EmpID 103, Project 4​
| New York | -- From EmpID 107, Project 5​
| Paris | -- From EmpID 105, Project 6​
*(Note: The exact order might vary, but all cities will be listed as many times as they appear in either result set.)*​

●​ INTERSECT Example (MySQL workaround): Find cities where employees reside AND where employees leading
projects also reside.​
(As INTERSECT is not directly supported in MySQL, we use a JOIN or IN clause to achieve the same logic.)​
SQL​
SELECT DISTINCT E.City​
FROM EMPLOYEES E​
INNER JOIN PROJECTS P ON E.EmpID = P.EmpID;​

Explanation: This query directly finds the cities of employees who are linked to projects. Since the PROJECTS
table's EmpID is a foreign key to EMPLOYEES, any EmpID in PROJECTS must exist in EMPLOYEES. Thus, joining
them and selecting distinct cities from EMPLOYEES gives us the cities where project-leading employees reside.
This effectively acts as an INTERSECT between "all employee cities" and "cities of project leaders".​
Output:

City

| :--------- |​
| New York |​
| London |​
| Paris |​

●​ EXCEPT Example (MySQL workaround): Find cities where employees reside but no project-leading employee
resides there.​
(As EXCEPT is not directly supported in MySQL, we use NOT IN or LEFT JOIN with IS NULL.)​
SQL​
SELECT DISTINCT City​
FROM EMPLOYEES​
WHERE City NOT IN (SELECT E.City FROM EMPLOYEES E INNER JOIN PROJECTS P ON E.EmpID = P.EmpID);​

Explanation: This query selects all distinct cities from the EMPLOYEES table, then filters out any city that is also
found in the subquery (which lists cities of employees leading projects). In our current dataset, all employee
cities have at least one employee leading a project (101-New York, 102-London, 103-New York, 104-London,
105-Paris, 107-New York). So, there are no cities where an employee resides but no project-leading employee
resides.​
Output:
City

| :--- |​
| |​
*(Empty set, as all cities with employees also have employees leading projects in our sample data.)*​

**Let's imagine a scenario where there *would* be output for `EXCEPT`:**​
If `EmpID` 108 (Henry Wilson, London) was NOT involved in any project, and no other employee from London was
either. Then 'London' would appear if London was in the main `SELECT` but not in the subquery.​
In our current data, cities are 'New York', 'London', 'Paris'. All these cities have at least one project lead from them. So,
the result is empty.​

6. Using Two Relations in a Query (JOINs)


Data in relational databases is often spread across multiple tables to avoid redundancy and improve organization.
JOIN operations are fundamental for combining rows from two or more tables based on related columns between
them.

Real-Life Example:
If you have a table of "Student Details" (Student ID, Name, Class) and another table of "Marks" (Student ID, Subject,
Score). To get a report showing "Student Name, Subject, Score," you need to JOIN these two tables using the
common "Student ID."
Types of JOINs:
1.​ INNER JOIN:
○​ Description: Returns only the rows where there is a match in both tables based on the join condition. Rows
that do not have a match in both tables are excluded.
○​ Analogy: Finding students who are both registered and have submitted marks (i.e., common students in
both lists).
2.​ LEFT JOIN (or LEFT OUTER JOIN):
○​ Description: Returns all rows from the left table, and the matching rows from the right table. If there is no
match for a row in the right table, NULL values are returned for columns from the right table.
○​ Analogy: Getting a list of all registered students, and if they have submitted marks, show their marks;
otherwise, just show their name.
3.​ RIGHT JOIN (or RIGHT OUTER JOIN):
○​ Description: Returns all rows from the right table, and the matching rows from the left table. If there is no
match for a row in the left table, NULL values are returned for columns from the left table.
○​ Analogy: Getting a list of all subjects for which marks were submitted, and if a student is linked, show their
name; otherwise, just show the subject.
4.​ CROSS JOIN:
○​ Description: Produces a Cartesian product of the two tables. Every row from the first table is combined with
every row from the second table. This generally results in a very large number of rows
(textrowsoftable1timestextrowsoftable2).
○​ Analogy: Combining every student with every possible subject, even if they didn't take it. Rarely used
directly, but important for understanding joins.

5.​ SELF JOIN:


○​ Description: A regular join operation where a table is joined with itself. This is typically used when you need
to compare rows within the same table. An alias is essential for this.
○​ Analogy: Finding pairs of students who live in the same city from a single student address list.

General Syntax:

SQL

SELECT columns​
FROM table1​
JOIN_TYPE table2​
ON join_condition;​

Or for older syntax:

SQL

SELECT columns​
FROM table1, table2​
WHERE join_condition;​

(The explicit JOIN syntax with ON is preferred as it clearly separates join conditions from filter conditions.)

Practical Demonstration (Using Two Relations - JOINs):


●​ INNER JOIN Example: List all employees and the projects they are currently leading.​
SQL​
SELECT E.EmpName, P.ProjectName, P.Budget​
FROM EMPLOYEES AS E​
INNER JOIN PROJECTS AS P​
ON E.EmpID = P.EmpID;​

Explanation: This query links EMPLOYEES and PROJECTS tables where EmpID matches in both. Only employees
who have a corresponding project in the PROJECTS table will appear.​
Output:​
| EmpName | ProjectName | Budget |​
| :------------ | :---------------------- | :---------- |​
| Alice Smith | HR Portal | 150000.00 |​
| Bob Johnson | E-commerce Site | 300000.00 |​
| Carol White | Sales CRM Update | 100000.00 |​
| David Green | Mobile App Dev | 250000.00 |​
| Eve Black | New Employee Onboarding | 80000.00 |​
| Grace Lee | Data Migration | 180000.00 |
●​ LEFT JOIN Example: List all employees and any projects they are leading. If an employee is not leading any
project, still list their name with NULL for project details.​
SQL​
SELECT E.EmpName, E.Department, P.ProjectName​
FROM EMPLOYEES AS E​
LEFT JOIN PROJECTS AS P​
ON E.EmpID = P.EmpID;​

Explanation: This query returns all employees from the EMPLOYEES table (left table). If a match is found in
PROJECTS, project details are shown. If no match, ProjectName will be NULL. Notice Frank Brown and Henry
Wilson appear here, who were excluded from the INNER JOIN output.​
Output:​
| EmpName | Department | ProjectName |​
| :------------ | :---------- | :---------------------- |​
| Alice Smith | HR | HR Portal |​
| Bob Johnson | IT | E-commerce Site |​
| Carol White | Sales | Sales CRM Update |​
| David Green | IT | Mobile App Dev |​
| Eve Black | HR | New Employee Onboarding |​
| Frank Brown | Sales | NULL |​
| Grace Lee | IT | Data Migration |​
| Henry Wilson | HR | NULL |
●​ RIGHT JOIN Example: List all projects and the employee leading them. If a project hypothetically had no
employee assigned (not possible with our current data, as EmpID is a foreign key), it would still appear with NULL
for employee details.​
SQL​
SELECT P.ProjectName, P.Budget, E.EmpName​
FROM EMPLOYEES AS E​
RIGHT JOIN PROJECTS AS P​
ON E.EmpID = P.EmpID;​

Explanation: This query returns all projects from the PROJECTS table (right table). If a match is found in
EMPLOYEES, employee details are shown. In our current data, all projects have an assigned EmpID that exists in
the EMPLOYEES table, so the output will be similar to an INNER JOIN for these columns.​
Output:​
| ProjectName | Budget | EmpName |​
| :---------------------- | :---------- | :------------ |​
| HR Portal | 150000.00 | Alice Smith |​
| E-commerce Site | 300000.00 | Bob Johnson |​
| Mobile App Dev | 250000.00 | David Green |​
| Sales CRM Update | 100000.00 | Carol White |​
| Data Migration | 180000.00 | Grace Lee |​
| New Employee Onboarding | 80000.00 | Eve Black |
●​ SELF JOIN Example: Find pairs of employees who work in the same city.​
SQL​
SELECT A.EmpName AS Employee1, B.EmpName AS Employee2, A.City​
FROM EMPLOYEES AS A, EMPLOYEES AS B​
WHERE A.City = B.City​
AND A.EmpID <> B.EmpID; -- To avoid pairing an employee with themselves​

Explanation: We treat the EMPLOYEES table as two separate tables (aliased as A and B). We then join them on
the condition that their City is the same, but their EmpID is different (to avoid matching an employee with
themselves).​
Output:​
| Employee1 | Employee2 | City |​
| :------------ | :------------ | :--------- |​
| Alice Smith | Carol White | New York |​
| Alice Smith | Frank Brown | New York |​
| Alice Smith | Grace Lee | New York |​
| Bob Johnson | David Green | London |​
| Bob Johnson | Henry Wilson | London |​
| Carol White | Alice Smith | New York |​
| Carol White | Frank Brown | New York |​
| Carol White | Grace Lee | New York |​
| David Green | Bob Johnson | London |​
| David Green | Henry Wilson | London |​
| Frank Brown | Alice Smith | New York |​
| Frank Brown | Carol White | New York |​
| Frank Brown | Grace Lee | New York |​
| Grace Lee | Alice Smith | New York |​
| Grace Lee | Carol White | New York |​
| Grace Lee | Frank Brown | New York |​
| Henry Wilson | Bob Johnson | London |​
| Henry Wilson | David Green | London |

This revised explanation should be perfectly aligned with the NCERT Class 12 IP (065) curriculum, providing clear,
neat, and direct explanations with consistent examples and their outputs.

You might also like