Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 34

UNIT-3

DBMS Relational Algebra


What is Relational Algebra in DBMS?
 Relational algebra is a procedural query language that works on relational
model.
 The purpose of a query language is to retrieve data from database or perform
various operations such as insert, update, delete on the data.
 relational algebra is a procedural query language, it means that it tells what
data to be retrieved and how to be retrieved.
 relational calculus is a non-procedural query language, which means it tells
what data to be retrieved but doesn’t tell how to retrieve it. We will discuss
relational calculus in a separate tutorial.

Types of operations in relational algebra


We have divided these operations in two categories:
1. Basic Operations
2. Derived Operations

Basic/Fundamental Operations:
1. Select (σ)
2. Project (∏)
3. Union (∪)
4. Set Difference (-)
5. Cartesian product (X)
6. Rename (ρ)

Derived Operations:
1. Natural Join (⋈)
2. Left, Right, Full outer join (⟕, ⟖, ⟗)
3. Intersection (∩)
4. Division (÷)

Select Operator (σ)


Select Operator is denoted by sigma (σ) and it is used to find the tuples (or rows) in
a relation (or table) which satisfy the given condition.(where clause in SQL, which
is used for the same purpose.)

Syntax of Select Operator (σ)

σ Condition/Predicate(Relation/Table name)
Select Operator (σ) Example
Table: CUSTOMER
---------------

Customer_Id Customer_Name Customer_City


----------- ------------- -------------
C10100 Steve Agra
C10111 Raghu Agra
C10115 Chaitanya Noida
C10117 Ajeet Delhi
C10118 Carl Delhi
Query:

σ Customer_City="Agra" (CUSTOMER)
Output:

Customer_Id Customer_Name Customer_City


----------- ------------- -------------
C10100 Steve Agra
C10111 Raghu Agra

σ (CUSTOMER)

Project Operator (∏)


 Project operator is denoted by ∏ symbol and it is used to select desired columns (or
attributes) from a table (or relation).
 Project operator in relational algebra is similar to the Select statement in SQL.

Syntax of Project Operator (∏)

∏ column_name1, column_name2, ...., column_nameN(table_name)


Project Operator (∏) Example
In this example, we have a table CUSTOMER with three columns, we want to
fetch only two columns of the table, which we can do with the help of Project
Operator ∏.

Table: CUSTOMER

Customer_Id Customer_Name Customer_City


----------- ------------- -------------
C10100 Steve Agra
C10111 Raghu Agra
C10115 Chaitanya Noida
C10117 Ajeet Delhi
C10118 Carl Delhi
Query:

∏ Customer_Name, Customer_City (CUSTOMER)


Output:

Customer_Name Customer_City
------------- -------------
Steve Agra
Raghu Agra
Chaitanya Noida
Ajeet Delhi
Carl Delhi

∏ Customer_Name (CUSTOMER)
Output:

Union Operator (∪)


 Union operator is denoted by ∪ symbol and it is used to select all the rows (tuples) from
two tables (relations).
 . Lets say we have two relations R1 and R2 both have same columns and we want to
select all the tuples(rows) from these relations then we can apply the union operator on
these relations.
Note: The rows (tuples) that are present in both the tables will only appear once in
the union set. In short you can say that there are no duplicates present after the
union operation.

Syntax of Union Operator (∪)

table_name1 ∪ table_name2
Union Operator (∪) Example
Table 1: COURSE

Course_Id Student_Name Student_Id


--------- ------------ ----------
C101 Aditya S901
C104 Aditya S901
C106 Steve S911
C109 Paul S921
C115 Lucy S931
Table 2: STUDENT

Student_Id Student_Name Student_Age


------------ ---------- -----------
S901 Aditya 19
S911 Steve 18
S921 Paul 19
S931 Lucy 17
S941 Carl 16
S951 Rick 18
Query:

∏ Student_Name (COURSE) ∪ ∏ Student_Name (STUDENT)


Output:

