0% found this document useful (0 votes)
29 views28 pages

Basic SQL Relational Algebra Operations

Uploaded by

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

Basic SQL Relational Algebra Operations

Uploaded by

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

unit-III

Basic SQL Relational Algebra Operations


 The basic set of operations for the relational model is known as the relational algebra. These
operations enable a user to specify basic retrieval requests.

 The result of a retrieval is a new relation, which may have been formed from one or more relations.
The algebra operations thus produce new relations, which can be further manipulated using
operations of the same algebra.

 A sequence of relational algebra operations forms a relational algebra expression, whose result
will also be a relation that represents the result of a database query (or retrieval request.
 Basic Relational Algebra Operations
(Unary Relational Operations:)

 SELECT Operation

SELECT operation is used to select a subset of the tuples from a relation that satisfy a selection condition. It
is a filter that keeps only those tuples that satisfy a qualifying condition – those satisfying the condition are
selected while others are discarded.

Example: To select the EMPLOYEE tuples whose department number is four or those
whose salary is greater than $30,000 the following notation is used:
DNO = 4 (EMPLOYEE)
SALARY > 30,000 (EMPLOYEE)

In general, the select operation is denoted

(R)
<selection condition>
where the symbol  (sigma) is used to denote the select operator, and the selection condition is a Boolean
expression specified on the attributes of relation R.

Note :The SELECT operation s is commutative.

 PROJECT Operation
This operation selects certain columns from the table and discards the other columns. The
PROJECT creates a vertical partitioning – one with the needed columns (attributes) containing results of
the operation and other containing the discarded Columns.

Example: To list each employee’s first and last name and salary, the following is used:

LNAME, FNAME,SALARY(EMPLOYEE)

The general form of the project operation is <attribute list>(R) where  where  (pi) is the
symbol used to represent the project operation and <attribute list> is the desired list of attributes from
the attributes of relation R.

The project operation removes any duplicate tuples, so the result of the project operation is a set
of tuples and hence a valid relation.

 Rename Operation

The RENAME operation is used to rename the output of a relation. Sometimes it is simple and
suitable to break a complicated sequence of operations and rename it as a relation with different
names.

 Example-3: Query to rename the table name Project to Pro and its attributes to P, Q, R.

ρ Pro(P, Q, R) (Project)

 Example-1: Query to rename the relation Student as Male Student and the attributes of
Student – RollNo, SName as (Sno, Name).

ρ MaleStudent(Sno, Name) πRollNo, SName (σCondition(Student))

***************************************************************************

Relational Algebra Operations From Set Theory


Set theory Operations from relational algebra

The SQL Set operation is used to combine the two or more SQL SELECT statements.

Types of Set Operation(binary operations)


Union
UnionAll
Intersect
Minus
division
-------------------------------------------------------------
consider the following two tables first and second for various operation on set theory
mysql> select * from first;
+----+---------+
| id | name |
+----+---------+
| 1 | ramu |
| 2 | jack |
| 3 | jill |
| 5 | sridevi |
+----+---------+
4 rows in set (0.00 sec)

mysql> select * from second;


+----+---------+
| id | name |
+----+---------+
| 1 | ramu |
| 3 | jill |
| 5 | sridevi |
| 7 | ganga |
+----+---------+
4 rows in set (0.00 sec)
*************************************************************************************
1. Union
In the union operation, all the number of datatype and columns must be same in both
the tables on which UNION operation is being applied.
Let R and S be two relations.

 R ∪ S is the set of all tuples belonging to either R or S or both.


Then-

 In R ∪ S, duplicates are automatically removed.


 Union operation is both commutative and associative

The union operation eliminates the duplicate rows from its result set.
Syntax
SELECT column_name FROM table1
UNION
SELECT column_name FROM table2;

Union SQL query will be:example

mysql> SELECT * FROM First


-> UNION
-> SELECT * FROM Second;
+----+---------+
| id | name |
+----+---------+
| 1 | ramu |
| 2 | jack |
| 3 | jill |
| 5 | sridevi |
| 7 | ganga |
+----+---------+
5 rows in set (0.00 sec)
-----------------------------------------------------------------------
2. Union All
. Union All operation is equal to the Union operation.It returns the set without
removing duplication and sorting the data. Union operation is both commutative and
associative.

Syntax:
SELECT column_name FROM table1
UNION ALL
SELECT column_name FROM table2;

Example: Using the above First and Second table.


Union All query will be like:

mysql> SELECT * FROM First


-> UNION ALL
-> SELECT * FROM Second;
+----+---------+
| id | name |
+----+---------+
| 1 | ramu |
| 2 | jack |
| 3 | jill |
| 5 | sridevi |
| 1 | ramu |
| 3 | jill |
| 5 | sridevi |
| 7 | ganga |
+----+---------+
8 rows in set (0.00 sec)
----------------------------------------------------------------------
3. Intersect
It is used to combine two SELECT statements. The Intersect operation returns the
common rows from both the SELECT statements.
In the Intersect operation, the number of columns and datatypes must be the same.
It has no duplicates and it arranges the data in ascending order by default.
Let R and S be two relations.
Then-
 R ∩ S is the set of all tuples belonging to both R and S.
 In R ∩ S, duplicates are automatically removed.
 Intersection operation is both commutative and associative.

Note :Since MySQL does not provide support for the INTERSECT operator.
However, we can use the INNER JOIN and IN clause to emulate this operator.

Syntax
SELECT column_name FROM table1
INTERSECT
SELECT column_name FROM table2

sql syntax:
SELECT * FROM first
INTERSECT
SELECT * FROM second;

INTERSECT Operator using INNER JOIN

mysql> SELECT * FROM first inner join second where first.id=second.id;

+----+---------+----+---------+
| id | name | id | name |
+----+---------+----+---------+
| 1 | ramu | 1 | ramu |
| 3 | jill | 3 | jill |
| 5 | sridevi | 5 | sridevi |
+----+---------+----+---------+
3 rows in set (0.00 sec)

INTERSECT Operator using IN and Subquery

mysql> SELECT * FROM first where id in(select id from second);


+----+---------+
| id | name |
+----+---------+
| 1 | ramu |
| 3 | jill |
| 5 | sridevi |
+----+---------+
3 rows in set (0.00 sec)

--------------------------------------------------------------------
4. Minus
It combines the result of two SELECT statements. Minus operator is used to display the
rows which are present in the first query but absent in the second query.
It has no duplicates and data arranged in ascending order by default.
Let R and S be two relations.
Then-
 R – S is the set of all tuples belonging to R and not to S.
 In R – S, duplicates are automatically removed.
 Difference operation is associative but not commutative.

Syntax:
SELECT column_name FROM table1
MINUS
SELECT column_name FROM table2;

Example
Using the above First and Second table.
Minus query in SQL will be:

SELECT * FROM First


MINUS
SELECT * FROM Second;

Note:Simulation of MySQL MINUS Operator


Since MySQL does not provide support for MINUS operator. However, we can use
a LEFT JOIN clause and RIGHT JOIN Clause to simulate this operator.
We can use the following syntax to simulate the MINUS operator:
SELECT column_list FROM table1
LEFT JOIN table2 ON condition
WHERE table2.column_name ;

SELECT column_list FROM table1


RIGHT JOIN table2 ON condition
WHERE table1.column_name ;
mysql> SELECT * FROM First left join second on first.id=second.id;

+----+---------+------+---------+
| id | name | id | name |
+----+---------+------+---------+
| 1 | ramu | 1 | ramu |
| 2 | jack | NULL | NULL |
| 3 | jill | 3 | jill |
| 5 | sridevi | 5 | sridevi |
+----+---------+------+---------+----
4 rows in set (0.00 sec)

mysql> SELECT * FROM First right join second on first.id=second.id;


+------+---------+----+---------+-----
| id | name | id | name |
+------+---------+----+---------+----
| 1 | ramu | 1 | ramu |
| 3 | jill | 3 | jill |
| 5 | sridevi | 5 | sridevi |
| NULL | NULL | 7 | ganga |
+------+---------+----+---------+-----
4 rows in set (0.00 sec)

5. Division
Important: Division is not supported by SQL implementations. However, it can be represented using other operations.(like
cross join, Except, In )

Given two relations(tables): R(x,y) , S(y).


R and S : tables
x and y : column of R
y : column of S
R(x,y) div S(y) means gives all distinct values of x from R that are associated with all values of y in S.
Computation of Division : R(x,y) div S(y)
Steps:
 Find out all possible combinations of S(y) with R(x) by computing R(x) x(cross join) S(y), say r1
 Subtract actual R(x,y) from r1, say r2
 x in r2 are those that are not associated with every value in S(y); therefore R(x)-r2(x) gives us x
that are associated with all values in S
Queries
1. Implementation 1:
2. SELECT * FROM R
3. WHERE x not in ( SELECT x FROM (
4. (SELECT x , y FROM (select y from S ) as p cross join
5. (select distinct x from R) as sp)
6. EXCEPT
(SELECT x , y FROM R) ) AS r );

***************************************************************************************
***********
JOINS

What is Join in DBMS?


Join in DBMS is a binary operation which allows you to combine join product and selection in one single
statement. The goal of creating a join condition is that it helps you to combine the data from two or more DBMS
tables. The tables in DBMS are associated using the primary key and foreign keys.
JOINS are used with SELECT statement. It is used to retrieve data from multiple tables. It is performed
whenever you need to fetch records from two or more tables.
There are three types of joins:

Types of Join
There are mainly two types of joins in DBMS:

1. Inner Joins: Theta, Natural, EQUI


2. Outer Join: Left, Right, Full

Inner Join
Inner Join is used to return rows from both tables which satisfy the given condition. It is the most widely used join
operation and can be considered as a default join-type

An Inner join or equijoin is a comparator-based join which uses equality comparisons in the join-predicate.
However, if you use other comparison operators like “>” it can’t be called equijoin.

SELECT Customers.CustomerName, Orders.OrderID


FROM Customers
INNER JOIN Orders
ON Customers.CustomerID = Orders.CustomerID;

Inner Join further divided into three subtypes:

 Theta join
 Natural join
 EQUI join

Theta Join
Theta Join allows you to merge two tables based on the condition represented by theta. Theta joins work for all
combines. In relational database systems, joins are fundamental for retrieving data from multiple tables. The
Theta Join is a versatile join type that allows for a broader range of conditions compared to the more commonly
used Inner Join, which strictly relies on equality conditions.

Definition and Syntax

A Theta Join can be defined as follows:

SELECT *
FROM TableA A
JOIN TableB B
ON A.column_name operator B.column_name;

Here, operator can be any comparison operator such as <, >, <=, >=, !=, or =. The result of a Theta Join will
include all combinations of rows from both tables where the specified condition holds true.
Example Scenario

Consider two tables: Employees and Departments.

Employees Table:
EmployeeI
Name Salary
D
1 Alice 70000
2 Bob 50000
3 Charlie 60000

Departments Table:

DepartmentID DepartmentName MinSalary


1 HR 55000
2 IT 60000
3 Sales 45000
To find all employees whose salary is greater than the minimum salary of their respective departments, we can
use a Theta Join as follows:

SELECT E.Name, D.DepartmentName


FROM Employees E
JOIN Departments D
ON E.Salary > D.MinSalary;

Result Set
The result of the above query would yield:

Name DepartmentName
Alice HR
Charlie IT
Bob Sales
Performance Considerations

While Theta Joins are powerful, they can also lead to performance issues, especially with large datasets. The
database engine must evaluate the join condition for every combination of rows from the participating tables,
which can result in a Cartesian product if not properly constrained.

To optimize performance:

 Indexes: Ensure that the columns involved in the join condition are indexed.
 Filtering: Apply additional filtering conditions in the WHERE clause to reduce the number of rows
processed.
 Join Order: Consider the order of joins, as it can significantly impact performance.

Conclusion

Theta Joins provide a flexible way to combine data from multiple tables based on various conditions. By
understanding how to implement and optimize Theta Joins, database professionals can enhance their querying
capabilities and improve the efficiency of data retrieval operations. As with any join operation, careful
consideration of the join conditions and performance implications is essential for effective database management.

comparison operators. It is denoted by symbol θ.

The general case of JOIN operation is called a Theta join.

⋈ B
Syntax:

A θ

Theta join can use any conditions in the selection criteria.


Consider the following tables.
Table A Table B
column 1 column 2 column 1 column 2
1 1 1 1
1 2 1 3

For example:
A ⋈ A.column 2 > B.column 2 (B)

A ⋈ A.column 2 > B.column 2 (B)


column 1 column 2
1 2

EQUI Join(Simple Join)


EQUI Join is done when a Theta join uses only the equivalence condition. EQUI join is the most difficult
operation to implement efficiently in an RDBMS, and one reason why RDBMS have essential performance
problems.
An EQUI Join is a powerful tool in SQL that allows you to combine records from two or more tables based on a
common attribute. The term "EQUI" comes from the equality condition used in the join, where the values in the
specified columns must be equal for the records to be combined. This type of join is particularly useful when
dealing with normalized databases, where data is distributed across multiple tables to reduce redundancy.

Understanding EQUI Join


To grasp the concept of an EQUI Join, consider the following scenario:
 Table A: Employees
o EmployeeID
o EmployeeName
o DepartmentID
 Table B: Departments
o DepartmentID
o DepartmentName

In this example, the DepartmentID column serves as the common attribute between the two tables. An EQUI Join
will allow us to retrieve a list of employees along with their respective department names.

SQL Syntax for EQUI Join


The SQL syntax for performing an EQUI Join can be expressed as follows:

SELECT A.EmployeeID, A.EmployeeName, B.DepartmentName


FROM Employees A
JOIN Departments B ON A.DepartmentID = B.DepartmentID;

In this query:
 We are selecting the EmployeeID and EmployeeName from the Employees table (aliased as A) and
the DepartmentName from the Departments table (aliased as B).
 The JOIN clause specifies that we want to combine records from both tables where
the DepartmentID matches.

A ⋈
For example:

A.column 2 = B.column 2 (B)


A ⋈ A.column 2 = B.column 2 (B)

column 1 column 2

1 1

Natural Join (⋈)


Natural Join does not utilize any of the comparison operators. In this type of join, the attributes should have the
same name and domain. In Natural Join, there should be at least one common attribute between two relations.
It performs selection forming equality on those attributes which appear in both relations and eliminates the
duplicate attributes.

A natural join is a type of join operation that creates an implicit join by


combining tables based on columns with the same name and data type.
It is similar to the INNER or LEFT JOIN, but we cannot use the ON or USING clause with
natural join as we used in them.

Points to remember:
o There is no need to specify the column names to join.
o The resultant table always contains unique columns.
o It is possible to perform a natural join on more than two tables.
o Do not use the ON clause.

Syntax:
The following is a basic syntax to illustrate the natural join:
SELECT [column_names | *]
FROM table_name1
NATURAL JOIN table_name2;

SELECT Customers.CustomerName, Orders.OrderID


FROM Customers
CROSS JOIN Orders;

In this syntax, we need to specify the column names to be included in the result set
after the SELECT keyword. If we want to select all columns from both tables,
the * operator will be used. Next, we will specify the table names for joining after the
FROM keyword and write the NATURAL JOIN clause between them.

Example:

Consider the following two tables

C
Num Square
2 4
3 9
D
Num Cube
2 8

C ⋈ D
3 18

C⋈D
Num Square Cube
2 4 8
3 9 18

Outer Join
An Outer Join doesn’t require each record in the two join tables to have a matching record. In this type of join, the
table retains each record even if no other matching record exists.

Three types of Outer Joins are:


 Left Outer Join
 Right Outer Join
 Full Outer Join

Left Outer Join (A ⟕ B)


Left Outer Join returns all the rows from the table on the left even if no matching rows have been found in the
table on the right. When no matching record is found in the table on the right, NULL is returned.

Syntax
1. SELECT table1.column1, table1.column2, table2.column1,....
2. FROM table1
3. LEFT JOIN table2
4. ON table1.matching_column = table2.matching_column;

SELECT Customers.CustomerName, Orders.OrderID


FROM Customers
LEFT JOIN Orders
ON Customers.CustomerID = Orders.CustomerID;

Consider the following 2 Tables

A
Num Square
2 4
3 9
4 16
B
Num Cube
2 8
3 18
5 75

A⋈B
A B

Num Square Cube

2 4 8

3 9 18

4 16 –

Right Outer Join ( A ⟖ B )


Right Outer Join returns all the columns from the table on the right even if no matching rows have been found in
the table on the left. Where no matches have been found in the table on the left, NULL is returned. RIGHT outer
JOIN is the opposite of LEFT JOIN
Syntax
1. SELECT table1.column1, table1.column2, table2.column1,....
2. FROM table1
3. RIGHT JOIN table2
4. ON table1.matching_column = table2.matching_column;

SELECT Customers.CustomerName, Orders.OrderID


FROM Customers
RIGHT JOIN Orders
ON Customers.CustomerID = Orders.CustomerID;

In our example, let’s assume that you need to get the names of members and movies rented by them. Now we
have a new member who has not rented any movie yet.

A⋈B
A B

Num Cube Square

2 8 4

3 18 9

5 75 –

Full Outer Join ( A ⟗ B)


In a Full Outer Join , all tuples from both relations are included in the result, irrespective of the matching
condition. A full outer join returns all the rows from both tables, including the unmatched rows. If there is no
match, NULL values are returned for the columns of the table that does not have a matching row. This type of join
is useful when we want to retrieve all the records from both tables, regardless of whether there is a match or not.

Syntax
1. SELECT table1.column1, table1.column2, table2.column1,....
2. FROM table1
3. FULL JOIN table2
4. ON table1.matching_column = table2.matching_column;

SELECT Customers.CustomerName, Orders.OrderID


FROM Customers
FULL OUTER JOIN Orders
ON Customers.CustomerID = Orders.CustomerID;

Example:

A B
A⋈B

Num Square Cube

2 4 8

3 9 18

4 16 –

5 – 75

Summary
 There are mainly two types of joins in DBMS 1) Inner Join 2) Outer Join
 An inner join is the widely used join operation and can be considered as a default join-type.
 Inner Join is further divided into three subtypes: 1) Theta join 2) Natural join 3) EQUI join
 Theta Join allows you to merge two tables based on the condition represented by theta
 When a theta join uses only equivalence condition, it becomes an equi join.
 Natural join does not utilize any of the comparison operators.
 An outer join doesn’t require each record in the two join tables to have a matching record.
 Outer Join is further divided into three subtypes are: 1)Left Outer Join 2) Right Outer Join 3) Full Outer
