0% found this document useful (0 votes)
0 views

Dbms Mid-2 Unit-3 Longs Answers

The document provides an overview of relational set operators in databases, including Union, Intersection, Difference, and Cartesian Product, along with their syntax and examples. It also discusses the differences between LEFT JOIN and RIGHT JOIN, explaining how they handle unmatched rows in SQL queries. Additionally, the document outlines various types of views in SQL, such as Simple, Complex, Materialized, Updatable, and Read-Only views, along with examples of how to create tables with relationships using primary and foreign keys.

Uploaded by

PAVANKUMAR KOTNI
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Dbms Mid-2 Unit-3 Longs Answers

The document provides an overview of relational set operators in databases, including Union, Intersection, Difference, and Cartesian Product, along with their syntax and examples. It also discusses the differences between LEFT JOIN and RIGHT JOIN, explaining how they handle unmatched rows in SQL queries. Additionally, the document outlines various types of views in SQL, such as Simple, Complex, Materialized, Updatable, and Read-Only views, along with examples of how to create tables with relationships using primary and foreign keys.

Uploaded by

PAVANKUMAR KOTNI
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 37

DBMS UNIT-3 part-b LONGS

1. List all Relational Set operators with it’s description and


Syntax.
1A) Relational set operators are used in relational
databases to perform operations on tables (relations).
These operations allow you to manipulate and query data
across multiple tables. The primary relational set operators
are:
1. Union
2. Intersection
3. Difference (Minus)
4. Cartesian Product
Here’s a description of each operator along with its syntax:

1. Union ( ∪ )
The Union operator combines the results of two queries
into a single result set. It returns all the rows from both
relations, removing duplicates.
Description:
 Combines tuples from two relations, excluding
duplicates.
 Both relations must have the same number of attributes
and corresponding attribute domains (data types).
Syntax:
SELECT column1, column2, ... FROM table1
UNION
SELECT column1, column2, ... FROM table2;
Example:
SELECT EmployeeID FROM Employees1
UNION
SELECT EmployeeID FROM Employees2;
 This query will return all distinct EmployeeIDs from both
Employees1 and Employees2.

2. Intersection ( ∩ )
The Intersection operator returns only the rows that are
common to both relations.
Description:
 Returns the common tuples between two relations.
 Both relations must have the same number of attributes
and corresponding attribute domains.
Syntax:
SELECT column1, column2, ... FROM table1
INTERSECT
SELECT column1, column2, ... FROM table2;
Example:
SELECT EmployeeID FROM Employees1
INTERSECT
SELECT EmployeeID FROM Employees2;
 This query will return only the EmployeeIDs that exist in
both Employees1 and Employees2.

3. Difference ( − or MINUS )
The Difference operator (also called Minus in some SQL
implementations) returns the rows that are in the first
relation but not in the second.
Description:
 Returns tuples that are in the first relation but not in the
second.
 Both relations must have the same number of attributes
and corresponding attribute domains.
Syntax:
SELECT column1, column2, ... FROM table1
MINUS
SELECT column1, column2, ... FROM table2;
Example:
SELECT EmployeeID FROM Employees1
MINUS
SELECT EmployeeID FROM Employees2;
 This query will return EmployeeIDs that are in
Employees1 but not in Employees2.
4. Cartesian Product ( × )
The Cartesian Product operator returns the combined
rows of two relations. Each row from the first relation is
paired with each row from the second relation, producing
a new relation with all possible combinations.
Description:
 It combines every tuple of the first relation with every
tuple of the second relation.
 The result will have the number of columns equal to the
sum of columns of both relations.
Syntax:
SELECT * FROM table1
CROSS JOIN table2;
Example:

SELECT * FROM Employees


CROSS JOIN Departments;
 This query will return every possible combination of an
Employee and a Department.

Summary of Relational Set Operators


