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

Module 2 Relational Model & SQL (1)

Uploaded by

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

Module 2 Relational Model & SQL (1)

Uploaded by

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

MODULE 2

Relational Model & SQL


Contents
• Relational Model
• Structure of relational database
• Reduction of ER model into Relational schemas
• Schemas-instance distinction
• Referential algebra
• Tuple Relation Calculus
• Domain Relational Calculus
• Example Queries
• SQL
• Introduction to SQL
• Data Definition statements with constraints,insert, update and delete
• Set operations
• Aggregate functions group by and having clauses,
• Nested queries
• Views
• Complex queries
• Joins
Structure of relational database
• A relational database consists of a collection of tables, each having a
unique name.
• A row in a table represents a relationship among a set of values.

• Thus a table represents a collection of relationships.

• There is a direct correspondence between the concept of a table and


the mathematical concept of a relation. A substantial theory has been
developed for relational databases.
Relational Query Languages
• A query language is a language in which a user requests information
from the database.
• Query languages can be categorized as either procedural or
nonprocedural.
1. Procedural Query language:

• In procedural query language, user instructs the system to perform a series of operations to
produce the desired results. Here users tells what data to be retrieved from database and how to
retrieve it.

• In procedural query language, a user gives step-by-step instructions to the system on how to get the
information they want from a database.

For example – Let’s take a real world example to understand the procedural language, you are
asking your younger brother to make a cup of tea, if you are just telling him to make a tea and
not telling the process then it is a non-procedural language, however if you are telling the step
by step process like switch on the stove, boil the water, add milk etc. then it is a procedural
language.
Non-procedural query language:

• In Non-procedural query language, user instructs the system to produce the desired result

without telling the step by step process. Here users tells what data to be retrieved from database
but doesn’t tell how to retrieve it.
• In a non-procedural query language, the user only specifies what information they want from the

database, without giving explicit instructions on how to retrieve it step by step.


• It's like placing an order at a restaurant without telling the chef how to cook the meal.

• You tell the system what data you need, and it figures out the most efficient way to get it for you.

• This approach allows for more flexibility and abstraction, as users don't have to worry about the

detailed process of retrieving the data – they just focus on what results they want.
Relational Algebra, Calculus, RDBMS & SQL:
• Relational algebra and calculus are the theoretical concepts used on
relational model.

• RDBMS is a practical implementation of relational model.

• SQL is a practical implementation of relational algebra and calculus.


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.
• When I say that relational algebra is a procedural query language, it
means that it tells what data to be retrieved and how to be retrieved.
• On the other hand 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.
Types of operations in relational algebra
• Basic/Fundamental • Derived
Operations: Operations:
• 1. Select (σ) • 1. Natural Join (⋈)
2. Project (∏) 2. Left, Right, Full
3. Union (∪)
4. Set Difference (-)
outer join (⟕, ⟖, ⟗)
5. Cartesian product (X) 3. Intersection (∩)
6. Rename (ρ) 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.
• If you understand little bit of SQL then you can think of it as a 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 Output:
• C10111 Raghu Agra
• C10115 Chaitanya Noida Customer_Id Customer_Name Customer_City
• C10117 Ajeet Delhi ----------- ------------- -------------
• C10118 Carl Delhi C10100 Steve Agra
C10111 Raghu Agra
• Query:

• σ Customer_City="Agra" (CUSTOMER)
Examples to solve
• Select All Rows:
• The σ symbol represents the SELECT operator, and the condition inside the brackets specifies the rows to be selected.
• σ(True)(Employees)
• This selects all rows from the "Employees" relation because the condition is always true.

• Select Rows with a Condition:


• This selects rows where the "Department" is 'HR'.
• σ(Department='HR')(Employees)

• Select with Multiple Conditions:


• This selects rows where the "Department" is 'HR' and the "Salary" is greater than 50000.
• σ(Department='HR' AND Salary > 50000)(Employees)

• Selecting Specific Columns:


• In relational algebra, the projection (π) symbol is used to specify the columns. So, if you want to select only the "FirstName" and
"LastName" columns where the "Department" is 'IT', it would look like this:

• π(FirstName, LastName)(σ(Department='IT')(Employees))
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
Examples to solve
• Consider the following table
1. projection of CustomerName
and status from customer table.
2. Projection of id and name
From student table
Output
Union Operator (∪)

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

• Lets discuss union operator a bit more. 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
Query:

∏ Student_Name (COURSE) ∪ ∏ Student_Name (STUDENT)

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.
Examples to solve
Intersection Operator (∩)
• ntersection 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.
• 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. 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
Query:
Lets find the cartesian product of table R and S.
RXS

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.
Query:

ρ(CUST_NAMES, ∏(Customer_Name)(CUSTOMER))
Extended Operators
• Derived from basic operators.

Extended
Operators

Join Intersection Divide


Join
• What is join?
• Join is a binary operation which allows you to combine join product and selection in one
single statement.
• Why joins are needed?
• The goal of creating a join condition is that it helps you to combine the data from multiple
join tables.
Types of joins

Types of Joins

Inner Join Outer Join


Natural Left Outer Right Full Outer
EQUI join
join Join Outer Join Join
Inner Joins
• widely used join operation.
• considered as a default join-type.
• The inner JOIN is used to return rows from both tables which satisfy the given
condition.
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 this type of 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.
Equi Join

• EQUI JOIN performs a JOIN against equality or matching column(s) values of


the associated tables. An equal sign (=) is used as comparison operator in the
where clause to refer equality.

• You may also perform EQUI JOIN by using JOIN keyword followed by ON
keyword and then specifying names of the columns along with their associated
tables to check equality.
Syntax:

• SELECT column_list
• FROM table1, table2....
• WHERE table1.column_name =
• table2.column_name;
• or

• SELECT *
• FROM table1
• JOIN table2
• [ON (join_condition)]
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
Right Outer Join
Intersection Join
• SQL | INTERSECT Clause

• The INTERSECT clause in SQL is used to combine two SELECT statements


but the dataset returned by the INTERSECT statement will be the intersection
of the data-sets of the two SELECT statements. In simple words, the
INTERSECT statement will return only those rows which will be common to
both of the SELECT statements.
• Syntax:

• SELECT column1 , column2 ....


• FROM table_names
• WHERE condition

• INTERSECT

• SELECT column1 , column2 ....