Join
 The LEFT Outer Join returns all the rows from the table on the left, even if no matching rows have been
found in the table on the right.
 The RIGHT Outer Join returns all the columns from the table on the right, even if no matching rows have
been found in the table on the left.
 In a full outer join, all tuples from both relations are included in the result, irrespective of the matching
condition.

*****************************************************************************

Aggregate Functions
MySQL's aggregate function is used to perform calculations on multiple values
and return the result in a single value like the average of all values, the sum
of all values, and maximum & minimum value among certain groups of values. We
mostly use the aggregate functions with SELECT statements in the data query
languages.
In database management an aggregate function is a function where the values of multiple rows
are grouped together as input on certain criteria to form a single value of more significant
meaning.

Various Aggregate Functions


1) Count()
2) Sum()
3) Avg()
4) Min()
5) Max()

Syntax:
The following are the syntax to use aggregate functions in MySQL:
1. function_name (DISTINCT | ALL expression)
In the above syntax, we had used the following parameters:
o First, we need to specify the name of the aggregate function.
o Second, we use the DISTINCT modifier when we want to calculate the result
based on distinct values or ALL modifiers when we calculate all values,
including duplicates. The default is ALL.
o Third, we need to specify the expression that involves columns and arithmetic
operators.

There are various aggregate functions available in MySQL. Some of the most
commonly used aggregate functions are summarised in the below table:

Aggregate Descriptions
Function

count() It returns the number of rows,


including rows with NULL values in a
group.

sum() It returns the total summed values


(Non-NULL) in a set.

average() It returns the average value of an


expression.

min() It returns the minimum (lowest) value


in a set.

max() It returns the maximum (highest)


value in a set.

groutp_concat( It returns a concatenated string.


)

first() It returns the first value of an


expression.

last() It returns the last value of an


expression.

Why we use aggregate functions?

We mainly use the aggregate functions in databases, spreadsheets and many other
data manipulation software packages. In the context of business, different
organization levels need different information such as top levels managers interested
in knowing whole figures and not the individual details. These functions produce the
summarised data from our database. Thus they are extensively used in economics
and finance to represent the economic health or stock and sector performance.
:

Count() Function
MySQL count() function returns the total number of values in the expression. This
function produces all rows or only some rows of the table based on a specified
condition, and its return type is BIGINT. It returns zero if it does not find any matching
rows. It can work with both numeric and non-numeric data types.
COUNT(*)
or
COUNT( [ALL|DISTINCT] expression )

SELECT COUNT(*)
FROM PRODUCT_MAST;
-------------------------------------------------------------------------------------------------------------------------
--------

Sum() Function
The MySQL sum() function returns the total summed (non-NULL) value of an
expression. It returns NULL if the result set does not have any rows. It works with
numeric data type only.
SUM()
or
SUM( [ALL|DISTINCT] expression )