Operator Description Syntax
Union ( ∪ ) Combines tuples SELECT ... FROM
Operator Description Syntax
table1 UNION
from two relations,
SELECT ... FROM
removing duplicates.
table2;
SELECT ... FROM
Returns tuples that
Intersection ( table1 INTERSECT
are present in both
∩) SELECT ... FROM
relations.
table2;
Returns tuples SELECT ... FROM
Difference ( − present in the first table1 MINUS
) relation but not the SELECT ... FROM
second. table2;
Combines each tuple
SELECT * FROM
Cartesian from the first relation
table1 CROSS
Product ( × ) with each tuple from
JOIN table2;
the second.

2. Discuss the difference between a LEFT JOIN and a RIGHT


JOIN? Explain with an example
2A) Both LEFT JOIN and RIGHT JOIN are types of outer
joins in SQL. They allow you to combine records from two
tables based on a related column. However, the difference
lies in how they handle the unmatched rows in the tables.
Here's a detailed comparison:

1. LEFT JOIN (or LEFT OUTER JOIN)


The LEFT JOIN returns all the rows from the left table (the
first table in the query) and the matching rows from the
right table (the second table in the query). If there is no
match, NULL values are returned for columns from the
right table.
Key Points:
 All rows from the left table are included in the result.
 Matching rows from the right table are included.
 If no matching rows are found in the right table, NULL
values are displayed for the columns from the right
table.
Syntax:
SELECT columns
FROM table1
LEFT JOIN table2
ON table1.column = table2.column;
Example of LEFT JOIN:
Consider two tables:
1. Employees Table: | EmpID | EmpName |
|-------|------------| | 1 | John | | 2 | Alice | | 3 | Bob |
2. Departments Table: | DeptID | EmpID | DeptName |
|--------|-------|------------| | 10 | 1 | HR | | 20 | 3 |
Finance |
SQL Query:
SELECT Employees.EmpName, Departments.DeptName
FROM Employees
LEFT JOIN Departments ON Employees.EmpID =
Departments.EmpID;
Result:
EmpName DeptName
John HR
Alice NULL
Bob Finance
 Explanation:
o John is in the HR department.
o Alice has no matching record in the Departments
table, so NULL is returned for DeptName.
o Bob is in the Finance department.

2. RIGHT JOIN (or RIGHT OUTER JOIN)


The RIGHT JOIN returns all the rows from the right table
(the second table in the query) and the matching rows
from the left table (the first table in the query). If there is
no match, NULL values are returned for columns from the
left table.
Key Points:
 All rows from the right table are included in the result.
 Matching rows from the left table are included.
 If no matching rows are found in the left table, NULL
values are displayed for the columns from the left table.
Syntax:
SELECT columns
FROM table1
RIGHT JOIN table2
ON table1.column = table2.column;
Example of RIGHT JOIN:
Consider the same two tables:
1. Employees Table: | EmpID | EmpName |
|-------|------------| | 1 | John | | 2 | Alice | | 3 | Bob |
2. Departments Table: | DeptID | EmpID | DeptName |
|--------|-------|------------| | 10 | 1 | HR | | 20 | 3 |
Finance | | 30 | 4 | Marketing |
SQL Query:
SELECT Employees.EmpName, Departments.DeptName
FROM Employees
RIGHT JOIN Departments ON Employees.EmpID =
Departments.EmpID;
Result:
EmpName DeptName
John HR
EmpName DeptName
Bob Finance
NULL Marketing
 Explanation:
o John is in the HR department.
o Bob is in the Finance department.
o The Marketing department does not have a
matching EmpID in the Employees table, so NULL is
returned for EmpName.

Key Differences Between LEFT JOIN and RIGHT JOIN:


Aspect LEFT JOIN RIGHT JOIN
All rows from the
All rows from the
left table and
right table and
matching rows
matching rows
Result Rows from the right
from the left table.
table. If no match,
If no match, NULL
NULL from the
from the left table.
right table.
Which table's
Left table (first Right table (second
rows are
table). table).
guaranteed?
Handling of If no match in right If no match in left
unmatched table, returns table, returns
rows NULL for right NULL for left table
Aspect LEFT JOIN RIGHT JOIN
table columns. columns.
Useful when you Useful when you
want to keep all want to keep all
records from the records from the
Use Case left table right table
regardless of regardless of
matching in the matching in the
right table. left table.

3. Explain different types of views with an example.