• FROM table_names
• WHERE condition
Key points to remember
• 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 subtypes: 1)) Natural join 2) EQUI join
• Theta Join allows you to merge two tables based on the condition represented
• 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.
Relational Calculus
• Relational calculus is a non-procedural query language that tells the system what data to be retrieved but doesn’t
tell how to retrieve it:
• This means that in relational calculus, you specify what information you want from the database, but you don't
need to specify the step-by-step procedure or method to obtain that information. It focuses on the "what" rather
than the "how."
• It uses mathematical predicate calculus instead of algebra:
• Instead of using mathematical operations like addition or subtraction (which is what algebra does), relational
calculus uses a different branch of mathematics called predicate calculus. Predicate calculus helps in expressing
conditions or criteria to select the desired data.
• It provides the description about the query to get the result whereas relational algebra gives the method to get the
result:
• In relational calculus, you describe the conditions or criteria for the data you want (like specifying
characteristics or properties), whereas relational algebra provides a set of operations and rules to actually
perform the steps needed to retrieve the data.
• It informs the system what to do with the relation, but does not inform how to perform it:
• Relational calculus gives instructions on what information you're interested in (what to do with the relation), but
it doesn't specify the detailed steps or procedures on how to achieve that. The "how" is left to the database
management system to figure out based on the provided criteria.
1. Tuple Relational Calculus (TRC)
• Tuple relational calculus is used for selecting those tuples that satisfy the
given condition.
• The resulting relation can have one or more tuples. It is denoted as below:
• {t | P (t)} or {t | condition (t)} -- this is also known as expression of
relational calculus
• Where t is the resulting tuples, P(t) is the condition used to fetch t.
Examples
Imagine you have a database table named "Employees" with columns like "Name," "Department," and "Salary." You want to
find all employees who work in the "IT" department. Here's how you might express this in Tuple Relational Calculus:
In Tuple Relational Calculus:
You would write a statement like this:
{EmployeeName ∣ Employees(EmployeeName, Department, Salary) ∧Department="IT"}
{EmployeeName ∣ Employees(EmployeeName, Department, Salary) ∧Department="IT"}
Breaking it down:
•{EmployeeName ∣ ...}{EmployeeName ∣ ...}: This part says we want a set of EmployeeNames that meet certain conditions.
•Employees(EmployeeName, Department, Salary)Employees(EmployeeName, Department, Salary): This part specifies that
we are working with the "Employees" table and listing its columns.
•∧∧: This is the logical AND, indicating that both conditions on the left and right must be true.
•Department="IT"Department="IT": This condition specifies that we are interested in employees where the "Department" is
equal to "IT."
Queries-1: Find the loan number, branch, amount of loans of greater than or equal to
10000 amount.

Queries-2: Find the loan number for each loan of an amount greater or equal to 10000.

Queries-3: Find the names of all customers who have a loan and an account at the
bank.
Queries-4: Find the names of all customers having a loan at the “ABC” branch.
2. Domain Relational Calculus (DRC)
• Domain Relational Calculus is a non-procedural query language equivalent in
power to Tuple Relational Calculus. Domain Relational Calculus provides only
the description of the query but it does not provide the methods to solve it. In
Domain Relational Calculus, a query is expressed as,

• { < x1, x2, x3, ..., xn > | P (x1, x2, x3, ..., xn ) }
• where, < x1, x2, x3, …, xn > represents resulting domains variables and P (x1,
x2, x3, …, xn ) represents the condition or formula equivalent to the Predicate
calculus.
• the basic components and concepts of Domain Relational Calculus:

• Domains: In DRC, a domain is a set of possible values that an attribute in a relation can take. For example, the

domain of a "Name" attribute might be the set of all possible names.


• Variables: Variables are used to represent elements from domains. In DRC, variables are typically denoted by

single letters. For instance, "x" might represent a name from the "Name" domain.
• Predicates: Predicates are conditions that must be satisfied for a tuple to be included in the result. These

conditions are expressed using logical operators such as AND, OR, and NOT. For example, you might have a
predicate like "x = 'John'" to retrieve tuples where the name is 'John'.
• Quantifiers: DRC uses quantifiers to express the scope of variables. There are two types of quantifiers:

• Existential Quantifier (∃): Represents "there exists." For example, ∃x means "there exists an x."

• Universal Quantifier (∀): Represents "for all." For example, ∀x means "for all x."
• Suppose you have a relation called "Students" with attributes "Name" and "Age." You
want to find the names of all students who are 20 years old. In DRC, you could
express this as:

• Domain Relational Calculus provides a way to describe the desired information


from a database by specifying conditions on the attributes using variables,
domains, and logical operators.
• Query-1: Find the loan number for each loan of an amount greater or equal to
150.
• Query-2: Find the names of all customers having a loan at the “Main” branch
and find the loan amount .
Introduction to SQL
• Structured Query Language or SQL
• a standard Database language which is used to create, maintain and retrieve
the data from relational databases like MySQL, Oracle, SQL Server, PostGre,
etc.
• The recent ISO standard version of SQL is SQL:2019.
• As the name suggests, it is used when we have structured data (in the form of
tables).
• All databases that are not relational (or do not use fixed structure tables to
store data) and therefore do not use SQL, are called NoSQL databases.
Examples of NoSQL are MongoDB, DynamoDB, Cassandra, etc
Following are some interesting facts about SQL.

• SQL is case insensitive. But it is a recommended practice to use keywords


(like SELECT, UPDATE, CREATE, etc) in capital letters and use user
defined things (liked table name, column name, etc) in small letters.
• We can write comments in SQL using “–” (double hyphen) at the beginning
of any line.
• SQL is the programming language for relational databases (explained
below) like MySQL, Oracle, Sybase, SQL Server, Postgre, etc. Other non-
relational databases (also called NoSQL) databases like MongoDB,
DynamoDB, etc do not use SQL
• Although there is an ISO standard for SQL, most of the implementations
slightly vary in syntax. So we may encounter queries that work in SQL
Server but do not work in MySQL.
These are some important terminologies that are used in terms of
relation.
• Suppose we have a relation (table) called "Students" with the following attributes: ROLL_NO, NAME, ADDRESS, PHONE, and AGE.
• Attribute:
• Definition: Attributes are the properties that define a relation.
• Example: In our "Students" relation, ROLL_NO, NAME, ADDRESS, PHONE, and AGE are attributes.
• Tuple:
• Definition: Each row in the relation is known as a tuple.
• Example: If we have a row that looks like (1, "John", "New York", 1234567890, 20), this is a tuple representing a student with a roll number of
1, name John, living in New York, having the phone number 1234567890, and aged 20.
• Degree:
• Definition: The number of attributes in the relation is known as the degree of the relation.
• Example: If our "Students" relation has attributes ROLL_NO, NAME, ADDRESS, PHONE, and AGE, then the degree of this relation is 5.
• Cardinality:
• Definition: The number of tuples in a relation is known as the cardinality.
• Example: If our "Students" relation has four rows (tuples), then the cardinality of this relation is 4.
• Column:
• Definition: A column represents the set of values for a particular attribute.
• Example: If you extract the column for the attribute ROLL_NO from the "Students" relation, you'll get a list of all roll numbers.
ROLL_NO NAME ADDRESS PHONE AGE
1 John New York 1234567890 20
2 Jane Chicago 9876543210 22
3 Bob LA 5555555555 21
4 Alice Boston 1111111111 19

