UNIT2

You might also like

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

CONSTRAINTS:

SQL constraints are used to specify rules for data in a table.

Constraints can be specified when the table is created with the CREATE TABLE statement, or
after the table is created with the ALTER TABLE statement.

Syntax
CREATE TABLE table_name  (
     column1 datatype constraint,
     column2 datatype constraint,
     column3 datatype constraint, 
);

The following constraints are commonly used in SQL:

 NOT NULL - Ensures that a column cannot have a NULL value


 UNIQUE - Ensures that all values in a column are different
 PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies
each row in a table
 FOREIGN KEY - Prevents actions that would destroy links between tables
 CHECK - Ensures that the values in a column satisfies a specific condition
 DEFAULT - Sets a default value for a column if no value is specified

NOT NULL CONSTRAINT:


Using Create Statement:

CREATE TABLE Persons (    ID int NOT NULL,    LastName varchar(255) NOT NULL,


 FirstName varchar(255) NOT NULL,    Age number(9));

Using Alter Statement

ALTER TABLE Persons MODIFY Age  NOT NULL;

Drop Constraint (not null)

ALTER TABLE Persons MODIFY Age NULL;

UNIQUE CONSTRAINT:
SQL UNIQUE Constraint

The UNIQUE constraint ensures that all values in a column are different.


Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for a
column or set of columns.

A PRIMARY KEY constraint automatically has a UNIQUE constraint.

However, you can have many UNIQUE constraints per table, but only one PRIMARY
KEY constraint per table.

SQL UNIQUE Constraint

Using Create Statement:

CREATE TABLE Persons (    ID number(9) NOT NULL UNIQUE,    LastName


varchar(255) NOT NULL,    FirstName varchar(255),    Age number(9));

Using Alter Statement


ALTER TABLE Persons ADD CONSTRAINT UC_Person UNIQUE (ID,LastName);

DROP a Unique Constraint


ALTER TABLE Persons DROP CONSTRAINT UC_Person;

PRIMARY KEY CONSTRAINT:
PRIMARY KEY Constraint:

The PRIMARY KEY constraint uniquely identifies each record in a table.

Primary keys must contain UNIQUE values, and cannot contain NULL values.

A table can have only ONE primary key; and in the table, this primary key can consist of single
or multiple columns (fields).

Using Create Statement:

CREATE TABLE Persons (ID number(9) NOT NULL PRIMARY KEY, LastName


varchar(255) NOT NULL,
    FirstName varchar(255), Age int
);

To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint


on multiple columns, use the following SQL syntax:

CREATE TABLE Persons (ID number(9) NOT NULL,LastName varchar(255) NOT NULL,


FirstName varchar(255),Age
mber(9),    CONSTRAINT PK_Person PRIMARY KEY (ID,LastName));
Note: In the example above there is only ONE PRIMARY KEY (PK_Person). However, the
VALUE of the primary key is made up of TWO COLUMNS (ID + LastName).

Using Alter Statement:

ALTER TABLE Persons ADD CONSTRAINT PK_Person PRIMARY KEY (ID);

Drop Constraint:

ALTER TABLE Persons DROP CONSTRAINT PK_Person;

FOREIGN KEY CONSTRAINT:

The FOREIGN KEY constraint is used to prevent actions that would destroy links between
tables.

A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY
KEY in another table.

The table with the foreign key is called the child table, and the table with the primary key is
called the referenced or parent table.
Persons Table

PersonID LastName FirstName Age

1 Hansen Ola 30

2 Svendson Tove 23

3 Pettersen Kari 20

Orders Table

OrderID OrderNumber PersonID

1 77895 3
2 44678 3

3 22456 2

4 24562 1

Notice that the "PersonID" column in the "Orders" table points to the "PersonID" column in the
"Persons" table.

The "PersonID" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.

The "PersonID" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.

The FOREIGN KEY constraint prevents invalid data from being inserted into the foreign key
column, because it has to be one of the values contained in the parent table.

Using Create Statement:

CREATE TABLE Orders (OrderID int NOT NULL PRIMARY KEY,


    OrderNumber int NOT NULL,PersonID
number(9) FOREIGN KEY REFERENCES Persons(PersonID)
);

To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint


on multiple columns, use the following SQL syntax:

CREATE TABLE Orders (OrderID int NOT NULL, OrderNumber int NOT NULL,PersonID


number(9),    PRIMARY KEY (OrderID),   CONSTRAINT FK_PersonOrder FOREIGN KEY (
PersonID)  REFERENCES Persons(PersonID));

Using Alter Statement:

ALTER TABLE Orders
ADD CONSTRAINT FK_PersonOrderFOREIGN KEY (PersonID) REFERENCES Persons(Per
sonID);

Drop Statement:

ALTER TABLE Orders DROP CONSTRAINT FK_PersonOrder;
 CHECK CONSTRAINT:

The CHECK constraint is used to limit the value range that can be placed in a column.

Using Create Statement:

CREATE TABLE Persons (ID number(9) NOT NULL, LastName varchar(255) NOT NULL,


    FirstName varchar(255), Age int CHECK (Age>=18));

To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple


columns, use the following SQL syntax:

CREATE TABLE Persons ( ID number(9) NOT NULL, LastName varchar(255) NOT NULL,


    FirstName varchar(255), Age int, City varchar(255),
    CONSTRAINT CHK_Person CHECK (Age>=18 AND City='Sandnes')
);

Using Alter Statement:

ALTER TABLE Persons ADD CHECK (Age>=18);

To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple


columns, use the following SQL syntax:

ALTER TABLE Persons
ADD CONSTRAINT CHK_PersonAge CHECK (Age>=18 AND City='Sandnes');

Drop Constraint:

ALTER TABLE Persons DROP CONSTRAINT CHK_PersonAge;

DEFAULT CONSTRAINT

The DEFAULT constraint is used to set a default value for a column.

The default value will be added to all new records, if no other value is specified.

Using Create Statement:

CREATE TABLE Persons ( ID number(9) NOT NULL, LastName varchar(255) NOT NULL,


    FirstName varchar(255), Age number(9), City varchar(255) DEFAULT 'Sandnes'
);
Using Alter Statement:

ALTER TABLE Persons modify city default “sanders’;

Drop Constraint:

ALTER TABLE Persons MODIFY City DEFAULT null ;

Reduction to Relational Schemas


 We can represent a database that conforms to an E-R database schema by a collection of
tables.
 For each entity set and for each relationship set in the database, there is a unique table to
which we assign the name of the corresponding entity set or relationship set.
 Each table has multiple columns, each of which has a unique name.
 Both the E-R model and the relational-database model are abstract, logical
representations of real-world enterprises.
 Converting a database representation from an E-R diagram to a table format is the way
we arrive at a relational-database design from an E-R diagram.
Converting ER Diagrams to Tables-
 

 ER diagram is converted into the tables in relational model.


 This is because relational models can be easily implemented by RDBMS like MySQL ,
Oracle etc.

Rule-01: For Strong Entity Set With Only Simple Attributes-


 

A strong entity set with only simple attributes will require only one table in relational model.
 Attributes of the table will be the attributes of the entity set.
 The primary key of the table will be the key attribute of the entity set.
Example-

 
 
Roll_no Name Gender

 
 

Schema : Student ( Roll_no , Name , Gender )


 Rule-02: For Strong Entity Set With Composite Attributes-
 
 A strong entity set with any number of composite attributes will require only one table in
relational model.
 While conversion, simple attributes of the composite attributes are taken into account and not
the composite attribute itself.
 
Example-
 

Roll_n First_nam Last_nam House_n Stree Cit


o e e o t y

 
 
 

Schema : Student ( Roll_no , First_name , Last_name , House_no , Street , City )


 

Rule-03: For Strong Entity Set With Multi Valued Attributes-


 