3A) In SQL, a view is a virtual table that provides a way to
present data from one or more tables in a simplified or
customized manner. Views do not store data themselves
but display data dynamically based on a query defined at
the time of their creation. There are several types of views,
which differ in their usage, data presentation, and
restrictions.
Here are the different types of views in SQL:

1. Simple View
A simple view is a view that is based on a single table and
does not include any complex operations such as joins,
subqueries, or groupings. It provides a straightforward
representation of data from a single table.
Key Points:
 It is based on one table.
 Typically used for security purposes, to expose only
specific columns or rows of a table.
 It allows users to access a subset of data in a user-
friendly format.
Example of Simple View:
Suppose we have a table Employees:
EmpID EmpName Age Department
1 John 30 HR
2 Alice 25 IT
3 Bob 35 Finance
SQL Query to create a simple view:
CREATE VIEW EmployeeNames AS
SELECT EmpID, EmpName
FROM Employees;
Using the View:
SELECT * FROM EmployeeNames;
Result:
EmpID EmpName
1 John
2 Alice
3 Bob
This view simply exposes the EmpID and EmpName
columns from the Employees table.

2. Complex View
A complex view is a view that is created from multiple
tables and can include features such as joins, subqueries,
grouping, or aggregations. These views are used when data
from multiple tables needs to be combined or
transformed.
Key Points:
 It can be based on more than one table.
 May include operations like JOIN, GROUP BY, or ORDER
BY.
 Can include subqueries, which allow for complex
filtering and calculations.
Example of Complex View:
Consider two tables: Employees and Departments.
Employees Table:
EmpID EmpName DeptID
1 John 10
2 Alice 20
3 Bob 10
Departments Table:
DeptID DeptName
10 HR
20 IT
SQL Query to create a complex view:
CREATE VIEW EmployeeDetails AS
SELECT E.EmpID, E.EmpName, D.DeptName
FROM Employees E
JOIN Departments D ON E.DeptID = D.DeptID;
Using the View:
SELECT * FROM EmployeeDetails;
Result:
EmpID EmpName DeptName
1 John HR
2 Alice IT
3 Bob HR
This view combines data from two tables: Employees and
Departments, showing which department each employee
belongs to.

3. Materialized View
A materialized view is a view that physically stores the
result of a query, unlike other views that are virtual and
dynamically calculated every time they are accessed.
Materialized views can be refreshed periodically to ensure
that they reflect the latest data from the underlying tables.
Key Points:
 Stores the query result physically, improving
performance for complex queries.
 Can be refreshed at regular intervals to update the data.
 Useful for reporting purposes and data warehousing,
where real-time data is not critical.
Example of Materialized View:
If we wanted to create a materialized view based on the
Employees and Departments tables, the syntax would
depend on the database system. In Oracle, for instance:
CREATE MATERIALIZED VIEW EmployeeDetailsMaterialized
AS
SELECT E.EmpID, E.EmpName, D.DeptName
FROM Employees E
JOIN Departments D ON E.DeptID = D.DeptID;
In this case, the result of the query would be stored
physically, allowing for faster access to the employee and
department data. The materialized view can be refreshed
using:
REFRESH MATERIALIZED VIEW
EmployeeDetailsMaterialized;

4. Updatable View
An updatable view is a view that allows updates (inserts,
updates, or deletes) on the underlying table through the
view itself. However, not all views are updatable, especially
if they are based on complex queries involving joins,
aggregates, or non-key columns.
Key Points:
 It allows users to modify the data in the underlying table
via the view.
 A view is updatable only if it satisfies certain conditions
(e.g., not based on joins or aggregations).
Example of an Updatable View:
Consider the Employees table:
EmpID EmpName Age Department
1 John 30 HR
2 Alice 25 IT
You could create an updatable view like this:
CREATE VIEW EmployeeUpdate AS
SELECT EmpID, EmpName, Age
FROM Employees;
You can then update the employee's age through the view:
UPDATE EmployeeUpdate
SET Age = 31
WHERE EmpID = 1;
This would update the Age of the employee with EmpID =
1 in the underlying Employees table.