Student_Name
------------
Aditya
Carl
Paul
Lucy
Rick
Steve
Note: As you can see there are no duplicate names present in the output even
though we had few common names in both the tables, also in the COURSE table
we had the duplicate name itself.

Intersection Operator (∩)


 Intersection operator is denoted by ∩ symbol and it is used to select common rows
(tuples) from two tables (relations).
 Lets say we have two relations R1 and R2 both have same columns and we want to select
all those tuples(rows) that are present in both the relations, then in that case we can apply
intersection operation on these two relations R1 ∩ R2.

Note: Only those rows that are present in both the tables will appear in the result
set.

Syntax of Intersection Operator (∩)

table_name1 ∩ table_name2
Intersection Operator (∩) Example
Lets take the same example that we have taken above.
Table 1: COURSE

Course_Id Student_Name Student_Id


--------- ------------ ----------
C101 Aditya S901
C104 Aditya S901
C106 Steve S911
C109 Paul S921
C115 Lucy S931
Table 2: STUDENT

Student_Id Student_Name Student_Age


------------ ---------- -----------
S901 Aditya 19
S911 Steve 18
S921 Paul 19
S931 Lucy 17
S941 Carl 16
S951 Rick 18
Query:
∏ Student_Name (COURSE) ∩ ∏ Student_Name (STUDENT)
Output:

Student_Name
------------
Aditya
Steve
Paul
Lucy

Set Difference (-)


Set Difference is denoted by – symbol. Lets say we have two relations R1 and R2 and we want to
select all those tuples(rows) that are present in Relation R1 but not present in Relation R2, this
can be done using Set difference R1 – R2.

Syntax of Set Difference (-)

table_name1 - table_name2
Set Difference (-) Example
Lets take the same tables COURSE and STUDENT that we have seen above.

Query:
Lets write a query to select those student names that are present in STUDENT
table but not present in COURSE table.

∏ Student_Name (STUDENT) - ∏ Student_Name (COURSE)


Output:

Student_Name
------------
Carl
Rick

Cartesian product (X)


Cartesian Product is denoted by X symbol. Lets say we have two relations R1 and R2 then the
cartesian product of these two relations (R1 X R2) would combine each tuple of first relation R1
with the each tuple of second relation R2.

Syntax of Cartesian product (X)

R1 X R2
Cartesian product (X) Example
Table 1: R

R
Col_A Col_B
----- ------
AA 100
BB 200
CC 300
Table 2: S

S
Col_X Col_Y
----- -----
XX 99
YY 11
ZZ 101
Query:
Lets find the cartesian product of table R and S.

RXS
Output:

Col_A Col_B Col_X Col_Y


----- ------ ------ ------
AA 100 XX 99
AA 100 YY 11
AA 100 ZZ 101
BB 200 XX 99
BB 200 YY 11
BB 200 ZZ 101
CC 300 XX 99
CC 300 YY 11
CC 300 ZZ 101
Note: The number of rows in the output will always be the cross product of
number of rows in each table. In our example table 1 has 3 rows and table 2 has 3
rows so the output has 3×3 = 9 rows.

Rename (ρ)
Rename (ρ) operation can be used to rename a relation or an attribute of a relation.
Rename (ρ) Syntax:
ρ(new_relation_name, old_relation_name)

Rename (ρ) Example


Lets say we have a table customer, we are fetching customer names and we are
renaming the resulted relation to CUST_NAMES.

Table: CUSTOMER

Customer_Id Customer_Name Customer_City


----------- ------------- -------------
C10100 Steve Agra
C10111 Raghu Agra
C10115 Chaitanya Noida
C10117 Ajeet Delhi
C10118 Carl Delhi
Query:

ρ(CUST_NAMES, ∏(Customer_Name)(CUSTOMER))
Output:

CUST_NAMES
----------
Steve
Raghu
Chaitanya
Ajeet
Carl

Join Operations

 Join operation is essentially a cartesian product followed by a selection criterion.


 Join operation denoted by ⋈.
 JOIN operation also allows joining variously related tuples from different relations.