A strong entity set with any number of multi valued attributes will require two tables in relational
model.
 One table will contain all the simple attributes with the primary key.
 Other table will contain the primary key and all the multi valued attributes.

Example-
 

Roll_no City

Roll_ Mobile_
no no

 
 

Rule-04: Translating Relationship Set into a Table-


 
A relationship set will require one table in the relational model.
Attributes of the table are-
Primary key attributes of the participating entity sets

 Its own descriptive attributes if any.
Set of non-descriptive attributes will be the primary key.
 
Example-
 

Emp_n Dept_i sinc


o d e

Schema : Works in ( Emp_no , Dept_id , since )


 

NOTE-
 
If we consider the overall ER diagram, three tables will be required in relational model-
 One table for the entity set “Employee”
 One table for the entity set “Department”
 One table for the relationship set “Works in”
 

Rule-05: For Binary Relationships With Cardinality Ratios-


 
The following four cases are possible-
 
Case-01: Binary relationship with cardinality ratio m:n
Case-02: Binary relationship with cardinality ratio 1:n
Case-03: Binary relationship with cardinality ratio m:1
Case-04: Binary relationship with cardinality ratio 1:1
 
 

Case-01: For Binary Relationship With Cardinality Ratio m:n

Here, three tables will be required-


1. A ( a1 , a2 )
2. R ( a1 , b1 )
3. B ( b1 , b2 )
 

Case-02: For Binary Relationship With Cardinality Ratio 1:n

 
 

Here, two tables will be required-


1. A ( a1 , a2 )
2. BR ( a1 , b1 , b2 )
 

NOTE- Here, combined table will be drawn for the entity set B and relationship set R.
 

Case-03: For Binary Relationship With Cardinality Ratio m:1

Here, two tables will be required-


1. AR ( a1 , a2 , b1 )
2. B ( b1 , b2 )
 

NOTE- Here, combined table will be drawn for the entity set A and relationship set R.
 
Case-04: For Binary Relationship With Cardinality Ratio 1:1

 
 Here, two tables will be required. Either combine ‘R’ with ‘A’ or ‘B’
 
Way-01: Way-02:
1. A ( a1 , a2 ) 1.AR ( a1 , a2 , b1 )
2. BR ( a1 , b1 , b2 ) 2. B ( b1 , b2 )

Thumb Rules to Remember

 While determining the minimum number of tables required for binary


relationships with given cardinality ratios, following thumb rules must be kept in
mind-
 For binary relationship with cardinality ration m : n , separate and
individual tables will be drawn for each entity set and relationship.
 For binary relationship with cardinality ratio either m : 1 or 1 : n , always
remember “many side will consume the relationship” i.e. a combined table
will be drawn for many side entity set and relationship set.
 For binary relationship with cardinality ratio 1 : 1 , two tables will be
required. You can combine the relationship set with any one of the entity
sets.
 

Rule-06: For Binary Relationship With Both Cardinality Constraints and


Participation Constraints-
 
 Cardinality constraints will be implemented as discussed in Rule-05.
 Because of the total participation constraint, foreign key acquires NOT NULL constraint
i.e. now foreign key can not be null.

Case-01: For Binary Relationship With Cardinality Constraint and Total Participation
Constraint From One Side-
 

Because cardinality ratio = 1 : n , so we will combine the entity set B and relationship set R.
Then, two tables will be required-
1. A ( a1 , a2 )
2. BR ( a1 , b1 , b2 )
Because of total participation, foreign key a1 has acquired NOT NULL constraint, so it can’t be
null now.
 

Case-02: For Binary Relationship With Cardinality Constraint and Total Participation
Constraint From Both Sides-

 Ifthere is a key constraint from both the sides of an entity set with total participation, then that
binary relationship is represented using only single table.
 

Sol: -ARB(a1,a2,b1,b2)
Rule-07: For Binary Relationship With Weak Entity Set -

 Weak entity set always appears in association with identifying relationship with total
participation constraint.
 
 

Here, two tables will be required-


1. A ( a1 , a2 )
2. BR ( a1 , b1 , b2 )