•Attribute: ROLL_NO, NAME, ADDRESS, PHONE, AGE


•Tuple: (1, "John", "New York", 1234567890, 20)
•Degree: 5 (number of attributes)
•Cardinality: 4 (number of tuples)
•Column: If you extract the column for ROLL_NO, you get [1, 2, 3, 4].
DDL: CREATE
• There are two CREATE statements available in SQL:
• CREATE DATABASE
• CREATE TABLE
CREATE DATABASE

• A Database is defined as a structured set of data. So, in SQL the very first step to
store the data in a well structured manner is to create a database. The CREATE
DATABASE statement is used to create a new database in SQL.
• Syntax:

• CREATE DATABASE database_name;

• database_name: name of the database.


• Example Query:
• This query will create a new database in SQL and name the database as
my_database.

• CREATE DATABASE my_database;


CREATE TABLE
• We have learned above about creating databases. Now to store the data we
need a table to do that. The CREATE TABLE statement is used to create a
table in SQL. We know that a table comprises of rows and columns. So while
creating tables we have to provide all the information to SQL about the names
of the columns, type of data to be stored in columns, size of the data etc. Let
us now dive into details on how to use CREATE TABLE statement to create
tables in SQL.
• Syntax:

• CREATE TABLE table_name


• (
• column1 data_type(size),
• column2 data_type(size),
• column3 data_type(size),
• ....
• );

• table_name: name of the table.


• column1 name of the first column.
• data_type: Type of data we want to store in the particular column.
• For example,int for integer data.
• size: Size of the data we can store in a particular column. For example if for
• a column we specify the data_type as int and size as 10 then this column can store an
integer
• Example Query:
• This query will create a table named Students with three columns,
ROLL_NO, NAME and SUBJECT.

• CREATE TABLE Students


•(
• ROLL_NO int(3),
• NAME varchar(20),
• SUBJECT varchar(20),
• );
• This query will create a table named Students. The ROLL_NO field is of
type int and can store an integer number of size 3. The next two columns
NAME and SUBJECT are of type varchar and can store characters and the
size 20 specifies that these two fields can hold maximum of 20 characters.
• SQL> CREATE TABLE CUSTOMERS(
• ID INT NOT NULL,
• NAME VARCHAR (20) NOT NULL,
• AGE INT NOT NULL,
• ADDRESS CHAR (25) ,
• SALARY DECIMAL (18, 2),
• PRIMARY KEY (ID)
• );
• CREATE TABLE Employee_Info
•(
• EmployeeID int,
• EmployeeName varchar(255),
• Emergency ContactName varchar(255),
• PhoneNumber int,
• Address varchar(255),
• City varchar(255),
• Country varchar(255)
• );
SQL ALTER TABLE Statement
• he ALTER TABLE statement is used to add, delete, or modify columns in an
existing table.

• The ALTER TABLE statement is also used to add and drop various constraints
on an existing table.
ALTER TABLE - ADD Column
• To add a column in a table, use the following syntax:

• ALTER TABLE table_name


• ADD column_name datatype;
• The following SQL adds an "Email" column to the "Customers" table:

• Example
• ALTER TABLE Customers ADD Email varchar(255);
ALTER TABLE - DROP COLUMN
• To delete a column in a table, use the following syntax (notice that
some database systems don't allow deleting a column):
• ALTER TABLE table_name DROP COLUMN column_name;
• The following SQL deletes the "Email" column from the "Customers"
table:
• Example
• ALTER TABLE Customers DROP COLUMN Email;
ALTER TABLE - ALTER/MODIFY COLUMN

• To change the data type of a column in a table, use the following syntax:
• Oracle 10G and later:
• ALTER TABLE table_name MODIFY column_name datatype;
SQL RENAME TABLE

• SQL RENAME TABLE syntax is used to change the name of a table.


Sometimes, we choose non-meaningful name for the table. So it is
required to be changed.
• syntax to rename a table from the database.
ALTER TABLE table_name RENAME TO new_table_name;
• RENAME old_table _name To new_table_name;
• You should use any one of the following syntax to RENAME the table
name:
ALTER TABLE STUDENTS RENAME TO ARTISTS;
• Or
RENAME STUDENTS TO ARTISTS;
After that the table "students" will be changed into table name "ar
tists"
SQL TRUNCATE TABLE

• A truncate SQL statement is used to remove all rows (complete data)


from a table. It is similar to the DELETE statement with no WHERE
clause.
• TRUNCATE TABLE Vs DELETE TABLE
• Truncate table is faster and uses lesser resources than DELETE
TABLE command.
• TRUNCATE TABLE Vs DROP TABLE
• Drop table command can also be used to delete complete table but
it deletes table structure too. TRUNCATE TABLE doesn't delete the
structure of the table.
• the syntax to truncate the table from the database.
1.TRUNCATE TABLE table_name;
• For example, you can write following command to truncate the data
of employee table
1.TRUNCATE TABLE Employee;
• Note: The rollback process is not possible after truncate table
statement. Once you truncate a table you cannot use a flashback
table statement to retrieve the content of the table.
SQL DROP TABLE

• A SQL DROP TABLE statement is used to delete a table definition and all data
from a table.
• This is very important to know that once a table is deleted all the information
available in the table is lost forever, so we have to be very careful when using
this command.
• Let's see the syntax to drop the table from the database.
• DROP TABLE "table_name";
SQL DELETE TABLE

• The DELETE statement is used to delete rows from a table. If you want to
remove a specific row from a table you should use WHERE condition.
• DELETE FROM table_name [WHERE condition];
• But if you do not specify the WHERE condition it will remove all the rows from
the table.
• DELETE FROM table_name;
• There are some more terms similar to DELETE statement like as DROP
statement and TRUNCATE statement but they are not exactly same there are
some differences between them.
Difference between DELETE and TRUNCATE statements

• There is a slight difference b/w delete and truncate statement.


The DELETE statement only deletes the rows from the table based
on the condition defined by WHERE clause or delete all the rows
from the table when condition is not specified.
• But it does not free the space containing by the table.
• The TRUNCATE statement: it is used to delete all the rows from
the table and free the containing space.
Difference b/w DROP and TRUNCATE statements

• When you use the drop statement it deletes the table's row together
with the table's definition so all the relationships of that table with
other tables will no longer be valid.
• When you drop a table:
• Table structure will be dropped
• Relationship will be dropped
• Integrity constraints will be dropped
• Access privileges will also be dropped
• On the other hand when we TRUNCATE a table, the table structure
remains the same, so you will not face any of the above problems.
DML Data Manipulation Language
• DML:
• SELECT
• INSERT
• UPDATE
• DELETE
• MERGE
• CALL
• EXPLAIN PLAN
• LOCK TABLE
SQL Select

• SELECT Statement • SQL SELECT RANDOM


• SQL SELECT UNIQUE • SQL SELECT AS
• SQL SELECT DISTINCT
• SQL SELECT IN
• SQL SELECT COUNT
• SQL SELECT Multiple
• SQL SELECT TOP
• SQL SELECT FIRST • SQL SELECT DATE
• SQL SELECT LAST • SQL SELECT SUM
• SQL SELECT NULL
SQL SELECT

• The most commonly used SQL command is SELECT statement. It is


used to query the database and retrieve selected data that follow
the conditions we want.
• In simple words, we can say that the select statement used to query
or retrieve data from a table in the database.
• the syntax of select statement.
SELECT expressions
FROM tables
WHERE conditions;
Optional clauses in SELECT statement

• There are some optional clauses in SELECT statement:


• [WHERE Clause] : It specifies which rows to retrieve.
• [GROUP BY Clause] : Groups rows that share a property so that the
aggregate function can be applied to each group.
• [HAVING Clause] : It selects among the groups defined by the
GROUP BY clause.
• [ORDER BY Clause] : It specifies an order in which to return the
rows.
Optional clauses in SELECT statement
• A WHERE clause in SQL is a data manipulation language statement.
• WHERE clauses are not mandatory clauses of SQL DML statements. But it
can be used to limit the number of rows affected by a SQL DML statement
or returned by a query.
• Actually. it filters the records. It returns only those queries which fulfill the
specific conditions.

= equal
WHERE clause is used in SELECT, UPDATE, DELETE
statement etc. > greater than
Let's see the syntax for sql where: < less than
1.SELECT column1, column 2, ... column n
>= greater than or equal
2.FROM table_name
3.WHERE [conditions] <= less than or equal
WHERE clause uses some conditional selection <> not equal to
SQL SELECT UNIQUE
• Actually, there is no difference between DISTINCT and UNIQUE.
• SELECT UNIQUE is an old syntax which was used in oracle
description but later ANSI standard defines DISTINCT as the official
keyword.
• After that oracle also added DISTINCT but did not withdraw the
service of UNIQUE keyword for the sake of backward compatibility.
• In simple words, we can say that SELECT UNIQUE statement is used
to retrieve a unique or distinct element from the table.
• the syntax of select unique statement.
1.SELECT UNIQUE column_name FROM table_name;
• SQL SELECT DISTINCT statement can also be used for the same
cause.
SQL SELECT DISTINCT

• The SQL DISTINCT command is used with SELECT key word to


retrieve only distinct or unique data.
• In a table, there may be a chance to exist a duplicate value and
sometimes we want to retrieve only unique values. In such
scenarios, SQL SELECT DISTINCT statement is used.
• SELECT DISTINCT column_name ,column_name FROM table_name;
SQL SELECT COUNT

• The SQL COUNT() function is used to return the number of rows in


a query.
• The COUNT() function is used with SQL SELECT statement and it is
very useful to count the number of rows in a table having enormous
data.
• For example: If you have a record of the voters in selected area
and want to count the number of voters then it is very difficult to do
it manually but you can do it easily by using the SQL SELECT COUNT
query.
• the syntax of SQL COUNT statement.
1.SELECT COUNT (expression) FROM tables WHERE conditions;
• Let's see the examples of sql select count function.
• SQL SELECT COUNT(column_name)
1.SELECT COUNT(name) FROM employee_table;
• It will return the total number of names of employee_table. But null
fields will not be counted.
• SQL SELECT COUNT(*)
1.SELECT COUNT(*) FROM employee_table;
• The "select count(*) from table" is used to return the number of
records in table.
• SQL SELECT COUNT(DISTINCT column_name)
1.SELECT COUNT(DISTINCT name) FROM employee_table;
• It will return the total distinct names of employee_table.
The SQL SELECT DISTINCT Statement

• The SELECT DISTINCT statement is used to return only distinct (different)


values.
• Inside a table, a column often contains many duplicate values; and sometimes
you only want to list the different (distinct) values.
• SELECT DISTINCT Syntax
• SELECT DISTINCT column1, column2, ... FROM table_name;
SQL SELECT FIRST

• The SQL first() function is used to return the first value of the
selected column.
• Let's see the syntax of sql select first() function:
1.SELECT FIRST(column_name) FROM table_name;
• Here a point is notable that first function is only supported by MS
Access.
SQL SELECT LAST

• The last() function is used to return the last value of the specified
column.
• Syntax for SQL SELECT LAST() FUNCTION:
1.SELECT LAST (column_name) FROM table_name;
• You should note that the last() function is only supported in MS
Access. But there are ways to get the last record in MySql, SQL
Server, Oracle etc. databases.
SQL INSERT INTO Statement

• The SQL INSERT INTO Statement


• The INSERT INTO statement is used to insert new records in a table.
• INSERT INTO Syntax
• It is possible to write the INSERT INTO statement in two ways.
• The first way specifies both the column names and the values to be inserted:
• INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
SQL NULL Values

• What is a NULL Value?


• A field with a NULL value is a field with no value.
• If a field in a table is optional, it is possible to insert a new record or update a
record without adding a value to this field. Then, the field will be saved with a
NULL value.
• Note: A NULL value is different from a zero value or a field that contains
spaces. A field with a NULL value is one that has been left blank during record
creation!
How to Test for NULL Values?

• It is not possible to test for NULL values with comparison operators, such as =,
<, or <>.
• We will have to use the IS NULL and IS NOT NULL operators instead.
• IS NULL Syntax
• SELECT column_names
FROM table_name
WHERE column_name IS NULL;
• IS NOT NULL Syntax
• SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;
SQL UPDATE Statement

• The SQL UPDATE Statement


• The UPDATE statement is used to modify the existing records in a table.
• UPDATE Syntax
• UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
• Note: Be careful when updating records in a table! Notice the WHERE clause
in the UPDATE statement. The WHERE clause specifies which record(s) that
should be updated. If you omit the WHERE clause, all records in the table will
be updated!
SQL DELETE Statement

• The SQL DELETE Statement


• The DELETE statement is used to delete existing records in a table.
• DELETE Syntax
• DELETE FROM table_name WHERE condition;
• Note: Be careful when deleting records in a table! Notice the WHERE clause
in the DELETE statement. The WHERE clause specifies which record(s)
should be deleted. If you omit the WHERE clause, all records in the table will
be deleted!
MERGE Statement in SQL

• As MERGE statement in SQL, is the combination of three INSERT, DELETE


and UPDATE statements. So if there is a Source table and a Target
table that are to be merged, then with the help of MERGE statement, all the
three operations (INSERT, UPDATE, DELETE) can be performed at once.
Example:The task is to update the details of the products in the
PRODUCT_LIST as per the UPDATED_LIST.
• Suppose there are two tables:
PRODUCT_LIST which is the table that contains the current details about
the products available with fields P_ID, P_NAME, and P_PRICE
corresponding to the ID, name and price of each product.
• UPDATED_LIST which is the table that contains the new details about the
products available with fields P_ID, P_NAME, and P_PRICE corresponding
to the ID, name and price of each product.
• Solution
• Now in order to explain this example better, let’s split the example into
steps.
• Step 1: Recognise the TARGET and the SOURCE table
• So in this example, since it is asked to update the products in the
PRODUCT_LIST as per the UPDATED_LIST, hence the PRODUCT_LIST
will act as the TARGET and UPDATED_LIST will act as the SOURCE
table.
Step 2: Recognize the operations to be performed
Step 3: Write the SQL Query
• /* Selecting the Target and the Source */ /* 2. Performing the INSERT operation */
• MERGE PRODUCT_LIST AS TARGET
• USING UPDATE_LIST AS SOURCE /* When no records are matched with TARGET
table
• /* 1. Performing the UPDATE operation */ Then insert the records in the target table */
• /* If the P_ID is same, check for change in WHEN NOT MATCHED BY TARGET
P_NAME or P_PRICE */
THEN INSERT (P_ID, P_NAME, P_PRICE)
• ON (TARGET.P_ID = SOURCE.P_ID)
VALUES (SOURCE.P_ID, SOURCE.P_NAME,
• WHEN MATCHED
SOURCE.P_PRICE)
• AND TARGET.P_NAME <>
SOURCE.P_NAME
• OR TARGET.P_PRICE <> SOURCE.P_PRICE /* 3. Performing the DELETE operation */

• /* Update the records in TARGET */ /* When no records are matched with SOURCE
• THEN UPDATE table
• SET TARGET.P_NAME = Then delete the records from the target table */
SOURCE.P_NAME, WHEN NOT MATCHED BY SOURCE


TARGET.P_PRICE = SOURCE.P_PRICE THEN DELETE

/* END OF MERGE */
• MERGE - UPSERT operation (insert or update)
• CALL - call a PL/SQL or Java subprogram
• EXPLAIN PLAN - interpretation of the data access path
• LOCK TABLE - concurrency Control
(DCL) DATA CONTROL LANGUAGE
• DCL is short name of Data Control Language which includes commands such
as GRANT and mostly concerned with rights, permissions and other controls
of the database system.

• GRANT - allow users access privileges to the database


• REVOKE - withdraw users access privileges given by using the GRANT
command

• Database Administrator's or owner’s of the database object can


provide/remove privileges on a database object.
SQL Grant Command

• • SQL Grant command is used to provide access or privileges on the database


objects to the users.
• • The syntax for the GRANT command is:
• GRANT privilege_name ON object_name TO {user_name | PUBLIC |
role_name} [with GRANT option];
• Here, privilege_name: is the access right or privilege granted to the user.
• object_name: is the name of the database object like table, view etc.,.
• user_name: is the name of the user to whom an access right is being granted.
• Public is used to grant rights to all the users.
• With Grant option: allows users to grant access rights to other users.
SQL Revoke Command
• The revoke command removes user access rights or privileges to the
database objects.
• The syntax for the REVOKE command is:
• REVOKE privilege_name ON object_name FROM {User_name | PUBLIC |
Role_name}
• For Example:
• (a) GRANT SELECT ON employee TO user1
• This command grants a SELECT permission on employee table to user1.
• (b) REVOKE SELECT ON employee FROM user1
• This command will revoke a SELECT privilege on employee table from user1.
Transaction Control Language
• TCL is short name of Transaction Control Language which deals with a
transaction within a database.

• COMMIT - commits a Transaction


• ROLLBACK - rollback a transaction in case of any error occurs
• SAVEPOINT - to rollback the transaction making points within groups
• SET TRANSACTION - specify characteristics of the transaction

• Oracle Syntax:
• CREATE USER username IDENTIFIED BY password
COMMIT command

• COMMIT command is used to permanently save any transaction into the


database.
• When we use any DML command like INSERT, UPDATE or DELETE, the
changes made by these commands are not permanent, until the current
session is closed, the changes made by these commands can be rolled back.
• To avoid that, we use the COMMIT command to mark the changes as
permanent.
• Following is commit command's syntax,
• COMMIT;
ROLLBACK command

• This command restores the database to last commited state. It is also used
with SAVEPOINT command to jump to a savepoint in an ongoing transaction.
• If we have used the UPDATE command to make some changes into the
database, and realise that those changes were not required, then we can use
the ROLLBACK command to rollback those changes, if they were not
commited using the COMMIT command.
• Following is rollback command's syntax,
• ROLLBACK TO savepoint_name;
SAVEPOINT command

• SAVEPOINT command is used to temporarily save a transaction so that you


can rollback to that point whenever required.
• Following is savepoint command's syntax,
• SAVEPOINT savepoint_name;
• In short, using this command we can name the different states of our data in
any table and then rollback to that state using the ROLLBACK command
whenever required.
SQL Constraints
• SQL constraints are used to specify rules for the data in a table.
• Constraints are used to limit the type of data that can go into a table. This ensures the accuracy and
reliability of the data in the table. If there is any violation between the constraint and the data action,
the action is aborted.
• Constraints can be column level or table level. Column level constraints apply to a column, and table
level constraints apply to the whole table.
• 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 - Uniquely identifies a row/record in another table
• CHECK - Ensures that all values in a column satisfies a specific condition
• DEFAULT - Sets a default value for a column when no value is specified
• INDEX - Used to create and retrieve data from the database very quickly
SQL NOT NULL Constraint
• By default, a column can hold NULL values.
• The NOT NULL constraint enforces a column to NOT accept NULL values.
• This enforces a field to always contain a value, which means that you cannot insert
a new record, or update a record without adding a value to this field.

SQL NOT NULL on CREATE TABLE


The following SQL ensures that the "ID", SQL NOT NULL on ALTER TABLE
"LastName", and "FirstName" columns will NOT To create a NOT NULL constraint on the "Age"
accept NULL values when the "Persons" table is column when the "Persons" table is already
created: created, use the following SQL:

Example ALTER TABLE Persons


CREATE TABLE Persons ( MODIFY Age int NOT NULL;
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);
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 on CREATE TABLE
• The following SQL creates a UNIQUE constraint on the "ID" column when the
"Persons" table is created:
• CREATE TABLE Persons (
• ID int NOT NULL UNIQUE,
• LastName varchar(255) NOT NULL,
• FirstName varchar(255),
• Age int
• );
• To name a UNIQUE constraint, and to define a UNIQUE constraint on multiple
columns, use the following SQL syntax:
• CREATE TABLE Persons (
• ID int NOT NULL,
• LastName varchar(255) NOT NULL,
• FirstName varchar(255),
• Age int,
• CONSTRAINT UC_Person UNIQUE (ID,LastName)
• );
SQL UNIQUE Constraint on ALTER TABLE

• To create a UNIQUE constraint on the "ID" column when the table is already
created, use the following SQL:
• ALTER TABLE Persons ADD UNIQUE (ID);
• To name a UNIQUE constraint, and to define a UNIQUE constraint on multiple
columns, use the following SQL syntax:
• ALTER TABLE Persons
ADD CONSTRAINT UC_Person UNIQUE (ID,LastName);
DROP a UNIQUE Constraint

• To drop a UNIQUE constraint, use the following SQL:


• ALTER TABLE Persons DROP CONSTRAINT UC_Person;
SQL 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).
SQL PRIMARY KEY on CREATE TABLE