Types of JOIN:

Various forms of join operation are:

Inner Joins:

 Theta join
 EQUI join
 Natural join

Outer join:

 Left Outer Join


 Right Outer Join
 Full Outer Join

Inner Join:
In an inner join, only those tuples that satisfy the matching criteria are included, while
the rest are excluded. Let's study various types of Inner Joins:

Theta Join:

The general case of JOIN operation is called a Theta join. It is denoted by symbol θ

Example : A ⋈θ B

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 e: A ⋈ A.column 2 > B.column 2 (B)

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

column 1 column 2

1 2

EQUI JOIN:
When a theta join uses only equivalence condition, it becomes a equi join.

For example: A ⋈ 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 can only be performed if there is a common attribute (column) between
the relations. The name and type of the attribute must be same.

Example :

Consider the following two tables

Num Square

2 4

3 9
D

Num Cube

2 8

3 27

C⋈D
C⋈D

Num Square Cube

2 4 4

3 9 27

OUTER JOIN

In an outer join, along with tuples that satisfy the matching criteria, we also include some or all
tuples that do not match the criteria.

Left Outer Join(A   B)

 In the left outer join, operation allows keeping all tuple in the left relation.
 if there is no matching tuple is found in right relation, then the attributes of right relation
in the join result are filled with null values.
Consider the following 2 Tables

Num Square

2 4

3 9

4 16

Num Cube

2 8

3 18

5 75

A B - Left Outer join


A⋈B

Num Square Cube

2 4 4

3 9 9

4 16 -
Right Outer Join: ( A   B )

 In the right outer join, operation allows keeping all tuple in the right relation.
 if there is no matching tuple is found in the left relation, then the attributes of the left
relation in the join result are filled with null values.

A B  Right outer join


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.
 Result of outer join contains all rows of bpth tables

Note : Outer Joins may Produce NULL Values

A B - full outer join


A⋈B

Num Cube Square

2 4 8

3 9 18

4 16 -

5 - 75

SET OPERATIONS IN SQL

SQL supports few Set operations which can be performed on the table data. These are used to get
meaningful results from data stored in the table, under different special conditions.

 UNION
 UNION ALL
 INTERSECT
 MINUS

UNION OPERATION

 UNION is used to combine the results of two or more SELECT statements.


 it will eliminate duplicate rows from its resultset.
 In case of union, number of columns and datatype must be same in both the tables, on
which UNION operation is being applied.
Example of UNION

The First table,

ID Name

1 abhi

2 adam

The Second table,

ID Name

2 adam

3 Chester

Union SQL query will be,

SELECT * FROM First UNION SELECT * FROM Second;


The resultset table will look like,

ID NAME

1 abhi

2 adam

3 Chester

UNION ALL

This operation is similar to Union. But it also shows the duplicate rows.

Example of Union All

The First table,
ID NAME

1 abhi

2 adam

The Second table,

ID NAME

2 adam

3 Chester

Union All query will be like,

SELECT * FROM First UNION ALL SELECT * FROM Second;

The resultset table will look like,

ID NAME

1 abhi

2 adam

2 adam

3 Chester

INTERSECT
 Intersect operation is used to combine two SELECT statements.
 it only retuns the records which are common from both SELECT statements.
 In case of Intersect the number of columns and datatype must be same.

Example of Intersect

The First table,

ID NAME

1 abhi

2 adam

The Second table,

ID NAME

2 adam

3 Chester

Intersect query will be,

SELECT * FROM First INTERSECT SELECT * FROM Second;

The resultset table will look like


ID NAME

2 adam

MINUS
The Minus operation combines results of two SELECT statements and return only those in the
final result, which belongs to the first set of the result.

Example of Minus

The First table,

ID NAME

1 abhi

2 adam

The Second table,

ID NAME

2 adam
3 Chester

Minus query will be,

SELECT * FROM First MINUS SELECT * FROM Second;

The resultset table will look like,