View in DBMS

 Views act as a proxy or virtual table created from the original table.

 Views simplify SQL queries and allow secure access to underlying tables. Views in
DBMS can be visualized as virtual tables that are formed by original tables from the
database.

The view has two primary purposes:

 Simplifying complex SQL queries.


 Restricting users from accessing sensitive data.

Sample Table

Employee Table:

This table contains details of employees in a particular company and has data fields such
as EmpID, EmpName, Address, Contact. We have added 6 records of employees for our
purpose.

EmpID EmpName Address Contact

1 Alex London 05-12421969

2 Adolf San Francisco 01-12584365

3 Aryan Delhi 91-9672367287

4 Bhuvan Hyderabad 91-9983288383


EmpID EmpName Address Contact

5 Carol New York 01-18928992

6 Steve California 01-13783282

EmpRole Table:

This table contains details of employees' roles in a particular company and has data fields
as EmpID, Role, Dept. We have stored all the records particular to the EmpID of each employee.

EmpID Role Dept

1 Intern Engineering

2 Trainee IT

3 Executive HR

4 SDE-1 Engineering

5 SDE-2 Engineering

6 Technical Architect Engineering

Creating View

The view can be created by using the CREATE VIEW statement, Views can be simple or
complex depending on their usage.

Syntax:

CREATE VIEW view_Name AS SELECT column1, column2,....


WHERE condition;

Here, viewName is the Name for the View we set, tableName is the Name of the table
FROM table Name

and condition is the Condition by which we select rows.

Creating a Simple View

Simple view is the view that is made from a single table, It takes only one table and just the
conditions, It also does not take any inbuilt SQL functions like AVG(), MIN(), MAX() etc,
or GROUP BY clause.
While creating a simple view, we are not creating an actual table, we are just projecting the data
from the original table to create a view table.

Example 1: In this example, we are creating a view table from Employee Table for getting
the EmpID and EmpName. So the query will be:

CREATE VIEW EmpView1 AS SELECT EmpID, EmpName


FROM Employee;

Now to see the data in the EmpView1 view created by us, We have to simply use the SELECT
statement.

SELECT * from EmpView1;

Output:

The view table EmpView1 that we have created from Employee Table contains EmpID and
EmpName as its data fields.

EmpID EmpName

1 Alex

2 Adolf

3 Aryan

4 Bhuvan

5 Carol

6 Steve

Creating a Complex View

The complex view is the view that is made from multiple tables, It takes multiple tables in which
data is accessed using joins or cross products, It contains inbuilt SQL functions
like AVG(), MIN(), MAX() etc, or GROUP BY clause. So, whenever we need to access data
from multiple tables we can make use of Complex Views.

Example:

In this example, we are creating a view table using Employee Table and EmpDept table for
getting the EmpName from Employee table and Dept from EmpDept. So the query will be:

CREATE VIEW CompView AS SELECT Employee.EmpName, EmpRole.Dept


FROM Employee, EmpRole WHERE Employee.EmpID = EmpRole.EmpID;
SELECT * from CompView;

Output:

The view table CompView that we have created from Employee Table and EmpRole Table
contains EmpName and Dept as its data fields. We have used the cross join to get our necessary
data.

EmpName Dept

Alex Engineering

Adolf IT

Aryan HR

Bhuvan Engineering

Carol Engineering

Steve Engineering

Deleting view

To delete the view so as we DROP a table in SQL, similarly, we can delete or drop a view using
the DROP statement. The DROP statement completely deletes the structure of the view.

Syntax:

DROP VIEW ViewName;

.Example:

DROP VIEW EmpView1;


SELECT * from EmpView1;

Output:

ORA-00942: table or view does not exist


Updating View

For updating the views we can use CREATE OR REPLACE VIEW statement, new columns will
replace or get added to the view.
Syntax:

CREATE OR REPLACE VIEW ViewName AS SELECT column1,coulmn2,..


FROM TableName WHERE condition;