Suppose we want to calculate the total number of working hours of all employees in
the table, we need to use the sum() function as shown in the following query:
1. mysql> SELECT SUM(working_hours) AS "Total working hours" FROM employee;
2. ----------------------------------------------------------------------------------------------------------

AVG() Function

MySQL AVG() function calculates the average of the values specified in the
column. Similar to the SUM() function, it also works with numeric data type only.

AVG()
or
AVG( [ALL|DISTINCT] expression )

Suppose we want to get the average working hours of all employees in the table, we
need to use the AVG() function as shown in the following query:

mysql> SELECT AVG(working_hours) AS "Average working hours" FROM employee;


------------------------------------------------------------------------------------------------

MIN() Function
MySQL MIN() function returns the minimum (lowest) value of the specified
column. It also works with numeric data type only.
MIN()
or
MIN( [ALL|DISTINCT] expression )

Suppose we want to get minimum working hours of an employee available in the


table, we need to use the MIN() function as shown in the following query:

mysql> SELECT MIN(working_hours) AS Minimum_working_hours FROM employee;


-----------------------------------------------------------------------------------------------------------

MAX() Function
MySQL MAX() function returns the maximum (highest) value of the specified
column. It also works with numeric data type only.
MAX()
or
MAX( [ALL|DISTINCT] expression )
Suppose we want to get maximum working hours of an employee available in the
table, we need to use the MAX() function as shown in the following query:
mysql> SELECT MAX(working_hours) AS Maximum_working_hours FROM employee;
-------------------------------------------------------------------------