5. Read-Only View
A read-only view is a view that cannot be modified directly
through the view. Any attempt to insert, update, or delete
data through the view will result in an error. This type of
view is typically used for reporting or when the integrity of
the underlying data must be maintained.
Key Points:
 Does not allow modification of the underlying data.
 Often used for providing access to read-only data.
Example of Read-Only View:
CREATE VIEW EmployeeReadOnly AS
SELECT EmpID, EmpName, Age
FROM Employees;
In this case, users can query the view but cannot modify
the data through it.

Summary of Types of Views:


Type of
Description Example
View
Simple A view CREATE VIEW
View based on a EmployeeNames AS SELECT
single table EmpID, EmpName FROM
Type of
Description Example
View
without
complex Employees;
operations.
CREATE VIEW
A view that
EmployeeDetails AS SELECT
combines
E.EmpID, E.EmpName,
Complex multiple
D.DeptName FROM
View tables using
Employees E JOIN
joins or
Departments D ON
subqueries.
E.DeptID = D.DeptID;
A view that CREATE MATERIALIZED
stores the VIEW
result EmployeeDetailsMaterialize
Materialize physically, d AS SELECT E.EmpID,
d View improving E.EmpName, D.DeptName
performance FROM Employees E JOIN
for complex Departments D ON
queries. E.DeptID = D.DeptID;
A view that
allows CREATE VIEW
Updatable modification EmployeeUpdate AS SELECT
View s to the EmpID, EmpName, Age
underlying FROM Employees;
data.
Read-Only A view that CREATE VIEW
Type of
Description Example
View
does not
allow
EmployeeReadOnly AS
modification
View SELECT EmpID, EmpName,
s to the
Age FROM Employees;
underlying
data.

4. Explain how to create tables with relationships between


them.
4A) In relational database design, relationships between
tables represent associations between different entities.
These relationships are crucial to maintaining data integrity
and are typically enforced using foreign keys. The most
common types of relationships between tables are one-to-
many, many-to-one, and many-to-many.
Below, we will discuss how to create tables with
relationships using primary and foreign keys in SQL.

1. One-to-Many Relationship
In a one-to-many relationship, one record in the parent
table can relate to many records in the child table. For
example, in a database with two tables, Department and
Employee, each department can have multiple employees,
but each employee can belong to only one department.
Steps to Create a One-to-Many Relationship:
1. Create the parent table (Department) with a Primary
Key.
2. Create the child table (Employee) and add a Foreign Key
referencing the primary key of the parent table.
Example:
Consider a Department table and an Employee table where
each department has multiple employees.
Step 1: Create the Department table:
CREATE TABLE Department (
DeptID INT PRIMARY KEY,
DeptName VARCHAR(100)
);
 DeptID is the Primary Key of the Department table.
Step 2: Create the Employee table:
CREATE TABLE Employee (
EmpID INT PRIMARY KEY,
EmpName VARCHAR(100),
Age INT,
DeptID INT,
FOREIGN KEY (DeptID) REFERENCES Department(DeptID)
);
 DeptID in the Employee table is the Foreign Key that
references DeptID in the Department table.
Explanation:
 The Department table represents the "parent" table
with the primary key DeptID.
 The Employee table represents the "child" table with a
foreign key DeptID that creates a relationship with the
Department table.
 The foreign key ensures that each employee belongs to a
valid department.

2. Many-to-One Relationship
A many-to-one relationship is essentially the reverse of a
one-to-many relationship. Many records in the child table
can reference the same record in the parent table.
In SQL, the many-to-one relationship is typically
represented using the same structure as the one-to-many
relationship. In the above example, many employees can
belong to the same department, but each employee is
assigned to one department.

3. Many-to-Many Relationship
In a many-to-many relationship, multiple records in one
table can be associated with multiple records in another
table. For example, in a database that tracks Students and
Courses, each student can enroll in multiple courses, and
each course can have multiple students.
To create a many-to-many relationship, we need to create
a junction table (also called a bridge table or association
table) that contains foreign keys referencing the primary
keys of the two tables involved in the relationship.
Steps to Create a Many-to-Many Relationship:
1. Create the two main tables (Student and Course) with
Primary Keys.
2. Create a junction table (StudentCourse) that contains
foreign keys referencing both the Student and Course
tables.
Example:
Step 1: Create the Student table:
CREATE TABLE Student (
StudentID INT PRIMARY KEY,
StudentName VARCHAR(100)
);
 StudentID is the Primary Key of the Student table.