Example 1:

CREATE OR REPLACE VIEW EmpView1 AS SELECT EmpID, EmpName, Address FROM


Employee;

SELECT * from EmpView1;

Output:

The data fields of view table EmpView1 have been updated to EmpID, EmpName, and Address.

EmpID EmpName Address

1 Alex London

2 Adolf San Francisco

3 Aryan Delhi

4 Bhuvan Hyderabad

5 Carol New York

6 Steve California

Manipulating Data in a View

 Updateable Views are views that allow for data manipulation but there are certain
conditions needed to be taken care of while manipulating the data of the view:

 The GROUP BY and ORDER BY clauses should not be included in the SELECT


statement used to generate the view.
 The DISTINCT keyword should not be used in the SELECT statement.
 All NOT NULL values should be present in the View.
 Nested or complex queries should Views can also be used to manipulate data in the scope
of the view table only, manipulating data in a view does not affect the data of the original
table.

 not be used to construct the view.


 A single table should be used to generate the view. We will not be able to update the if it
was constructed using several tables.

Inserting a row in a view

Inserting view a row in the view takes the same syntax as we use to insert a row in a simple table

Syntax:

INSERT INTO ViewName(column1, column2,..)


VALUES(value1, value2,..);

Here, viewName is the view in which we have to insert data and we add values according to the
columns in the view table.

Example: let's take the above created simple view EmpView2 and we want to insert a new row.

INSERT INTO EmpView2(EmpID, Role) VALUES(4, 'Intern');

Now to see the data in the EmpView2, We have to simply use the SELECT statement.

SELECT * from EmpView2;

Output:

Now the updated table EmpView2 has one more row of EmpID 4 and Role Intern.

EmpID Role

1 Intern

2 Trainee

3 Executive

4 Intern

Deleting a row in a view


Deleting a row in the view takes the same syntax as we use to delete a row in a simple table.

Syntax:

DELETE FROM ViewName WHERE condition;

Here, viewName is the view from which data has been deleted, condition is the Condition by
which we select rows to be deleted.

Example: let's take the above created simple view EmpView2 and we want to delete the row
having EmpID = 1.

DELETE FROM EmpView2 WHERE EmpID = 1;

Now to see the data in the EmpView2, We have to simply use the SELECT statement.

SELECT * from EmpView2;

Output:

Now 1 record with data EmpID 1 and Role Intern has been deleted.

EmpID Role

2 Trainee

3 Executive

4 Intern

Conclusion

Now that we have seen many examples of views in DBMS, let us note down a few points:

 Views are some kind of virtual tables created by original tables from the database.
 Views actually do not hold the actual data and just have the definition of the original

Views act as a proxy or virtual table created from the original table.

 data.The view has two primary purposes:


o Simplifying complex SQL queries.
o Restricting users from accessing sensitive data.
 View can be created by using the CREATE VIEW statement.
o Simple view is the view that is made from a single table.
o Complex view is the view that is made from multiple tables.
 We can delete or drop a view using the DROP statement
 For updating the views we can use CREATE OR REPLACE VIEW statement.
 Inserting a row in a view follows the same syntax as inserting a row in a plain table.
 Deleting a row in the view follows the same syntax as deleting a row in a

Relational Algebra

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.

procedural query language, it means that it tells what data to be retrieved and how to be
retrieved.

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.

\
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
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
Union Operator (∪)

Union operator is denoted by ∪ symbol and it is used to select all the rows (tuples) from two
tables (relations).

Note: union does not display duplicate data.


Unionall displays duplicate data.

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).

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

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

Query:.

∏ 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. I know it sounds confusing but once we take an
example of this, you will be able to understand this.

Syntax of Cartesian product (X)


R1 X R2
Cartesian product (X) Example

Table 1: R

Col_A Col_B
----- ------
AA 100
BB 200
CC 300
Table 2: 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

RELATIONAL CALCULUS:

NOTE: STUDY FROM NOTES RELATIONAL CALCULUS GIVEN

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

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