LAST() Function
This function returns the last value of the specified column. To get the last value of
the column, we must have to use the ORDER BY and LIMIT clause. It is because the
LAST() function only supports in MS Access.
Suppose we want to get the last working hour of an employee available in the table,
we need to use the following query:
mysql> SELECT working_hours FROM employee ORDER BY name DESC LIMIT 1;
***************************************************************************************
************************************************

MySQL Subquery
A subquery in MySQL is a query, which is nested into another SQL query and
embedded with SELECT, INSERT, UPDATE or DELETE statement along with the various
operators. We can also nest the subquery with another subquery.
A subquery is known as the inner query, and the query that contains subquery is
known as the outer query. The inner query executed first gives the result to the
outer query, and then the main/outer query will be performed.
MySQL allows us to use subquery anywhere, but it must be closed within parenthesis.
All subquery forms and operations supported by the SQL standard will be supported in
MySQL also.
The following are the rules to use subqueries:
o Subqueries should always use in parentheses.
o If the main query does not have multiple columns for subquery, then a
subquery can have only one column in the SELECT command.
o We can use various comparison operators with the subquery, such as >, <, =,
IN, ANY, SOME, and ALL. A multiple-row operator is very useful when the
subquery returns more than one row.
o We cannot use the ORDER BY clause in a subquery, although it can be used
inside the main query.
o If we use a subquery in a set function, it cannot be immediately enclosed in a
set function.

The following are the advantages of using subqueries:


o The subqueries make the queries in a structured form that allows us to isolate
each part of a statement.
o The subqueries provide alternative ways to query the data from the table;
otherwise, we need to use complex joins and unions.
o The subqueries are more readable than complex join or union statements.

MySQL Subquery Syntax

The following is the basic syntax to use the subquery in MySQL:


SELECT column_list (s) FROM table_name
WHERE column_name OPERATOR
(SELECT column_list (s) FROM table_name [WHERE])

1. SELECT emp_name, city, income FROM employees


