Subqueries Operators and Derived Tables in SQL
Subqueries Operators and Derived Tables in SQL
Problem Statement: You work as a junior analyst at your organization. You must help the
HR department create employee information, project details, and project assignment tables
in one of the databases so that managers from all departments can monitor the status and
progress of ongoing projects.
Objective: Build the appropriate database and table structures for storing the required
manager-specific data.
Step 1: Create a database named PROJ_DB with the CREATE DATABASE statement.
SQL Query
Step 2: Set PROJ_DB as the default database in MySQL with the USE statement.
SQL Query
USE PROJ_DB;
Use Case: Project and Team Management
Step 3: Set INNODB as the default storage engine for PROJ_DB database in MySQL with the SET
statement.
SQL Query
The managers have provided a detailed description of the required employee table given below.
Step 4: Create the required EMP_RECORDS table in the PROJ_DB database with the CREATE
TABLE statement as given below.
SQL Query
CREATE TABLE IF NOT EXISTS PROJ_DB.EMP_RECORDS (
LAST_NAME VARCHAR(100),
MANAGER_ID VARCHAR(100),
) ENGINE=INNODB;
Use Case: Project and Team Management
Step 5: Analyze the structure of the EMP_RECORDS table with the DESCRIBE statement.
Output:
SQL Query
DESCRIBE PROJ_DB.EMP_RECORDS;
Use Case: Project and Team Management
Step 6: Insert the required data from the downloaded EMP_RECORDS.csv file into the
EMP_RECORDS table as shown below.
SQL Query
INSERT INTO
PROJ_DB.EMP_RECORDS(EMP_ID,FIRST_NAME,LAST_NAME,GENDER,ROLE,DEPT,EXP,COUNTRY,CONTINENT,MANAGE
R_ID)
VALUES
("E083","Patrick","Voltz","M","MANAGER","HEALTHCARE",15,"USA","NORTH AMERICA","E002"),
...
...
("E002","Cynthia","Brooks","F","PRESIDENT","ALL",17,"CANADA","NORTH AMERICA","E001"),
("E001","Arthur","Black","M","CEO","ALL",20,"USA","NORTH AMERICA","E001");
Use Case: Project and Team Management
Step 7: Analyze the data entered into the EMP_RECORDS table with the SELECT statement.
SQL Query
Output:
Use Case: Project and Team Management
Similarly, the managers have provided a detailed description of the required projects table
given below.
PROJ_NAME A unique name assigned to each project based on the client requirements and application domain
START _DATE The planned date within the DEV_QTR for starting the project development (Format - YYYY-MM-DD)
CLOSURE_DATE The planned date within the DEV_QTR for finishing the project development (Format - YYYY-MM-DD)
DEV_QTR The quarter in the current financial year selected for end-to-end development of the project
The development status of the project as YTS (Yet To Start), WIP (Work In Progress), DONE (Finished on
STATUS
time), and DELAYED (Delayed and Ongoing)
Use Case: Project and Team Management
Step 8: Create the required PROJ_RECORDS table in the PROJ_DB database with the CREATE
TABLE statement as given below.
SQL Query
CREATE TABLE IF NOT EXISTS PROJ_DB.PROJ_RECORDS (
STATUS VARCHAR(7),
) ENGINE=INNODB;
Use Case: Project and Team Management
Step 9: Analyze the structure of the EMP_RECORDS table with the DESCRIBE statement.
Output:
SQL Query
DESCRIBE PROJ_DB.PROJ_RECORDS;
Use Case: Project and Team Management
Step 10: Insert the required data from the downloaded PROJ_RECORDS.csv file into the
PROJ_RECORDS table as shown below.
SQL Query
INSERT INTO
PROJ_DB.PROJ_RECORDS(PROJ_ID,PROJ_NAME,DOMAIN,START_DATE,CLOSURE_DATE,DEV_QTR,STATUS)
VALUES
("P103","Drug Discovery","HEALTHCARE","2021-04-06","2021-06-20","Q1","DONE"),
("P105","Fraud Detection","FINANCE","2021-04-11","2021-06-25","Q1","DONE"),
...
...
Step 11: Analyze the data entered into the PROJ_RECORDS table with the SELECT statement.
SQL Query
Output:
Use Case: Project and Team Management
Also, the managers have provided a detailed description of the required project assignment
table, which links each individual's employee ID to the project ID of the project to which they
have been assigned.
Step 12: Create the required PROJ_ASSIGN table in the PROJ_DB database with the CREATE
TABLE statement as given below.
SQL Query
) ENGINE=INNODB;
Use Case: Project and Team Management
Step 13: Analyze the structure of the PROJ_ASSIGN table with the DESCRIBE statement.
SQL Query
DESCRIBE PROJ_DB.PROJ_ASSIGN;
Output:
Use Case: Project and Team Management
Step 14: Insert the required data from the downloaded PROJ_ASSIGN.csv file into the
PROJ_RECORDS table as shown below.
SQL Query
VALUES ("E052","P103"),
("E505","P103"),
...
...
("E083","P103");
Use Case: Project and Team Management
Step 15: Analyze the data entered into the PROJ_ASSIGN table with the SELECT statement.
Output:
SQL Query
SQL
subquery
If an alias contains space, it must be enclosed in quotation marks.
Syntax
SELECT
[column_1 | expression] AS
column_alias_name
FROM
table_name;
A column alias cannot be used in the WHERE clause because the WHERE
clause is evaluated before the values of columns specified in the SELECT
statement during query execution in MySQL.
Column Alias
Problem Statement: Your manager expects you to identify the last and first names of all the
employees from the healthcare department.
Objective: Write two MySQL queries, one omitting the column alias and the other including
it to list the last and first names of all employees of the healthcare department.
Column Alias: Example
Step 1: Use the CONCAT_WS function in the SELECT statement as given below.
SQL Query
FROM PROJ_DB.EMP_RECORDS
Output:
Column Alias: Example
Step 2: Use the CONCAT_WS function in the SELECT statement followed by the AS keyword as
given below.
SQL Query
FROM PROJ_DB.EMP_RECORDS
Output:
Table Alias
Syntax
SELECT
[column_1 | expression], column_2
FROM
table_name AS table_alias_name;
Table aliases are preferred when there are multiple tables involved in an SQL
query. It helps in collecting data and connecting the tables via field relations.
Table Alias
Problem Statement: Your manager expects you to identify the first and last names of all the
employees separately from the healthcare department.
Objective: Write a MySQL queries to list the first name and last name of all employees from
the healthcare department using a table alias to refer to the table.
Table Alias: Example
Step 1: Use the SELECT statement with an alias name for the table as given below.
FROM PROJ_DB.EMP_RECORDS e
Output:
Introduction to JOINS
JOINS in MySQL
Problem Statement: Your manager expects you to identify employees assigned to projects.
Objective: Write an SQL query using the INNER JOIN clause with either ON or USING
keyword to perform the inner join on the EMP_RECORDS and PROJ_ASSIGN tables in
MySQL.
INNER JOIN: Example
Step 1: Use the INNER JOIN clause with the ON keyword in the SELECT statement to join
EMP_RECORDS and PROJ_ASSIGN tables as given below.
SELECT
e.DEPT, e.MANAGER_ID,
p.PROJ_ID
FROM
EMP_RECORDS e
ORDER BY e.MANAGER_ID;
INNER JOIN: Example
Step 2: Use the INNER JOIN clause with the USING keyword in the SELECT statement to join
EMP_RECORDS and PROJ_ASSIGN tables as given below.
SELECT
e.DEPT, e.MANAGER_ID,
p.PROJ_ID
FROM
EMP_RECORDS e
ORDER BY e.MANAGER_ID;
LEFT JOIN
The LEFT JOIN selects all data from the left table, regardless of
whether there are matching rows in the right table.
Syntax
SELECT column_list
FROM table_1
LEFT JOIN table_2 ON join_condition;
If no matching rows from the right table are found, the LEFT JOIN utilizes
NULLs in the result set for columns of the row from the right table.
LEFT JOIN: Example
Problem Statement: Your manager wants the details of the ongoing projects along with the
number of employees working on them.
Objective: Write an SQL query using the LEFT JOIN clause with either ON or USING
keyword to perform the left join on the PROJ_RECORDS and PROJ_ASSIGN tables in MySQL.
LEFT JOIN: Example
Step 1: Use the LEFT JOIN clause with the ON keyword in the SELECT statement to join
PROJ_RECORDS and PROJ_ASSIGN tables as given below.
SELECT
p.DEV_QTR, p.STATUS
FROM
PROJ_RECORDS p
GROUP BY p.PROJ_NAME
ORDER BY p.PROJ_ID;
LEFT JOIN: Example
Step 2: Use the LEFT JOIN clause with the USING keyword in the SELECT statement to join
PROJ_RECORDS and PROJ_ASSIGN tables as given below.
SELECT
p.DEV_QTR, p.STATUS
FROM
PROJ_RECORDS p
GROUP BY p.PROJ_NAME
ORDER BY p.PROJ_ID;
RIGHT JOIN
The RIGHT JOIN selects all data from the right table, regardless of
whether there are matching rows in the left table.
Syntax
SELECT column_list
FROM table_1
RIGHT JOIN table_2 ON join_condition;
If no matching rows from the left table are found, the RIGHT JOIN utilizes
NULLs in the result set for columns of the row from the left table.
RIGHT JOIN: Example
Problem Statement: Your manager wants the details of each employee along with the
number of projects assigned to them.
Objective: Write an SQL query using the RIGHT JOIN clause with either ON or USING
keyword to perform the left join on the EMP_RECORDS and PROJ_ASSIGN tables in MySQL.
RIGHT JOIN: Example
Step 1: Use the RIGHT JOIN clause with the ON keyword in the SELECT statement to join
EMP_RECORDS and PROJ_ASSIGN tables as given below.
SELECT
FROM
PROJ_ASSIGN a
GROUP BY e.EMP_ID
ORDER BY e.MANAGER_ID;
RIGHT JOIN: Example
Step 2: Use the RIGHT JOIN clause with the USING keyword in the SELECT statement to join
EMP_RECORDS and PROJ_ASSIGN tables as given below.
SELECT
FROM
PROJ_ASSIGN a
GROUP BY e.EMP_ID
ORDER BY e.MANAGER_ID;
CROSS JOIN
Syntax
SELECT select_list
FROM table_1
CROSS JOIN table_2;
CROSS JOIN: Example
Problem Statement: Your manager expects you to perform the cartesian product of the
rows in both the employee and project records tables.
Objective: Write an SQL query using the CROSS JOIN clause to perform the cross join on
the EMP_RECORDS and PROJ_ASSIGN tables to obtain their cartesian product in MySQL.
CROSS JOIN: Example
Step 1: Use the CROSS JOIN clause in the SELECT statement to join EMP_RECORDS and
PROJ_ASSIGN tables as given below.
SELECT
e.DEPT, e.MANAGER_ID,
a.PROJ_ID
FROM
PROJ_ASSIGN a
ORDER BY e.FIRST_NAME;
SELF JOIN
The SELF JOIN clause joins a table to itself using the INNER JOIN or LEFT JOIN.
The SELF JOIN is often used to query hierarchical data or to compare rows
within the same table.
SELF
JOIN
To perform a SELF JOIN, table aliases must be used to avoid repeating the
same table name in a single query.
Problem Statement: Your manager wants you to identify the number of employees
reporting to each manager including the President and the CEO.
Objective: Write an SQL query using either INNER JOIN or LEFT JOIN clause to simulate
the SELF JOIN clause on the EMP_RECORDS table in MySQL.
SELF JOIN: Example
Step 1: Use the INNER JOIN clause in the SELECT statement to simulate the SELF JOIN clause to
join EMP_RECORDS table as given below.
FROM
EMP_RECORDS m
ON m.EMP_ID = e.MANAGER_ID
GROUP BY m.EMP_ID
ORDER BY m.EMP_ID;
SELF JOIN: Example
Step 2: Use the LEFT JOIN clause in the SELECT statement to simulate the SELF JOIN clause to
join EMP_RECORDS table as given below.
FROM
EMP_RECORDS m
ON m.EMP_ID = e.MANAGER_ID
GROUP BY m.EMP_ID
ORDER BY m.EMP_ID;
Assisted Practice: Joins One
Duration: 15 mins
Problem statement: Assume that you have organized a quiz in your company and that people from different
offices across the world have participated. You have been asked to analyze the quiz data to understand
participation data and prize distribution across geographies.
You will be referring to the following datasets:
participant - This dataset contains information about the people who participated in the quiz and has 1000
rows and 11 columns
states - This dataset contains information about the states’ names, codes, regions, and the division a participant
belongs to and has 50 rows and 4 columns
Assisted Practice: Joins One
Step 01: Upload the participant and states datasets in the lab
1. Download these datasets from the Course Resources section of the LMS
2. In the file explorer area in the lab, click on the work tab and then click on the Upload button to upload
the datasets
Assisted Practice: Joins One
Step 03: Write a query to show the two tables (participant and state)
QUERY
Output:
Assisted Practice: Joins One
Step 04: Create a dataset containing the information on how many shirts need to be shipped to each state,
filter the data for the top five states with the most shirt shipments, and ensure data has the state’s name and
not just the two-letter codes
CREATE
SELECT s.state_name, COUNT(p.shirt_or_hat)
FROM states s JOIN participant p
ON s.state_code = p.state_code
WHERE p.shirt_or_hat='shirt'
GROUP BY s.state_name
ORDER BY COUNT(p.shirt_or_hat) DESC
LIMIT 5
Assisted Practice: Joins One
Output:
Assisted Practice: Joins One
Step 05: Write a query to collect the sorted information showing how many members of each team
are in each division and pull the bottom three divisions with the least members
SQL Query
Output:
Assisted Practice: Joins Two
Duration: 15 mins
Problem statement: You are working as a database administrator for an insurance firm. The head of the
insurance campaign planning department of your organization is looking for a dataset containing the
information of customers who have claimed an amount only under the B2C category and not under the B2B
category.
Objective: Use JOIN in MySQL to fetch the data of those specific customers who have claimed an amount only
under the B2C category and share it with the head of the insurance campaign planning department
Assisted Practice: Joins Two
Duration: 15 mins
Datasets: You’ve been asked to create the following tables to perform the required tasks:
Duration: 15 mins
Steps to be performed:
Step 01: Create the B2C_customers table per the given structure
Step 02: Create the B2B_customers table per the given structure
Step 03: Insert records in the B2C_customers table
Step 04: Insert records in the B2B_customers table
Step 05: Fetch the data of those specific customers who have claimed an amount only under the B2C category
and not under the B2B category
Assisted Practice: Joins Two
Step 01: Create the B2C_customers table per the given structure
Query
Output:
Assisted Practice: Joins Two
Step 02: Create the B2B_customers table per the given structure
Query
Output:
Assisted Practice: Joins Two
Query
INSERT INTO
B2C_customer(CUST_ID,POLICY_NO,CLAIM_DATE,CLAIM_AMT)
VALUES
("C","PO21","2020-03-03",1000),
("C2","PO22","2020-03-04",3200),
("C3","PO33","2020-03-05",5000),
("C4","PO44","2020-03-06",4500),
("C5","PO55","2020-03-07",1200);
Assisted Practice: Joins Two
Output:
Assisted Practice: Joins Two
Query
INSERT INTO
B2B_customer(CUST_ID,POLICY_NO,CLAIM_DATE,CLAIM_AMT)
VALUES
("C","PO21","2020-03-03",1000),
("C2","PO22","2020-03-04",3200),
("C8","PO33","2020-03-05",5000);
Assisted Practice: Joins Two
Output:
Assisted Practice: Joins Two
Step 05: Fetch the data of those specific customers who have claimed an amount only under the B2C
category and not under the B2B category
Query
Output:
Operators in MySQL
SET Operators
DEFINITION FUNCTIONALITY
Set operators are used
Set operators combine
Basic LOOP to get meaningful
the results of two
results from data
component queries
stored in the table
into a single result.
under different special
conditions.
Types of SET Operators
UNION
UNION ALL
SET
OPERATIONS
INTERSECT
MINUS
t1 UNION t2
UNION Operator
UNION
RULES
Syntax
SELECT column_list
UNION [DISTINCT | ALL]
SELECT column_list
UNION [DISTINCT | ALL]
SELECT column_list
...
UNION Operator: Example
Problem Statement: Your manager wants you to provide the full names and departments of
the employees along with the name and domain of projects as name and department from
both the employee and project records tables.
Objective: Write an SQL query using the UNION operator to perform the union of the
EMP_RECORDS and PROJ_RECORDS tables to obtain the required data in MySQL.
UNION Operator: Example
Step 1: Use the UNION operator in the SELECT statement to perform the union of the
EMP_RECORDS and PROJ_RECORDS tables as given below.
SELECT e.EMP_ID,
e.DEPT
FROM EMP_RECORDS e
UNION
FROM PROJ_RECORDS p
t1 UNION t2
ALL
UNION ALL Operator
Syntax
SELECT column_list
UNION ALL [DISTINCT | ALL]
SELECT column_list
UNION ALL [DISTINCT | ALL]
SELECT column_list
...
UNION ALL Operator: Example
Problem Statement: Your manager wants you to provide all the available entries with the
full names of all employees and projects along with their department or domain as their
domain in both the employee and project records tables together.
Objective: Write an SQL query using the UNION ALL operator to perform the union of the
EMP_RECORDS and PROJ_RECORDS tables to obtain the required data while considering
the duplicate rows in MySQL.
UNION ALL Operator: Example
Step 1: Use the UNION ALL operator in the SELECT statement to perform the union of the
EMP_RECORDS and PROJ_RECORDS tables while considering the duplicate rows as given below.
SELECT e.EMP_ID,
e.DEPT
FROM EMP_RECORDS e
UNION
FROM PROJ_RECORDS p
UNION JOIN
● Combines the result set of two or more ● Combines data from various tables based
SELECT statements on a matched condition between them
● Combines data into new rows ● Combines data into new columns
● Number of columns selected from each ● Number of columns selected from each
table must be the same table may not be the same
UNION vs. JOIN
UNION JOIN
t1 INTERSECT t2
INTERSECT Operator
INTERSECT
RULES
Syntax
(SELECT column_list
FROM table_1)
INTERSECT
(SELECT column_list
FROM table_2);
Emulating INTERSECT in MySQL
Syntax
SELECT
DISTINCT column_name_1
FROM table_1
Problem Statement: Your manager wants you to list the employee IDs of all the managers
who are involved with at least one project.
Objective: Write an SQL query using either INNER JOIN clause with the DISTINCT keyword
or IN operator with Subquery to simulate the INTERSECT operator on the EMP_RECORDS
and PROJ_ASSIGN tables in MySQL.
INTERSECT Using DISTINCT and INNER JOIN: Example
Step 1: Use the INNER JOIN clause with DISTINCT keyword in the SELECT statement to simulate
the INTERSECT operator on the EMP_RECORDS and PROJ_ASSIGN tables as given below.
SQL Query
FROM EMP_RECORDS e
ORDER BY e.EMP_ID;
Output:
INTERSECT Using IN and Subquery
Syntax
SELECT
DISTINCT column_name_1,
FROM
table_1
WHERE column_name_1 IN (
SELECT column_name_1
FROM table_2
);
INTERSECT Using IN and Subquery: Example
Step 2: Use the IN operator with Subquery in the SELECT statement to simulate the INTERSECT
operator on the EMP_RECORDS and PROJ_ASSIGN tables as given below.
SQL Query
FROM EMP_RECORDS e
WHERE e.EMP_ID IN (
SELECT a.EMP_ID
FROM PROJ_ASSIGN a
ORDER BY e.EMP_ID;
Output:
MINUS Operator
The MINUS operator compares the results of two queries. It returns distinct rows from
the result set of the first query that does not appear in the result set of the second
query.
Syntax
SELECT select_list1
FROM table_name1
MINUS
SELECT select_list2
FROM table_name2;
MINUS Operator
MINUS
RULES
Syntax
SELECT
select_list
FROM
table1
LEFT JOIN table2
ON join_predicate
WHERE
table2.column_name IS NULL;
MINUS Using LEFT JOIN
Syntax
SELECT
column_name_1
FROM
table_1
LEFT JOIN
WHERE
table_2.column_name_1 IS NULL;
MINUS Using LEFT JOIN: Example
Problem Statement: Your manager wants you to list the project IDs of the projects that are
not yet assigned to any manager or employee.
Objective: Write an SQL query using LEFT JOIN clause to simulate the MINUS operator on
the PROJ_RECORDS and PROJ_ASSIGN tables in MySQL.
MINUS Using LEFT JOIN: Example
Step 1: Use the LEFT JOIN clause in the SELECT statement to simulate the MINUS operator on
the PROJ_RECORDS and PROJ_ASSIGN tables as given below.
SQL Query
SELECT
p.PROJ_ID
FROM
PROJ_RECORDS p
LEFT JOIN
WHERE
a.PROJ_ID IS NULL;
Output:
Assisted Practice: Union
Duration: 15 mins
Problem statement: You have joined as an analyst in the talent acquisition team of Sun Tech. The team collects
the data for new hires in a separate table for every month, such as the data hires for January 2025 goes into the
NH_JAN_2025 table and the data for hires for February 2025 goes to NH_FEB_2025. You have been asked to
bring the data for January and February into a single table.
NH_JAN_2025 NH_FEB_2025
EMP_ID EMP_NAME DEPT EMP_ID EMP_NAME DEPT
Steps to be performed:
Step 01: Write a query to create two tables (NH_JAN_2025 and NH_FEB_2025) as shown in the
problem statement and fill the data shown in those tables in SQL
CREATE
CREATE TABLE NH_JAN_2025(EMP_ID int, EMP_NAME text, DEPT text);
Output:
Assisted Practice: Union
SQL Query
Output:
Assisted Practice: Union
Step 03: Write a query to show the two tables (NH_JAN_2025 and NH_FEB_2025)
SQL Query
Output:
Assisted Practice: Union
Step 04: Write a query to club the data of both tables into a single table along with the MONTH column
Hint: The MONTH column can be created by passing a string as a column name. This column should have
the month and year values in the data.
SQL Query
Output:
Subquery in SQL
Subquery in SQL
It is also called an Inner Query or Inner Select while the statement that
contains the subquery is called an outer query or outer select.
SQL
Subquery
It can be used anywhere an expression is used and must be closed in
parentheses.
Example
SELECT branchCode
FROM dataCenters Inner query
WHERE country = 'USA’
);
Subquery Rules
Comparison As
operators expressions
08 01 IN or NOT
ANY or ALL
IN
operators
07 02 operators
SUBQUERY
USAGE
UPDATE, RULES
06 03 EXISTS or
DELETE,
or insert NOT EXISTS
statement 05 04 operators
FROM WHERE
clause clause
Subqueries with Statements and Operators
Subquery as Expressions
SQL Query
FROM EMP_RECORDS m
Suppose you need to determine the count of managers and the total
team strength excluding them in the retail domain in MySQL.
Subquery With WHERE Clause
SQL Query
FROM PROJ_RECORDS p
Output:
WHERE p.PROJ_ID NOT IN (
FROM PROJ_ASSIGN a
SQL Query
SELECT
e.EMP_ID,
Output:
CONCAT(e.FIRST_NAME,' ',e.LAST_NAME) AS `FULL_NAME`,
e.ROLE, e.DEPT
FROM EMP_RECORDS e
SQL Query
SELECT
Suppose you need to determine the list of all managers who have not
been assigned to any projects in the organization in MySQL.
Subquery With ANY Operator
A subquery that returns a list of values that can be used with ANY
operator in the WHERE clause.
The ANY operator compares each value provided by the subquery with
the comparison expression and returns TRUE if any comparison pair
evaluates to TRUE; otherwise, it returns FALSE.
Subquery With ANY Operator
Suppose you need to determine any five employees with more than or equal to
the average experience of all employees in the organization in MySQL.
SQL Query
SELECT
Output:
e.EMP_ID,
FROM EMP_RECORDS e
LIMIT 5;
Subquery With ALL Operator
A subquery that returns a list of values can also be used with ALL
operators in the WHERE clause.
The ALL operator compares each value provided by the subquery with the
comparison expression and returns TRUE if all the comparison pairs
evaluate to TRUE; otherwise, it returns FALSE.
Subquery With ALL Operator
Suppose you need to determine all the employees with less than the
average experience of all employees in MySQL.
e.EMP_ID,
FROM EMP_RECORDS e
A subquery can also be used with the EXISTS and NOT EXISTS operators.
The EXISTS operator returns TRUE if the subquery returns the results;
otherwise, it returns FALSE. The NOT EXISTS operator is opposite to the
EXISTS operator.
Subquery With EXISTS or NOT EXISTS Operators
Suppose you need to print the names of all the projects only if even one
project is assigned to any employee in MySQL.
FROM PROJ_RECORDS
WHERE EXISTS (
SELECT PROJ_ID
FROM PROJ_ASSIGN
) ORDER BY PROJ_ID;
Subquery in the FROM Clause
The FROM clause creates a temporary table from the result set returned by
a subquery, often known as a derived table or materialized subquery.
SQL Query
SELECT
FROM (
) AS TOTAL_EXP;
SQL Query
SELECT
FROM PROJ_RECORDS
WHERE PROJ_ID IN (
Suppose you need to determine all those projects that are assigned to
at least one of the employees in MySQL.
Subquery With INSERT Statement
SQL Query
STATUS VARCHAR(7),
) ENGINE=INNODB;
Subquery With INSERT Statement
Let us now analyze the structure of the PROJ_RECORDS_BKUP table created in MySQL.
Output:
SQL Query
DESCRIBE PROJ_DB.PROJ_RECORDS_BKUP;
Subquery With INSERT Statement
Suppose you need to back up the data of all those projects which have no
employee assigned into the new PROJ_RECORDS_BKUP table in MySQL.
SQL Query
);
Subquery With INSERT Statement
Now, you need to fetch the data for all the columns from the
PROJ_RECORDS_BKUP table in MySQL to verify the table data.
SQL Query
Output:
Subquery With UPDATE Statement
SQL Query
UPDATE PROJ_RECORDS_BKUP
WHERE START_DATE = (
) AND CLOSURE_DATE = (
);
Suppose you need to change the development quarter along with its
start and closure dates for one of the projects in the
PROJ_RECORDS_BKUP table in MySQL.
Subquery With UPDATE Statement
Now, you need to check the updated data in all the columns of the
PROJ_RECORDS_BKUP table in MySQL to verify the update.
SQL Query
Output:
Subquery With DELETE Statement
SQL Query
WHERE PROJ_ID IN (
);
Now, you need to check the updated data for all the columns in the
PROJ_RECORDS_BKUP table in MySQL to verify the update.
SQL Query
Output:
Assisted Practice: Subquery
Duration: 15 mins
Problem statement: You’re an airport operations specialist, and you have access to the data tables with the
flight details of the different airport hubs of your company. You’ve been asked to analyze only those flights
where the origin or destination point is in SFO airport.
Objective: Write a query to retrieve all passenger information for the flight numbers operating to or from SFO
airport
Assisted Practice: Subquery
Duration: 15 mins
Datasets: You’ve been asked to create the following tables to perform the required tasks:
Duration: 15 mins
Steps to be performed:
Step 01: Create the Passenger table per the given structure
Step 02: Create the Flight table per the given structure
Step 03: Insert records in the Passenger table
Step 04: Insert records in the Flight table
Step 05: Retrieve the data of the passengers who have traveled on planes departing from or arriving to SFO
airport
Assisted Practice: Subquery
Step 01: Create the Passenger table per the given structure
Query
Output:
Assisted Practice: Subquery
Step 02: Create the Flight table per the given structure
Query
CREATE TABLE Flight(
FLT_NO text,
FLT_ORG text,
FLT_DEST text
);
Assisted Practice: Subquery
Output:
Assisted Practice: Subquery
Query
Output:
Assisted Practice: Subquery
Query
Output:
Assisted Practice: Subquery
Step 05: Retrieve the data of the passengers who have traveled on planes departing from or
arriving to SFO airport
Query
SELECT *
FROM Passenger
WHERE FLT_NO IN (
SELECT FLT_NO
FROM Flight
WHERE FLT_ORG="SFO" OR FLT_DEST="SFO"
);
Assisted Practice: Subquery
Output:
Derived Tables in SQL
Derived Tables
Example
SELECT select_list
FROM (
Error
It is mandatory for a derived table to have an alias so that it can be referenced in the
query.
Derived Tables: Example
Problem Statement: Your manager wants you to find the total number of managers in the
organization.
Objective: Write an SQL query using the COUNT function with the DISTINCT keyword on
the output returned by a subquery which creates a DERIVED TABLE to return the EMP_ID
of all managers from the EMP_RECORDS tables in MySQL.
Derived Tables: Example
Step 1: Use the COUNT function with the DISTINCT keyword on the output returned by a
subquery which creates a DERIVED TABLE for returning the EMP_ID of all managers as given
below.
FROM (
) employees
Output:
EXISTS Operator
EXISTS Operator
Syntax
SELECT
select_list
FROM
a_table
WHERE
[NOT] EXISTS(subquery);
EXISTS Operator: Example
Problem Statement: Your manager wants you to provide the basic information of all the
managers in the organization.
Objective: Write an SQL query using the EXISTS operator to verify the existence of
managers and return their details if available from the EMP_RECORDS tables in MySQL.
EXISTS Operator: Example
Step 1: Use the EXISTS operator in the SELECT statement to verify the existence of managers
and return their details if available from the EMP_RECORDS tables as given below.
m.ROLE, m.DEPT
FROM EMP_RECORDS m
WHERE EXISTS(
Syntax
SELECT
select_list
FROM
a_table
WHERE
NOT EXISTS(subquery);
NOT EXISTS Operator: Example
Problem Statement: Your manager wants you to provide the basic information of all the
employees with one year or less than one year of experience in the organization.
Objective: Write an SQL query that verifies if there is no entry for a negative experience in
the EMP_RECORDS tables using the NOT EXISTS operator, and then returns the basic
information for all employees in that table with an experience of less than or equal to one
in MySQL.
NOT EXISTS Operator: Example
Step 1: Use the NOT EXISTS operator in the SELECT statement to verify if there is no negative
entry experience.
Step 2: Return the basic information of all the employees with an experience of less than or
equals to one in the EMP_RECORDS table as given below.
SQL Query
m.DEPT, m.EXP
FROM EMP_RECORDS m
Output:
EXISTS vs. IN Operators
EXISTS vs. IN
● Stops scanning the table as soon as a ● Waits for MySQL to complete the execution
matching row is found of the subquery to utilize its result
Knowledge Check
Knowledge
Check
The JOIN where all possible row combinations are produced is called _________.
1
A. INNER JOIN
B. OUTER
C. NATURAL
D. CARTESIAN
Knowledge
Check
The JOIN where all possible row combinations are produced is called _________.
1
A. INNER JOIN
B. OUTER
C. NATURAL
D. CARTESIAN
A. SELF JOIN
B. COMPLETE
C. OBSOLETE
D. CROSS
Knowledge
Check
What is joining a table to itself called?
2
A. SELF JOIN
B. COMPLETE
C. OBSOLETE
D. CROSS
The term "self join" refers to the joining of a tables to itself in a database. A table name qualifier is not required
when doing a self-join because the table is utilized several times within the query.
Key Takeaways
MySQL supports four different types of joins: INNER, LEFT, RIGHT, and
CROSS.
A. RIGHT JOIN
B. LEFT JOIN
C. INNER JOIN
D. OUTER JOIN
Knowledge
Check In which JOIN all the rows from the left table appear in the output irrespective of the
content of the other table?
3
A. RIGHT JOIN
B. LEFT JOIN
C. INNER JOIN
D. OUTER JOIN
A ‘LEFT JOIN' produces output for every row in the left table, even if that row does not exist in the right table. This
is why it's referred to as a 'LEFT JOIN.' The ‘LEFT JOIN' is a type of OUTER JOIN.
Knowledge
Check Which clause is used to sort a UNION result as a whole?
4
A. LIMIT
B. GROUP BY
C. ORDER BY
D. SORT
Knowledge
Check Which clause is used to sort a UNION result as a whole?
4
A. LIMIT
B. GROUP BY
C. ORDER BY
D. SORT
To sort a ‘UNION' result as a whole, the ‘ORDER BY' clause is used with the ‘UNION' statement. It is placed after the
final SELECT statement which is enclosed in the parentheses.
Lesson-End Project: Employee Data Analysis
Problem statement:
You are a part of the HR department in a company, and you have been asked
to extract, update, and delete the employees’ details to maintain the records
for further analysis.
Objective:
The objective is to design a database to analyze the performance of the
employees on a quarterly basis.
Tasks to be performed:
1. Write a query to create an employee table with employee ID, first name,
last name, job ID, salary, manager ID, and department ID fields
2. Write a query to insert values into the employee table
3. Write a query to find the first and last names of every employee whose
salary is higher than the employee with the last name Kumar
4. Write a query to display the employee ID and last name of every employee
whose salary is greater than the average
Lesson-End Project: Employee Data Analysis
Tasks to be performed:
Note: Download the solution document from the Course Resources section
and follow the steps given in the document