Step 2: Create the Course table:
CREATE TABLE Course (
CourseID INT PRIMARY KEY,
CourseName VARCHAR(100)
);
 CourseID is the Primary Key of the Course table.
Step 3: Create the StudentCourse junction table:
CREATE TABLE StudentCourse (
StudentID INT,
CourseID INT,
PRIMARY KEY (StudentID, CourseID),
FOREIGN KEY (StudentID) REFERENCES
Student(StudentID),
FOREIGN KEY (CourseID) REFERENCES Course(CourseID)
);
 The junction table StudentCourse includes the foreign
keys StudentID and CourseID.
 The Primary Key of the StudentCourse table is a
composite key made up of both StudentID and CourseID
to ensure that each student-course pair is unique.
Explanation:
 A many-to-many relationship is created through the
StudentCourse table, which connects students to the
courses they are enrolled in.
 Each student can have multiple entries in the
StudentCourse table (enrolled in many courses), and
each course can have multiple students.

4. One-to-One Relationship
In a one-to-one relationship, each record in one table
corresponds to one record in another table. This type of
relationship is less common but useful in scenarios like
dividing a large table for performance reasons or splitting
confidential data.
Steps to Create a One-to-One Relationship:
1. Create two tables where each table has a primary key.
2. Ensure that the foreign key in one table references the
primary key of the other table, and that it is unique.
Example:
Consider a Person table and a Passport table, where each
person has only one passport, and each passport is
assigned to only one person.
Step 1: Create the Person table:
CREATE TABLE Person (
PersonID INT PRIMARY KEY,
Name VARCHAR(100),
Age INT
);
 PersonID is the Primary Key of the Person table.
Step 2: Create the Passport table:
CREATE TABLE Passport (
PassportID INT PRIMARY KEY,
PersonID INT UNIQUE,
IssueDate DATE,
ExpiryDate DATE,
FOREIGN KEY (PersonID) REFERENCES Person(PersonID)
);
 PersonID in the Passport table is a Foreign Key
referencing the PersonID of the Person table.
 The PersonID in the Passport table is also marked as
UNIQUE to ensure that each person can have only one
passport.
Explanation:
 A one-to-one relationship exists between Person and
Passport, where each person can have one and only one
passport, and each passport is linked to one person.

Summary of Creating Tables with Relationships


Relationship
Explanation SQL Example
Type
One record in
CREATE TABLE Employee
the parent
(EmpID INT PRIMARY KEY,
One-to- table relates
DeptID INT, FOREIGN KEY
Many to many
(DeptID) REFERENCES
records in the
Department(DeptID));
child table.
Many-to- Many records Same as one-to-many
One in the child relationship (reversed).
Relationship
Explanation SQL Example
Type
table can
relate to one
record in the
parent table.
CREATE TABLE
Multiple StudentCourse (StudentID
records in one INT, CourseID INT,
table can be FOREIGN KEY (StudentID)
Many-to-
related to REFERENCES
Many
multiple Student(StudentID),
records in FOREIGN KEY (CourseID)
another table. REFERENCES
Course(CourseID));
One record in CREATE TABLE Passport
each table (PassportID INT PRIMARY
corresponds KEY, PersonID INT
One-to-One
to one record UNIQUE, FOREIGN KEY
in the other (PersonID) REFERENCES
table. Person(PersonID));

5. Write a short note on Aggregate functions of SQL.


5A) Aggregate functions in SQL are used to perform
calculations on a set of values and return a single value as a
result. They are commonly used in GROUP BY clauses to
group rows based on certain criteria and then perform a
calculation on each group.
The most commonly used aggregate functions in SQL are:

1. COUNT()
 Purpose: Returns the number of rows in a result set.
 Syntax:
SELECT COUNT(column_name) FROM table_name;
 Example:
SELECT COUNT(*) FROM Employees;
This returns the total number of employees in the
Employees table.

2. SUM()
 Purpose: Returns the sum of values in a numeric
column.
 Syntax:
SELECT SUM(column_name) FROM table_name;
 Example:
SELECT SUM(Salary) FROM Employees;
This returns the total sum of the salaries of all employees.

3. AVG()
 Purpose: Returns the average value of a numeric
column.
 Syntax:
SELECT AVG(column_name) FROM table_name;
 Example:
SELECT AVG(Salary) FROM Employees;
This returns the average salary of all employees.

4. MAX()
 Purpose: Returns the maximum value from a set of
values in a column.
 Syntax:
SELECT MAX(column_name) FROM table_name;
 Example:
SELECT MAX(Salary) FROM Employees;
This returns the highest salary among all employees.

5. MIN()
 Purpose: Returns the minimum value from a set of
values in a column.
 Syntax
SELECT MIN(column_name) FROM table_name;
 Example:
SELECT MIN(Salary) FROM Employees;
This returns the lowest salary among all employees.

6. GROUP_CONCAT() (MySQL-specific)
 Purpose: Concatenates values from multiple rows into a
single string.
 Syntax:
SELECT GROUP_CONCAT(column_name) FROM
table_name;
 Example:
SELECT GROUP_CONCAT(DeptName) FROM Departments;
This returns a comma-separated list of all department
names in the Departments table.

Usage with GROUP BY


Aggregate functions are often used in combination with
the GROUP BY clause to calculate aggregates for each
group of rows.
Example:
SELECT DeptID, AVG(Salary) FROM Employees GROUP BY
DeptID;
This query calculates the average salary for each
department.
NULL Handling in Aggregate Functions
 Most aggregate functions ignore NULL values when
calculating results, except for the COUNT() function,
which can count NULL values if specified.
Example:

SELECT COUNT(*) FROM Employees WHERE Salary IS NOT


NULL;
This counts all employees who have a non-null salary.

6. Discuss full outer join with an appropriate example


6A) A Full Outer Join combines the results of both Left Join
and Right Join. It returns all rows from both the left and
right tables. If there is no match, the missing side will
contain NULL.

How Full Outer Join Works:


 The result will include:
o Rows from the left table that do not have matching
rows in the right table (with NULL in columns from
the right table).
o Rows from the right table that do not have
matching rows in the left table (with NULL in
columns from the left table).
o Rows where there is a match between both tables.
If a row in the left table has a matching row in the right
table, the result will contain that row. If a row does not
have a match, NULL values are included for the columns of
the table that does not have the match.

Syntax for Full Outer Join:


SELECT columns
FROM table1
FULL OUTER JOIN table2
ON table1.column = table2.column;
 table1 and table2: The two tables to join.
 column: The column on which the tables will be joined
(the key or condition for matching).

Example of Full Outer Join:


Consider two tables:
Employees Table:
EmpID Name DeptID
1 Alice 101
2 Bob 102
3 Charlie 103
4 David 104
Departments Table:
DeptID DeptName
101 HR
102 IT
105 Finance
Now, let's say we want to combine these tables using a Full
Outer Join on DeptID.
Query:
SELECT Employees.EmpID, Employees.Name,
Departments.DeptName
FROM Employees
FULL OUTER JOIN Departments
ON Employees.DeptID = Departments.DeptID;
Result:
EmpID Name DeptName
1 Alice HR
2 Bob IT
3 Charlie NULL
4 David NULL
NULL NULL Finance

Explanation of the Result:


 First Two Rows (Alice and Bob): These employees have
matching DeptIDs with departments (HR and IT), so their
data is combined.
 Rows for Charlie and David: These employees do not
have corresponding departments (no match on DeptID),
so NULL values are filled in for the DeptName.
 Last Row (Finance): This department has no employees,
so the EmpID and Name columns contain NULL.

Use Cases for Full Outer Join:


1. Missing Data: It is useful when you want to find records
that do not have a match in another table, like finding
employees who don't belong to any department or
departments that don't have any employees.
2. Comprehensive Data Representation: It helps in
reporting and analysis when it's important to show all
data from both tables, even when there are unmatched
rows.