2. WHERE emp_id IN (SELECT emp_id FROM employees);

MySQL Subquery with Comparison Operator


A comparison operator is an operator used to compare values and returns the result,
either true or false. The following comparison operators are used in MySQL <, >, =,
<>, <=>, etc. We can use the subquery before or after the comparison operators that
return a single value. The returned value can be the arithmetic expression or a column
function. After that, SQL compares the subquery results with the value on the other
side of the comparison operator. The below example explains it more clearly:
Following is a simple SQL statement that returns the employee detail whose
income is more than 350000 with the help of subquery:
SELECT * FROM employees
WHERE emp_id IN (SELECT emp_id FROM employees
WHERE income > 350000);

SELECT emp_name, city, income FROM employees


WHERE income = (SELECT MAX(income) FROM employees);

MySQL Subquery with IN or NOT-IN Operator


If the subquery produces more than one value, we need to use the IN or NOT IN
operator with the WHERE clause. Suppose we have a table
named "Student" and "Student2" that contains the following data:
1. SELECT Name, City FROM student
2. WHERE City NOT IN (
3. SELECT City FROM student2 WHERE City='Los Angeles');

MySQL Subquery in the FROM Clause


If we use a subquery in the FROM clause, MySQL will return the output from a
subquery is used as a temporary table. We called this table as a derived table, inline
views, or materialized subquery.
1. SELECT Max(items), MIN(items), FLOOR(AVG(items))
2. FROM
3. (SELECT order_id, COUNT(order_id) AS items FROM orders
4. GROUP BY order_date) AS Student_order_detail;

MySQL Correlated Subqueries


A correlated subquery in MySQL is a subquery that depends on the outer query. It
uses the data from the outer query or contains a reference to a parent query that also
appears in the outer query. MySQL evaluates it once from each row in the outer query.
1. SELECT emp_name, city, income
2. FROM employees emp WHERE income > (
3. SELECT AVG(income) FROM employees WHERE city = emp.city);

The below SQL statements uses EXISTS operator to find the name, occupation, and
age of the customer who has placed at least one order.

1. SELECT name, occupation, age FROM customer C


2. WHERE EXISTS (SELECT * FROM Orders O
3. WHERE C.cust_id = O.cust_id);

This statement uses NOT EXISTS operator that returns the customer details who have
not placed an order.

1. SELECT name, occupation, age FROM customer C


2. WHERE NOT EXISTS (SELECT * FROM Orders O
3. WHERE C.cust_id = O.cust_id);

MySQL ROW Subqueries


It is a subquery that returns a single row where we can get more than one column
values. We can use the following operators for comparing row subqueries =, >, <, >=,
<=, <>, !=, <=>. Let us see the following example:
1. SELECT * FROM customer C WHERE ROW(cust_id, occupation) = (
2. SELECT order_id, order_date FROM Orders O WHERE C.cust_id = O.cust_id);
If given row has cust_id, occupation values equal to the order_id, order_date values of
any rows in the first table, the WHERE expression is TRUE, and each query returns
those first table rows. Otherwise, the expression is FALSE, and the query produces an
empty set, which can be shown in the below image:

MySQL Subqueries with ALL, ANY, and SOME


We can use a subquery which is followed by the keyword ALL, ANY, or SOME after a
comparison operator. The following are the syntax to use subqueries with ALL, ANY, or
SOME:
1. operand comparison_operator ANY (subquery)
2. operand comparison_operator ALL (subquery)
3. operand comparison_operator SOME (subquery)
The ALL keyword compares values with the value returned by a subquery. Therefore,
it returns TRUE if the comparison is TRUE for ALL of the values returned by a
subquery. The ANY keyword returns TRUE if the comparison is TRUE for ANY of the
values returned by a subquery. The ANY and SOME keywords are the same because
they are the alias of each other. The following example explains it more clearly:
1. SELECT cust_id, name FROM customer WHERE
2. cust_id > ANY (SELECT cust_id FROM Orders);

If we use ALL in place of ANY, it will return TRUE when the comparison is TRUE for ALL
values in the column returned by a subquery. For example:

1. SELECT cust_id, name FROM customer WHERE


2. cust_id > ALL (SELECT cust_id FROM Orders);

))))))))))))))))))))))))))))))))))

Overview
Nested query is one of the most useful functionalities of SQL. Nested queries are useful when we
want to write complex queries where one query uses the result from another query. Nested queries
will have multiple SELECT statements nested together. A subquery is a SELECT statement nested
within another SELECT statement.

What is a Nested Query in SQL?


A nested query in SQL contains a query inside another query. The outer query will use the result of
the inner query. For instance, a nested query can have two SELECT statements, one on the inner
query and the other on the outer query.

What are the Types of Nested Queries in SQL?


Nested queries in SQL can be classified into two different types:

 Independent Nested Queries


 Co-related Nested Queries
Independent Nested Queries
In independent nested queries, the execution order is from the innermost query to the outer query.
An outer query won't be executed until its inner query completes its execution. The outer query
uses the result of the inner query. Operators such as IN, NOT IN, ALL, and ANY are used to write
independent nested queries.

 The IN operator checks if a column value in the outer query's result is present in the inner query's result. The final result