• The following SQL creates a PRIMARY KEY on the "ID" column when the
"Persons" table is created:
• CREATE TABLE Persons (
ID int 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 int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
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).
SQL PRIMARY KEY on ALTER TABLE

• To create a PRIMARY KEY constraint on the "ID" column when the table is already
created, use the following SQL:

• ALTER TABLE Persons ADD PRIMARY KEY (ID);

• To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY
constraint on multiple columns, use the following SQL syntax:

• ALTER TABLE Persons ADD CONSTRAINT PK_Person PRIMARY KEY (ID,


LastName);

• Note: If you use the ALTER TABLE statement to add a primary key, the primary key
column(s) must already have been declared to not contain NULL values (when the table
was first created).
DROP a PRIMARY KEY Constraint

• To drop a PRIMARY KEY constraint, use the following SQL:

• ALTER TABLE Persons DROP CONSTRAINT PK_Person;


SQL FOREIGN KEY Constraint
• A FOREIGN KEY is a key used to link two tables together.

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

• The table containing the foreign key is called the child table, and the table
containing the candidate key is called the referenced or parent table.
• Look at the following two tables:

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 is used to prevent actions


that would destroy links between tables.

The FOREIGN KEY constraint also prevents invalid data


from being inserted into the foreign key column, because it
has to be one of the values contained in the table it points
to.
SQL FOREIGN KEY on CREATE TABLE