7. Explain about sub queries with an example.


7A) A subquery (also known as an inner query or nested
query) is a query that is embedded within another query.
Subqueries are used to perform operations that require
multiple steps or calculations in a single SQL statement.
The result of a subquery can be used in various places
within the main query, such as in the WHERE, FROM, or
SELECT clauses.
Subqueries can return a single value, multiple values, or
even a set of results. There are two main types of
subqueries:
1. Single-Row Subqueries: Returns a single value (one row,
one column).
2. Multiple-Row Subqueries: Returns multiple rows or
columns.

Types of Subqueries:
1. Subquery in WHERE Clause: A subquery can be used in
the WHERE clause to filter the results based on a
condition.
2. Subquery in SELECT Clause: A subquery can be used in
the SELECT clause to compute a derived column.
3. Subquery in FROM Clause: A subquery can be used in
the FROM clause to create a temporary table for further
processing.

Syntax of a Subquery:
SELECT column_name(s)
FROM table_name
WHERE column_name OPERATOR (SELECT column_name
FROM table_name WHERE condition);
Here:
 OPERATOR: Could be =, IN, BETWEEN, EXISTS, etc.
 Subquery: The nested query inside parentheses.

Examples of Subqueries:
1. Subquery in WHERE Clause:
Let's consider a database with the following two tables:
Employees Table:
EmpID Name DeptID Salary
1 Alice 101 5000
2 Bob 102 6000
3 Charlie 103 4500
4 David 104 7000
5 Eve 102 5500
Departments Table:
DeptID DeptName
101 HR
102 IT
103 Sales
104 Marketing
Now, let's say we want to find the employees whose salary
is greater than the average salary in their department.
Query:
SELECT Name, Salary
FROM Employees
WHERE Salary > (SELECT AVG(Salary) FROM Employees
WHERE DeptID = Employees.DeptID);
Explanation:
 The subquery (SELECT AVG(Salary) FROM Employees
WHERE DeptID = Employees.DeptID) calculates the
average salary for each department.
 The outer query selects employees whose salary is
greater than the average salary of their respective
department.
 This query returns only the employees who meet this
condition.

2. Subquery in SELECT Clause:


In this example, we want to display the employee's name
along with the highest salary in their department.
Query:
SELECT Name, Salary,
(SELECT MAX(Salary) FROM Employees AS E2 WHERE
E2.DeptID = E1.DeptID) AS MaxSalary
FROM Employees AS E1;
Explanation:
 The subquery (SELECT MAX(Salary) FROM Employees AS
E2 WHERE E2.DeptID = E1.DeptID) retrieves the
maximum salary in the department of each employee.
 The result is returned as a derived column, MaxSalary,
along with the employee's name and salary.

3. Subquery in FROM Clause:


Sometimes a subquery can be used to create a derived
table. For example, suppose we want to find the average
salary for each department and then list departments with
a salary above the average.
Query:
SELECT DeptID, AVG(Salary) AS AvgSalary
FROM (SELECT DeptID, Salary FROM Employees WHERE
Salary > 5000) AS FilteredSalaries
GROUP BY DeptID;
Explanation:
 The subquery (SELECT DeptID, Salary FROM Employees
WHERE Salary > 5000) filters out employees with a
salary greater than 5000.
 The outer query then calculates the average salary for
each department based on this filtered dataset.

Types of Subqueries Based on the Number of Results:


1. Single-Row Subqueries:
o The subquery returns a single value, which is
typically used with comparison operators like =, <,
>, etc.
o Example:
SELECT Name
FROM Employees
WHERE Salary = (SELECT MAX(Salary) FROM Employees);
This returns the name of the employee with the highest
salary.
2. Multiple-Row Subqueries:
o The subquery returns more than one row of values,
which is typically used with operators like IN or
EXISTS.
o Example:
SELECT Name
FROM Employees
WHERE DeptID IN (SELECT DeptID FROM Departments
WHERE DeptName = 'IT');
This returns the names of employees who work in the IT
department.

You might also like