will have rows that satisfy the IN condition.
 The NOT IN operator checks if a column value in the outer query's result is not present in the inner query's result. The
final result will have rows that satisfy the NOT IN condition.
 The ALL operator compares a value of the outer query's result with all the values of the inner query's result and returns
the row if it matches all the values.
 The ANY operator compares a value of the outer query's result with all the inner query's result values and returns the
row if there is a match with any value.

Co-related Nested Queries


In co-related nested queries, the inner query uses the values from the outer query to execute the
inner query for every row processed by the outer query. The co-related nested queries run slowly
because the inner query is executed for every row of the outer query's result.

How to Write Nested Query in SQL?


We can write a nested query in SQL by nesting a SELECT statement within
another SELECT statement. The outer SELECT statement uses the result of the
inner SELECT statement for processing.
The general syntax of nested queries will be:
SELECT column_name [, column_name ]
FROM table1 [, table2 ]
WHERE column_name OPERATOR
(
SELECT column_name [, column_name ]
FROM table1 [, table2 ]
[WHERE]
)

The SELECT query inside the brackets () is the inner query, and the SELECT query outside the
brackets is the outer query. The outer query uses the result of the inner query.

Examples of Nested Query in SQL


We will use the Employees and Awards table below to understand independent and co-related
nested queries. We will be using Oracle SQL syntax in our queries.

Let's create the Employees and Awards tables:

CREATE TABLE Employees (


id NUMBER PRIMARY KEY,
name VARCHAR2(100) NOT NULL,
salary NUMBER NOT NULL,
role VARCHAR2(100) NOT NULL
);
CREATE TABLE Awards(
id NUMBER PRIMARY KEY,
employee_id NUMBER NOT NULL,
award_date DATE NOT NULL
);
INSERT INTO Employees VALUES (1, 'Augustine Hammond', 10000, 'Developer');
INSERT INTO Employees VALUES (2, 'Perice Mundford', 10000, 'Manager');
INSERT INTO Employees VALUES (3, 'Cassy Delafoy', 30000, 'Developer');
INSERT INTO Employees VALUES (4, 'Garwood Saffen', 40000, 'Manager');
INSERT INTO Employees VALUES (5, 'Faydra Beaves', 50000, 'Developer');

INSERT INTO Awards VALUES(1, 1, TO_DATE('2022-04-01', 'YYYY-MM-DD'));


INSERT INTO Awards VALUES(2, 3, TO_DATE('2022-05-01', 'YYYY-MM-DD'));

Employees
id name salary role

1 Augustine Hammond 10000 Developer

2 Perice Mundford 10000 Manager

3 Cassy Delafoy 30000 Developer

4 Garwood Saffen 40000 Manager

5 Faydra Beaves 50000 Developer

Awards
id employee_id award_date

1 1 2022-04-01

2 3 2022-05-01
id employee_id award_date

Independent Nested Queries

Example 1: IN
Select all employees who won an award.
SELECT id, name FROM Employees
WHERE
id IN (SELECT employee_id FROM Awards);

Output

id name
1 Augustine Hammond
Cassy Delafoy
3

Example 2: NOT IN
Select all employees who never won an award.
SELECT id, name FROM Employees
WHERE id NOT IN (SELECT employee_id FROM Awards);

Output

id name
2 Perice Mundford
4 Garwood Saffen
5 Faydra Beaves

Example 3: ALL
Select all Developers who earn more than all the Managers
SELECT * FROM Employees
WHERE role = 'Developer'
AND salary > ALL (
SELECT salary FROM Employees WHERE role = 'Manager'
);

Output
id name salary role

5 Faydra Beaves 50000 Developer


Explanation
The developer with id 5 earns (50000) more than all the managers: 2 (10000) and 4 (40000)
Example 4: ANY
SELECT * FROM Employees
WHERE role = 'Developer'
AND salary > ANY (
SELECT salary FROM Employees WHERE role = 'Manager'
);

Output
id name salary role

5 Faydra Beaves 50000 Developer

3 Cassy Delafoy 30000 Developer

Explanation
The developers with id 3 and 5 earn more than any manager:

 The developer with id 3 earns (30000) more than the manager with id 2 (10000)
 The developer with id 5 earns (50000) more than the managers with id 2 (10000) and 4 (40000)

Co-related Nested Queries


Select all employees whose salary is above the average salary of employees in their role.
SELECT * FROM Employees emp1
WHERE salary > (
SELECT AVG(salary)
FROM Employees emp2
WHERE emp1.role = emp2.role
);

Output
id name salary role

4 Garwood Saffen 40000 Manager

5 Faydra Beaves 50000 Developer

Explanation
The manager with id 4 earns more than the average salary of all managers (25000), and the
developer with id 5 earns more than the average salary of all developers (30000). The inner query is
executed for all rows fetched by the outer query. The inner query uses the role value (emp1.role)
of every outer query's row (emp1.role = emp2.role).
We can find the average salary of managers and developers using the below query:
SELECT role, AVG(salary)
FROM Employees
GROUP BY role;

