SQL
SQL
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.
2. PROJECTS Table: Stores information about projects and the employees leading them.
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.
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:
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 |
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:
TotalEmployees
| :------------- |
|8 |
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
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.
Operation Description
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.
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.
General Syntax:
SQL
SELECT columns
FROM table1
JOIN_TYPE table2
ON join_condition;
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.)
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.