ID NAME

1 abhi

A - B MEANS - ALL THE ROWS IN A THAT ARE NOT PRESENT IN B

B - A MEANS - ALL THE ROWS IN B THAT ARE NOT PRESENT IN A

SQL AGGREGATE FUNCTIONS

 SQL aggregation function is used to perform the calculations on multiple rows of a single
column of a table.
 It returns a single value.
 It is also used to summarize the data.

Types of SQL Aggregation Function


COUNT FUNCTION

 COUNT function is used to Count the number of rows in a database table. It can work on
both numeric and non-numeric data types.
 COUNT function uses the COUNT(*) that returns the count of all the rows in a specified
table. COUNT(*) considers duplicate and Null.

Syntax : COUNT(*)  or  COUNT( [ALL|DISTINCT] expression )  

Sample table:

PRODUCT_MAST

PRODUCT COMPANY QTY RATE COST

Item1 Com1 2 10 20

Item2 Com2 3 25 75

Item3 Com1 2 30 60

Item4 Com3 5 10 50

Item5 Com2 2 20 40
Item6 Cpm1 3 25 75

Item7 Com1 5 30 150

Item8 Com1 3 10 30

Item9 Com2 2 25 50

Item10 Com3 4 30 120

Example: COUNT( )

SELECT COUNT(*)  FROM PRODUCT_MAST;  

Output: 10

Example: COUNT with WHERE

1. SELECT COUNT(*)  FROM PRODUCT_MAST WHERE RATE>=20;  

Output: 7

Example: COUNT() with DISTINCT

SELECT COUNT(DISTINCT COMPANY)  FROM PRODUCT_MAST;    

Output: 3

SUM FUNCTION

Sum function is used to calculate the sum of all selected columns. It works on numeric fields
only.

Syntax : SUM()  or  SUM( [ALL|DISTINCT] expression )  

Example: SUM()

SELECT SUM(COST)  FROM PRODUCT_MAST;  

Output: 670

Example: SUM() with WHERE

SELECT SUM(COST)  FROM PRODUCT_MAST  WHERE QTY>3;  

Output: 320
AVG FUNCTION (AVERAGE)

The AVG function is used to calculate the average value of the numeric type. AVG function
returns the average of all non-Null values.

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

Example: SELECT AVG(COST)  FROM PRODUCT_MAST;  

Output: 67.00

MAX Function (MAXIMUM)

MAX function is used to find the maximum value of a certain column. This function determines
the largest value of all selected values of a column.

Syntax : MAX()  or  MAX( [ALL|DISTINCT] expression )  

Example: SELECT MAX(RATE)  FROM PRODUCT_MAST;  

OUTPUT:30

MIN Function (MINIMUM)

MIN function is used to find the minimum value of a certain column. This function determines
the smallest value of all selected values of a column.

Syntax :MIN()  or  MIN( [ALL|DISTINCT] expression )  

Example: SELECT MIN(RATE)  FROM PRODUCT_MAST;  

Output: 10

SQL GROUP BY AND HAVING CLAUSE

SQL Group by Clause

 The GROUP BY clause is a SQL command that is used to group rows that have the
same values.
 The GROUP BY clause is used in the SELECT statement.
 it is used in conjunction with aggregate functions to produce summary reports from the
database.
 The queries that contain the GROUP BY clause are called grouped queries and only
return a single row for every grouped item.

SQL GROUP BY Syntax


SELECT statements... GROUP BY column_name1[,column_name2,...]
[HAVING condition];

 "SELECT statements..." is the standard SQL SELECT command query.


 "GROUP BY column_name1" is the clause that performs the grouping based on
column_name1.
 "[,column_name2,...]" is optional; represents other column names when the grouping is
done on more than one column.
  "[HAVING condition]" is optional; it is used to restrict the rows affected by the GROUP
BY clause. It is similar to the  WHERE clause.

Grouping using a Single Column


24.1M
In order to help understand the effect of SQL Group By clause, let's execute a simple query that
returns all the gender entries from the members table.
EXAMPLE:

SELECT `gender` FROM `members` ;

gender
Female
Female
Male
Female
Male
Male
Male
Male
Male

Suppose we want to get the unique values for genders. We can use a following query -

SELECT `gender` FROM `members` GROUP BY `gender`;

gender
Female
Male

Note :
Only two results have been returned. This is because we only have two gender types Male and
Female. The GROUP BY clause in SQL grouped all the "Male" members together and returned
only a single row for it. It did the same with the "Female" members.

Grouping using multiple columns

Suppose that we want to get a list of movie category_id  and corresponding years in which they
were released.

SELECT `category_id`,`year_released` FROM `movies` ;

category_id year_released
1 2011
2 2008
NULL 2008
NULL 2010
8 2007
6 2007
6 2007
8 2005
NULL 2012
7 1920
8 NULL
8 1920

The above result has many duplicates.

Let's execute the same query using group by in SQL -

SELECT `category_id`,`year_released` FROM `movies` GROUP BY


`category_id`,`year_released`;

Executing the above script in MySQL workbench against the myflixdb gives us the
following results shown below.

category_id year_released
NULL 2008
NULL 2010
NULL 2012
1 2011
2 2008
6 2007
7 1920
8 1920
8 2005
8 2007

The GROUP BY clause operates on both the category id and year released to
identify unique rows in our above example.

If the category id is the same but the year released is different, then a row is treated as a
unique one .If the category id and the year released is the same for more than one row, then
it's considered a duplicate and only one row is shown.

Grouping and aggregate functions

Suppose we want total number of males and females in our database. We can use the following
script shown below to do that.

SELECT `gender`,COUNT(`membership_number`) FROM `members` GROUP BY `gender`;

gender COUNT('membership_number')
Female 3
Male 5

The results shown below are grouped by every unique gender value posted and the number of
grouped rows is counted using the COUNT aggregate function.

RESTRICTING QUERY RESULTS USING THE HAVING CLAUSE

 It's not always that we will want to perform groupings on all the data in a given table.
 There will be times when we will want to restrict our results to a certain given criteria.  
 In such cases , we can use the HAVING clause

Suppose we want to know all the release years for movie category id 8. We would use the
following script to achieve our results.
SELECT * FROM `movies` GROUP BY `category_id`,`year_released` HAVING
`category_id` = 8;

Executing the above will givw following result

movie_id title director year_released category_id


9 Honey mooners John Schultz 2005 8
5 Daddy's Little Girls NULL 2007 8

Note only movies with category id 8 have been affected by our GROUP BY clause.

Points To Remember

 The GROUP BY Clause SQL is used to group rows with same values.
 The GROUP BY Clause is used together with the SQL SELECT statement.
 The SELECT statement used in the GROUP BY clause can only be used contain column
names, aggregate functions, constants and expressions.
 SQL Having Clause is used to restrict the results returned by the GROUP BY clause.
 SQL GROUP BY Clause is used to collect data from multiple records and returned
record set by one or more columns.

SQL GROUP BY AND HAVING CLAUSE

SQL Group by Clause

 The GROUP BY clause is a SQL command that is used to group rows that have the
same values.
 The GROUP BY clause is used in the SELECT statement.
 it is used in conjunction with aggregate functions to produce summary reports from the
database.
 The queries that contain the GROUP BY clause are called grouped queries and only
return a single row for every grouped item.

SQL GROUP BY Syntax

SELECT statements... GROUP BY column_name1[,column_name2,...]


[HAVING condition];

 "SELECT statements..." is the standard SQL SELECT command query.


 "GROUP BY column_name1" is the clause that performs the grouping based on
column_name1.
 "[,column_name2,...]" is optional; represents other column names when the grouping is
done on more than one column.
  "[HAVING condition]" is optional; it is used to restrict the rows affected by the GROUP
BY clause. It is similar to the  WHERE clause.

Grouping using a Single Column