role avg(salary)
Developer 30000
Manager 25000

************************

views
Views in DBMS (Database Management Systems) are virtual tables that are
derived from the result of a query. They provide a way to present data from
one or more tables in a customized manner without actually modifying the
underlying tables. Views are widely used in database systems to simplify
complex queries, enhance security, and improve performance.
Definition of Views
A view is a logical representation of data that is stored in one or more tables. It
is defined by a query that retrieves data from the underlying tables and
presents it as a virtual table. The view itself does not store any data; it is just a
saved query that can be executed to retrieve the desired data.
Syntax for Creating Views
To create a view in DBMS, you can use the CREATE VIEW statement followed
by the view name and the query that defines the view. The basic syntax for
creating a view is as follows:
CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;

In this syntax:
 view_name is the name of the view you want to create.

 column1, column2, ... are the columns you want to include in the view.
 table_name is the name of the table(s) from which you want to retrieve
data.
 condition is an optional condition that filters the data retrieved from the
table(s).
Example of Creating a View
Let's consider a scenario where we have two
tables: employees and departments. The employees table contains information
about employees, such as their names, salaries, and department IDs.
The departments table contains information about departments, such as their
names and IDs.
We can create a view called employee_details that combines data from both
tables to provide a consolidated view of employee information. Here's an
example of how to create this view:
CREATE VIEW employee_details AS
SELECT e.name, e.salary, d.department_name
FROM employees e
JOIN departments d ON e.department_id = d.department_id;

In this example, the employee_details view includes the employee's name,


salary, and department name. It retrieves this information by joining
the employees and departments tables on the department_id column.
Using Views
Once a view is created, it can be used just like a regular table in queries. You
can select data from the view, filter it, join it with other tables, and perform
various other operations. The underlying query of the view is executed each
time the view is accessed, ensuring that the data is always up to date.
Views provide several benefits in DBMS:
1. Simplifying Complex Queries: Views allow you to encapsulate
complex queries into a single view, making it easier to retrieve specific
data without having to write complex queries every time.
2. Enhancing Security: Views can be used to restrict access to sensitive
data by providing a controlled interface. You can grant users access to
specific views while hiding the underlying tables and columns.
3. Improving Performance: Views can improve query performance by
precomputing complex joins, aggregations, or calculations and storing
the results in the view. This reduces the computational overhead when
executing queries.
4. Data Abstraction: Views provide a layer of abstraction, allowing you to
present a simplified and customized view of the data to different users or
applications.
In conclusion, views in DBMS are virtual tables that provide a logical
representation of data from one or more tables. They are created using
the CREATE VIEW statement and can be used to simplify queries, enhance
security, and improve performance. Views are a powerful tool in database
systems that help in managing and presenting data in a more efficient and
controlled manner.
****************************************************************************
Views in a DBMS are virtual tables that are derived from the underlying base
tables. They provide a way to present a subset of data or a different
perspective of the data to the users. While views do not store any data
themselves, they can be used to simplify complex queries, enhance security,
and provide a logical organization of data.
In a DBMS, there are several operations that can be performed on views to
manipulate and retrieve data. Let's explore some of these operations in detail:
1. Creating Views
To create a view, you need to define its structure and the query that will
populate the view with data. The CREATE VIEW statement is used for this
purpose. Here's an example:
CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
2. Selecting Data from Views
Once a view is created, you can query it just like you would query a regular
table. The SELECT statement is used to retrieve data from a view. Here's an
example:
SELECT * FROM view_name;
3. Updating Views
Views can be updated to modify the underlying data in the base tables.
However, there are certain restrictions on updating views. For example, views
that involve multiple tables or complex expressions may not be updatable. To
update a view, you need to use the UPDATE statement. Here's an example:
UPDATE view_name
SET column1 = value1, column2 = value2
WHERE condition;
4. Inserting Data into Views
In some cases, it is possible to insert data into views. However, there are
certain conditions that need to be met for a view to be updatable. For example,
the view must not contain any derived columns or aggregate functions. To
insert data into a view, you need to use the INSERT statement. Here's an
example:
INSERT INTO view_name (column1, column2, ...)
VALUES (value1, value2, ...);
5. Deleting Data from Views
Views can also be used to delete data from the underlying base tables. To
delete data from a view, you need to use the DELETE statement. Here's an
example:
DELETE FROM view_name
WHERE condition;
6. Dropping Views
If you no longer need a view, you can drop it from the database using the
DROP VIEW statement. Here's an example:
DROP VIEW view_name;
These are some of the common operations that can be performed on views in a
DBMS. It's important to note that the availability and functionality of these
operations may vary depending on the specific DBMS you are using. Therefore,
it's always recommended to refer to the documentation of your DBMS for
detailed information on working with views.
In conclusion, views in a DBMS provide a powerful way to manipulate and
retrieve data. They can be created, selected from, updated, inserted into,
deleted from, and dropped. Understanding these operations can help you
effectively utilize views in your database applications.

You might also like