• The following SQL creates a FOREIGN KEY on the "PersonID" column when
the "Orders" table is created:
• CREATE TABLE Orders (
OrderID int NOT NULL PRIMARY KEY,
OrderNumber int NOT NULL,
PersonID int 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 int,
• PRIMARY KEY (OrderID),
• CONSTRAINT FK_PersonOrder FOREIGN KEY (PersonID)
• REFERENCES Persons(PersonID)
• );
SQL FOREIGN KEY on ALTER TABLE

• To create a FOREIGN KEY constraint on the "PersonID" column when the


"Orders" table is already created, use the following SQL:

• ALTER TABLE Orders ADD FOREIGN KEY (PersonID) 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:

• ALTER TABLE Orders ADD CONSTRAINT FK_PersonOrder FOREIGN KEY


(PersonID) REFERENCES Persons(PersonID);
DROP a FOREIGN KEY Constraint
• To drop a FOREIGN KEY constraint, use the following SQL:
• ALTER TABLE Orders DROP CONSTRAINT FK_PersonOrder;
SQL AUTO INCREMENT Field
• Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table.

• Often this is the primary key field that we would like to be created automatically every time a new record is
inserted.
• You will have to create an auto-increment field with the sequence object (this object generates a number
sequence).

• Use the following CREATE SEQUENCE syntax:

• CREATE SEQUENCE seq_person


• MINVALUE 1
• START WITH 1
• INCREMENT BY 1
• CACHE 10;
• The code above creates a sequence object called seq_person, that starts with 1 and will increment by 1. It will
also cache up to 10 values for performance. The cache option specifies how many sequence values will be stored
in memory for faster access.
SQL Dates
• SQL Date Data Types
• DATE - format YYYY-MM-DD
• DATETIME - format: YYYY-MM-DD HH:MI:SS
• SMALLDATETIME - format: YYYY-MM-DD HH:MI:SS
• TIMESTAMP - format: a unique number
• Note: The date types are chosen for a column when you create a new table in
your database!
SYSDATE
• Purpose
• SYSDATE returns the current date and time set for the operating system on which the database resides.
The datatype of the returned value is DATE, and the format returned depends on the value of the
NLS_DATE_FORMAT initialization parameter. The function requires no arguments. In distributed SQL
statements, this function returns the date and time set for the operating system of your local database. You
cannot use this function in the condition of a CHECK constraint.