24.1M
In order to help understand the effect of SQL Group By clause, let's execute a simple query that
returns all the gender entries from the members table.
EXAMPLE:

SELECT `gender` FROM `members` ;

gender
Female
Female
Male
Female
Male
Male
Male
Male
Male

Suppose we want to get the unique values for genders. We can use a following query -

SELECT `gender` FROM `members` GROUP BY `gender`;

gender
Female
Male

Note :

Only two results have been returned. This is because we only have two gender types Male and
Female. The GROUP BY clause in SQL grouped all the "Male" members together and returned
only a single row for it. It did the same with the "Female" members.

Grouping using multiple columns


Suppose that we want to get a list of movie category_id  and corresponding years in which they
were released.

SELECT `category_id`,`year_released` FROM `movies` ;

category_id year_released
1 2011
2 2008
NULL 2008
NULL 2010
8 2007
6 2007
6 2007
8 2005
NULL 2012
7 1920
8 NULL
8 1920

The above result has many duplicates.

Let's execute the same query using group by in SQL -

SELECT `category_id`,`year_released` FROM `movies` GROUP BY


`category_id`,`year_released`;

Executing the above script in MySQL workbench against the myflixdb gives us the
following results shown below.

category_id year_released
NULL 2008
NULL 2010
NULL 2012
1 2011
2 2008
6 2007
7 1920
8 1920
8 2005
8 2007
The GROUP BY clause operates on both the category id and year released to
identify unique rows in our above example.

If the category id is the same but the year released is different, then a row is treated as a
unique one .If the category id and the year released is the same for more than one row, then
it's considered a duplicate and only one row is shown.

Grouping and aggregate functions

Suppose we want total number of males and females in our database. We can use the following
script shown below to do that.

SELECT `gender`,COUNT(`membership_number`) FROM `members` GROUP BY `gender`;

gender COUNT('membership_number')
Female 3
Male 5

The results shown below are grouped by every unique gender value posted and the number of
grouped rows is counted using the COUNT aggregate function.

RESTRICTING QUERY RESULTS USING THE HAVING CLAUSE

 It's not always that we will want to perform groupings on all the data in a given table.
 There will be times when we will want to restrict our results to a certain given criteria.  
 In such cases , we can use the HAVING clause

Suppose we want to know all the release years for movie category id 8. We would use the
following script to achieve our results.

SELECT * FROM `movies` GROUP BY `category_id`,`year_released` HAVING


`category_id` = 8;

Executing the above will givw following result

movie_id title director year_released category_id


9 Honey mooners John Schultz 2005 8
5 Daddy's Little Girls NULL 2007 8
Note only movies with category id 8 have been affected by our GROUP BY clause.

Points To Remember

 The GROUP BY Clause SQL is used to group rows with same values.
 The GROUP BY Clause is used together with the SQL SELECT statement.
 The SELECT statement used in the GROUP BY clause can only be used contain column
names, aggregate functions, constants and expressions.
 SQL Having Clause is used to restrict the results returned by the GROUP BY clause.
 SQL GROUP BY Clause is used to collect data from multiple records and returned
record set by one or more columns.

SQL NESTED QUERY

A Subquery or Nested Query is a query within another SQL query and embedded within
the WHERE clause.

IMPORTANT RULE:

 A subquery can be placed in a number of SQL clauses like WHERE clause, FROM
clause, HAVING clause.
 You can use Subquery with SELECT, UPDATE, INSERT, DELETE statements along
with the operators like =, <, >, >=, <=, IN, BETWEEN, etc.
 A subquery is a query within another query. The outer query is known as the main query,
and the inner query is known as a subquery.
 Subqueries are on the right side of the comparison operator.
 A subquery is enclosed in parentheses.
 In the Subquery, ORDER BY command cannot be used. But GROUP BY command can
be used to perform the same function as ORDER BY command.

SUBQUERIES WITH THE SELECT STATEMENT

SQL subqueries are most frequently used with the Select statement.

SYNTAX:

SELECT column_name  FROM table_name  WHERE column_name expression operator   
( SELECT column_name  from table_name WHERE ... );  

Example:

Consider the EMPLOYEE table have the following records:


ID NAME AGE ADDRESS SALARY

1 John 20 US 2000.00

2 Stephan 26 Dubai 1500.00

3 David 27 Bangkok 2000.00

4 Alina 29 UK 6500.00

5 Kathrin 34 Bangalore 8500.00

6 Harry 42 China 4500.00

7 Jackson 25 Mizoram 10000.00

The subquery with a SELECT statement will be:

SELECT *  FROM EMPLOYEE   WHERE ID IN (SELECT ID   FROM EMPLOYEE   W
HERE SALARY > 4500);  

This would produce the following result:

ID NAME AGE ADDRESS SALARY

4 Alina 29 UK 6500.00

5 Kathrin 34 Bangalore 8500.00

7 Jackson 25 Mizoram 10000.00

SUBQUERIES WITH THE INSERT STATEMENT

 SQL subquery can also be used with the Insert statement. In the insert statement, data
returned from the subquery is used to insert into another table.
 In the subquery, the selected data can be modified with any of the character, date
functions.

Syntax:

INSERT INTO table_name (column1, column2, column3....) SELECT * FROM table_nam
e  
WHERE VALUE OPERATOR  

Example
Consider a table EMPLOYEE_BKP with similar as EMPLOYEE.

Now use the following syntax to copy the complete EMPLOYEE table into the EMPLOYEE_BKP table.

INSERT INTO EMPLOYEE_BKP  SELECT * FROM EMPLOYEE WHERE ID IN 
(SELECT ID  FROM EMPLOYEE);  

SUBQUERIES WITH THE UPDATE STATEMENT

The subquery of SQL can be used in conjunction with the Update statement.
When a subquery is used with the Update statement, then either single or multiple columns in a
table can be updated.

Syntax

UPDATE table  SET column_name = new_value  WHERE VALUE OPERATOR    (SELE
CT COLUMN_NAME     FROM TABLE_NAME     WHERE condition);  

Example

Let's assume we have an EMPLOYEE_BKP table available which is backup of EMPLOYEE


table. The given example updates the SALARY by .25 times in the EMPLOYEE table for all
employee whose AGE is greater than or equal to 29.

UPDATE EMPLOYEE SET SALARY = SALARY * 0.25    WHERE AGE IN 
(SELECT AGE FROM CUSTOMERS_BKP     WHERE AGE >= 29);  

This would impact three rows, and finally, the EMPLOYEE table would have the following records.

ID NAME AGE ADDRESS SALARY

1 John 20 US 2000.00

2 Stephan 26 Dubai 1500.00

3 David 27 Bangkok 2000.00

4 Alina 29 UK 1625.00

5 Kathrin 34 Bangalore 2125.00

6 Harry 42 China 1125.00

7 Jackson 25 Mizoram 10000.00


SUBQUERIES WITH THE DELETE STATEMENT

The subquery of SQL can be used in conjunction with the Delete statement just
like any other statements mentioned above.

Syntax :

DELETE FROM TABLE_NAME WHERE VALUE OPERATOR    (SELECT COLUMN_
NAME    FROM TABLE_NAME     WHERE condition);   

Example

Let's assume we have an EMPLOYEE_BKP table available which is backup


of EMPLOYEE table. The given example deletes the records from the EMPLOYEE table for all
EMPLOYEE whose AGE is greater than or equal to 29.

DELETE FROM EMPLOYEE     WHERE AGE IN 
(SELECT AGE FROM EMPLOYEE_BKP        WHERE AGE >= 29 );  
This would impact three rows, and finally, the EMPLOYEE table would have the following records.

ID NAME AGE ADDRESS SALARY

1 John 20 US 2000.00

2 Stephan 26 Dubai 1500.00

3 David 27 Bangkok 2000.00

7 Jackson 25 Mizoram 10000.00

You might also like