• Examples
• The following example returns the current operating system date and time:

• SELECT TO_CHAR
• (SYSDATE, 'MM-DD-YYYY HH24:MI:SS') "NOW"
• FROM DUAL;

• NOW
• -------------------
• 04-13-2001 09:45:51
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.

• 4 different types of SET operations, along with example:

• UNION
• UNION ALL
• INTERSECT
• MINUS
UNION Operation

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


However 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.
UNION ALL
This operation is similar to Union. But it also shows the duplicate rows.
INTERSECT

• Intersect operation is used to combine two SELECT statements, but 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.
• NOTE: MySQL does not support INTERSECT operator.
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.
• Group By Clause
• Having Clause
• Aggregate Functions
Group By Clause
• The GROUP BY Clause is utilized in SQL with the SELECT statement to
organize similar data into groups. It combines the multiple records in single or
more columns using some functions. Generally, these functions are aggregate
functions such as min(),max(),avg(), count(), and sum() to combine into single
or multiple columns. It uses the split-apply-combine strategy for data analysis.

• In the split phase, It divides the groups with its values.


• In the apply phase, It applies the aggregate function and generates a single
value.
• In the combiner phase, It combines the groups with single values into a single
value.
• Points to Remember:

• GROUP BY Clause is utilized with the SELECT statement.


• GROUP BY aggregates the results on the basis of selected column: COUNT,
MAX, MIN, SUM, AVG, etc.
• GROUP BY returns only one result per group of data.
• GROUP BY Clause always follows the WHERE Clause.
• GROUP BY Clause always precedes the ORDER BY Clause
Having Clause
• HAVING Clause utilized in SQL as a conditional Clause with GROUP BY
Clause. This conditional clause returns rows where aggregate function results
matched with given conditions only. It added in the SQL because WHERE
Clause cannot be combined with aggregate results, so it has a different
purpose. The primary purpose of the WHERE Clause is to deal with non-
aggregated or individual records.

• HAVING Clause always utilized in combination with GROUP BY Clause.


• HAVING Clause restricts the data on the group records rather than individual
records.
• WHERE and HAVING can be used in a single query.
Aggregate Functions
• Aggregate functions used to combine the result of a group into a single such
as COUNT, MAX, MIN, AVG, SUM, STDDEV, and VARIANCE. These
functions also known as multiple-row functions.

• SUM(): Returns the sum or total of each group.


• COUNT(): Returns the number of rows of each group.
• AVG(): Returns the average and mean of each group.
• MIN(): Returns the minimum value of each group.
• MAX(): Returns the minimum value of each group.
Compare Having and Where Clause in SQL
Nested Queries in SQL
• In nested queries, a query is written inside a query. The result
of inner query is used in execution of outer query. We will use
STUDENT, COURSE, STUDENT_COURSE tables for
understanding nested queries.
There are mainly two types of nested queries:

• Independent Nested Queries: In independent nested queries, query execution


starts from innermost query to outermost queries. The execution of inner query
is independent of outer query, but the result of inner query is used in execution
of outer query. Various operators like IN, NOT IN, ANY, ALL etc are used in
writing independent nested queries.
• IN: If we want to find out S_ID who are enrolled in C_NAME ‘DSA’ or ‘DBMS’, we can write it with
the help of independent nested query and IN operator. From COURSE table, we can find out C_ID
for C_NAME ‘DSA’ or DBMS’ and we can use these C_IDs for finding S_IDs from
STUDENT_COURSE TABLE.

• STEP 1: Finding C_ID for C_NAME =’DSA’ or ‘DBMS’

• Select C_ID from COURSE where C_NAME = ‘DSA’ or C_NAME = ‘DBMS’

• STEP 2: Using C_ID of step 1 for finding S_ID

• Select S_ID from STUDENT_COURSE where C_ID IN

• (SELECT C_ID from COURSE where C_NAME = ‘DSA’ or C_NAME=’DBMS’);

• The inner query will return a set with members C1 and C3 and outer query will return those S_IDs
for which C_ID is equal to any member of set (C1 and C3 in this case). So, it will return S1, S2 and
S4.
• Note: If we want to find out names of STUDENTs who have either enrolled in ‘DSA’ or ‘DBMS’, it can be done
as:

• Select S_NAME from STUDENT where S_ID IN

• (Select S_ID from STUDENT_COURSE where C_ID IN

• (SELECT C_ID from COURSE where C_NAME=’DSA’ or C_NAME=’DBMS’));

• NOT IN: If we want to find out S_IDs of STUDENTs who have neither enrolled in ‘DSA’ nor in ‘DBMS’, it can
be done as:

• Select S_ID from STUDENT where S_ID NOT IN

• (Select S_ID from STUDENT_COURSE where C_ID IN

• (SELECT C_ID from COURSE where C_NAME=’DSA’ or C_NAME=’DBMS’));


• The innermost query will return a set with members C1 and C3. Second inner query will return those S_IDs
for which C_ID is equal to any member of set (C1 and C3 in this case) which are S1, S2 and S4. The
outermost query will return those S_IDs where S_ID is not a member of set (S1, S2 and S4). So it will return
S3.
• Co-related Nested Queries: In co-related nested queries, the output of inner
query depends on the row which is being currently executed in outer query.
e.g.; If we want to find out S_NAME of STUDENTs who are enrolled in C_ID
‘C1’, it can be done with the help of co-related nested query as:

• Select S_NAME from STUDENT S where EXISTS ( select * from


STUDENT_COURSE SC where S.S_ID=SC.S_ID and SC.C_ID=’C1’);

• For each row of STUDENT S, it will find the rows from STUDENT_COURSE
where S.S_ID = SC.S_ID and SC.C_ID=’C1’. If for a S_ID from STUDENT S,
atleast a row exists in STUDENT_COURSE SC with C_ID=’C1’, then inner
query will return true and corresponding S_ID will be returned as output.
VIEWS
• SQL CREATE VIEW Statement
• In SQL, a view is a virtual table based on the result-set of an SQL statement.
• A view contains rows and columns, just like a real table. The fields in a view are fields
from one or more real tables in the database.
• You can add SQL functions, WHERE, and JOIN statements to a view and present the data
as if the data were coming from one single table.

• CREATE VIEW Syntax


• CREATE VIEW view_name AS
• SELECT column1, column2, ...
• FROM table_name
• WHERE condition;
• Note: A view always shows up-to-date data! The database engine recreates the data,
using the view's SQL statement, every time a user queries a view.
• SQL CREATE VIEW Examples
• The following SQL creates a view that shows all customers from Brazil:

• Example
• CREATE VIEW [Brazil Customers] AS
• SELECT CustomerName, ContactName
• FROM Customers
• WHERE Country = "Brazil";
• SQL Updating a View
• A view can be updated with the CREATE OR REPLACE VIEW command.

• SQL CREATE OR REPLACE VIEW Syntax


• CREATE OR REPLACE VIEW view_name AS
• SELECT column1, column2, ...
• FROM table_name
• WHERE condition;
• The following SQL adds the "City" column to the "Brazil Customers" view:

• Example
• CREATE OR REPLACE VIEW [Brazil Customers] AS
• SELECT CustomerName, ContactName, City
• FROM Customers
• WHERE Country = "Brazil";
• SQL Dropping a View
• A view is deleted with the DROP VIEW command.

• SQL DROP VIEW Syntax


• DROP VIEW view_name;
• The following SQL drops the "Brazil Customers" view:

• Example
• DROP VIEW [Brazil Customers];
JOINS
• A JOIN clause is used to combine rows from two or more tables, based on a
related column between them.
Different Types of SQL JOINs

• Here are the different types of the JOINs in SQL:

• (INNER) JOIN: Returns records that have matching values in both tables
• LEFT (OUTER) JOIN: Returns all records from the left table, and the matched
records from the right table
• RIGHT (OUTER) JOIN: Returns all records from the right table, and the
matched records from the left table
• FULL (OUTER) JOIN: Returns all records when there is a match in either left
or right table
SQL INNER JOIN Keyword

• The INNER JOIN keyword selects records that have matching values in both
tables.

• INNER JOIN Syntax


• SELECT column_name(s)
• FROM table1
• INNER JOIN table2
• ON table1.column_name = table2.column_name;
• SQL INNER JOIN Example
• The following SQL statement selects all orders with customer information:

• Example
• SELECT Orders.OrderID, Customers.CustomerName
• FROM Orders
• INNER JOIN Customers ON Orders.CustomerID =
Customers.CustomerID;
• Note: The INNER JOIN keyword selects all rows from both tables as long
as there is a match between the columns. If there are records in the
"Orders" table that do not have matches in "Customers", these orders will
not be shown!
• JOIN Three Tables
• The following SQL statement selects all orders with customer and shipper
information:

• Example
• SELECT Orders.OrderID, Customers.CustomerName, Shippers.ShipperName
• FROM ((Orders
• INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID)
• INNER JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID);
• SQL LEFT JOIN Keyword
• The LEFT JOIN keyword returns all records from the left table (table1), and
the matched records from the right table (table2). The result is NULL from the
right side, if there is no match.

• LEFT JOIN Syntax


• SELECT column_name(s)
• FROM table1
• LEFT JOIN table2
• ON table1.column_name = table2.column_name;
• Note: In some databases LEFT JOIN is called LEFT OUTER JOIN.
• SQL LEFT JOIN Example
• The following SQL statement will select all customers, and any orders they
might have:

• Example
• SELECT Customers.CustomerName, Orders.OrderID
• FROM Customers
• LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
• ORDER BY Customers.CustomerName;

• Note: The LEFT JOIN keyword returns all records from the left table
(Customers), even if there are no matches in the right table (Orders).
• SQL RIGHT JOIN Keyword
• The RIGHT JOIN keyword returns all records from the right table (table2),
and the matched records from the left table (table1). The result is NULL
from the left side, when there is no match.

• RIGHT JOIN Syntax


• SELECT column_name(s)
• FROM table1
• RIGHT JOIN table2
• ON table1.column_name = table2.column_name;
• Note: In some databases RIGHT JOIN is called RIGHT OUTER JOIN.
• SQL RIGHT JOIN Example
• The following SQL statement will return all employees, and any orders they
might have placed:

• Example
• SELECT Orders.OrderID, Employees.LastName, Employees.FirstName
• FROM Orders
• RIGHT JOIN Employees ON Orders.EmployeeID =
Employees.EmployeeID
• ORDER BY Orders.OrderID;
• SQL FULL OUTER JOIN Keyword
• The FULL OUTER JOIN keyword returns all records when there is a match
in left (table1) or right (table2) table records.

• Note: FULL OUTER JOIN can potentially return very large result-sets!

• Tip: FULL OUTER JOIN and FULL JOIN are the same.

• FULL OUTER JOIN Syntax


• SELECT column_name(s)
• FROM table1
• FULL OUTER JOIN table2
• ON table1.column_name = table2.column_name
• WHERE condition;
• SQL FULL OUTER JOIN Example
• The following SQL statement selects all customers, and all orders:

• SELECT Customers.CustomerName, Orders.OrderID


• FROM Customers
• FULL OUTER JOIN Orders ON
Customers.CustomerID=Orders.CustomerID
• ORDER BY Customers.CustomerName;

• Note: The FULL OUTER JOIN keyword returns all matching records from
both tables whether the other table matches or not. So, if there are rows in
"Customers" that do not have matches in "Orders", or if there are rows in
"Orders" that do not have matches in "Customers", those rows will be listed
as well.
• SQL Self JOIN
• A self JOIN is a regular join, but the table is joined with itself.

• Self JOIN Syntax


• SELECT column_name(s)
• FROM table1 T1, table1 T2
• WHERE condition;
• T1 and T2 are different table aliases for the same table.
• SQL Self JOIN Example
• The following SQL statement matches customers that are from the same
city:

• Example
• SELECT A.CustomerName AS CustomerName1, B.CustomerName AS
CustomerName2, A.City
• FROM Customers A, Customers B
• WHERE A.CustomerID <> B.CustomerID
• AND A.City = B.City
• ORDER BY A.City;
• Consider the two tables below:

• Student
• Implement a query will show the names and age of students enrolled in
different courses.

• Above query you have to perform using


• INNER JOIN
• LEFT JOIN
• RIGHT JOIN
• FULL JOIN
Inner Join

You might also like