0% found this document useful (0 votes)
14 views193 pages

Structured Query Language

Structured Query Language (SQL) is a standard programming language for managing relational databases, developed in the 1970s at IBM. It encompasses various types of commands including Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), and Transaction Control Language (TCL), each serving different functions in database management. SQL allows users to create, modify, query, and control access to data within databases.

Uploaded by

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

Structured Query Language

Structured Query Language (SQL) is a standard programming language for managing relational databases, developed in the 1970s at IBM. It encompasses various types of commands including Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), and Transaction Control Language (TCL), each serving different functions in database management. SQL allows users to create, modify, query, and control access to data within databases.

Uploaded by

jasmin67450
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Structured Query Language

Unit-3
Background
• SQL (Structured Query Language) is a standard programming language for managing and
manipulating relational databases.
• It has a long and rich history, dating back to the 1970s.
• SQL was first developed in the early 1970s at IBM by a team led by Donald D. Chamberlin
and Raymond F. Boyce.
• The original name of the language was SEQUEL, which stood for "Structured English Query
Language." SEQUEL was designed to be a simple and intuitive way to access and manipulate
data stored in IBM's System R relational database management system.
• SEQUEL was later renamed to SQL, and IBM released the first commercial implementation
of the language in 1981 as part of their System R relational database management system
(RDBMS).
• SQL quickly became the standard language for interacting with relational databases, and it
was soon adopted by other RDBMS vendors such as Oracle, Sybase, and Microsoft. The
American National Standards Institute (ANSI) and the International Standards Organization
(ISO) published official SQL standards in 1986 and 1987, respectively.
SQL Definition
• Basically, SQL stands for Structured Query Language which is basically
a language used by databases.
• This language allows to handle the information using tables and
shows a language to query these tables and other objects related
(views, functions, procedures, etc.).
• Most of the databases like SQL Server, Oracle, PostgreSQL, MySQL,
MariaDB handle this language (with some extensions and variations)
to handle the data.
• With SQL you can insert, delete, and update data. You can also create,
delete, or alter database objects.
Types of SQL
Here are five types of widely used SQL queries.
1. Data Definition Language (DDL)
2. Data Manipulation Language (DML)
3. Data Control Language(DCL)
4. Transaction Control Language(TCL)
5. Data Query Language (DQL)
What is DDL?
• DDL or Data Definition Language actually consists of the SQL
commands that can be used to define the database schema.
• It simply deals with descriptions of the database schema and is used
to create and modify the structure of database objects in the
database.
• DDL is a set of SQL commands used to create, modify, and delete
database structures but not data.
• These commands are normally not used by a general user, who
should be accessing the database via an application.
List of DDL commands:
• CREATE: This command is used to create the database or its objects
(like table, index, function, views, store procedure, and triggers).
• DROP: This command is used to delete objects from the database.
• ALTER: This is used to alter the structure of the database.
• TRUNCATE: This is used to remove all records from a table, including
all spaces allocated for the records are removed.
• COMMENT: This is used to add comments to the data dictionary.
• RENAME: This is used to rename an object existing in the database.
DQL (Data Query Language):
• DQL statements are used for performing queries on the data within
schema objects.
• The purpose of the DQL Command is to get some schema relation
based on the query passed to it.
• It includes the SELECT statement.
• This command allows getting the data out of the database to perform
operations with it.
• When a SELECT is fired against a table or tables the result is compiled
into a further temporary table, which is displayed
List of DQL
• SELECT: It is used to retrieve data from the database.
DML(Data Manipulation Language):
• The SQL commands that deals with the manipulation of data present
in the database belong to DML or Data Manipulation Language and
this includes most of the SQL statements.
• It is the component of the SQL statement that controls access to data
and to the database.
• Basically, DCL statements are grouped with DML statements.
List of DML commands:
• INSERT : It is used to insert data into a table.
• UPDATE: It is used to update existing data within a table.
• DELETE : It is used to delete records from a database table.
• LOCK: Table control concurrency.
DCL (Data Control Language):
• DCL includes commands such as GRANT and REVOKE which mainly
deal with the rights, permissions, and other controls of the database
system.
List of DCL commands:
• GRANT: This command gives users access privileges to the database.
• REVOKE: This command withdraws the user’s access privileges given
by using the GRANT command.
TCL (Transaction Control Language):
• Transactions group a set of tasks into a single execution unit.
• Each transaction begins with a specific task and ends when all the
tasks in the group successfully complete.
• If any of the tasks fail, the transaction fails.
• Therefore, a transaction has only two results: success or failure.
• The following TCL commands are used to control the execution of a
transaction:
• BEGIN: Opens a Transaction.
• COMMIT: Commits a Transaction.
• ROLLBACK: Rollbacks a transaction in case of any error occurs.
• SAVEPOINT: Sets a save point within a transaction.
• SET TRANSACTION: Specifies characteristics for the transaction.
DDL (Data Definition Language)
• Data Definition Language helps you to define the database structure
or schema. Let’s learn about DDL commands with syntax.
• Five types of DDL commands in SQL are:
CREATE
• CREATE statements is used to define the database structure schema:
• Syntax:
• CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,....]);
For example:
• Create database university;
• Create table students;
• Create view for_students;
DROP
• Drops commands remove tables and databases from RDBMS.
• Syntax
• DROP TABLE table_name ;
Example
• Drop object_type object_name;
• Drop database university;
• Drop table student;
ALTER
• Alters command allows you to alter the structure of the database.
• Syntax:
• To add a new column in the table
• ALTER TABLE table_name ADD column_name COLUMN-definition;
• To modify an existing column in the table:
• ALTER TABLE MODIFY(COLUMN DEFINITION....);
Example
• Alter table students add address varchar(50);
• Alter table students modify address varchar(30);
TRUNCATE
• This command used to delete all the rows from the table and free the
space containing the table.

• Syntax:

• TRUNCATE TABLE table_name;


Example:
• TRUNCATE table students;
Domain Types in SQL
• In SQL, the domain type is a user-defined data type that specifies a
set of values and rules that define the valid values for a column in a
database table.
• A domain can be used to define the data type for one or more
columns in a table, providing a way to enforce consistency and data
integrity across multiple tables and applications.
SQL has the following domain types:
• char(n) (or character(n)): fixed-length character string, with user-specified length.
• varchar(n) (or character varying): variable-length character string, with user-specified
maximum length.
• int or integer: an integer (length is machine-dependent).
• smallint: a small integer (length is machine-dependent).
• numeric(p, d): a fixed-point number with user-specified precision, consists of p digits (plus
a sign) and d of p digits are to the right of the decimal point. E.g., numeric(3, 1) allows
44.5 to be stored exactly but not 444.5.
• real or double precision: floating-point or double-precision floating-point numbers, with
machine-dependent precision.
• float(n): floating-point, with user-specified precision of at least n digits.
• date: a calendar date, containing four digit year, month, and day of the month.
• time: the time of the day in hours, minutes, and seconds.
DML (Data Manipulation Language)
Introduction
• Data manipulation Language(DML) deals with data manipulation, and
is used to store, modify, delete and update data in database.
• Examples of DML Commands
• Select: retrieve data from the database.
• INSERT: command to add new or new value to the database
• UPDATE: command to change or update current/existing data to a more
recent value within the database
• DELETE: command to delete or delete the values or data information of the
current table in the database
Insert 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:
• Specify both the column names and the values to be inserted:
• If you are adding values for all the columns of the table, you do not need to
specify the column names in the SQL query. However, make sure the order of
the values is in the same order as the columns in the table.
1. Specify both the column names and the
values to be inserted
• INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
2. If you are adding values for all the columns of
the table, you do not need to specify the column
names
• INSERT INTO table_name
VALUES (value1, value2, value3, ...);
INSERT INTO Example
• INSERT INTO Customers
(CustomerName, ContactName, Address, City, PostalCode, Country)
VALUES
('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway');
• INSERT INTO Customers
VALUES
('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway');
Insert Data Only in Specified Columns
• It is also possible to only insert data in specific columns.
• The following SQL statement will insert a new record, but only insert
data in the "CustomerName", "City", and "Country" columns

• INSERT INTO Customers (CustomerName, City, Country)


VALUES ('Cardinal', 'Stavanger', 'Norway');
SQL INSERT Multiple Rows
• In the previous tutorial, you have learned how to add one row at a
time to a table by using the INSERT statement.
• To add multiple rows to a table at once, you use the following form of
the INSERT statement:
• INSERT INTO table_name (column_list) VALUES (value_list_1),
(value_list_2), ... (value_list_n);
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;
• Example
• DELETE FROM Customers WHERE c_name=‘kakashi';
Delete All Records
•DELETE FROM table_name;
•The following SQL statement deletes all rows in the
"Customers" table, without deleting the table:
• DELETE FROM Customers;
Truncate Table
• The SQL TRUNCATE TABLE command is used to delete complete data
from an existing table.
• You can also use DROP TABLE command to delete complete table but
it would remove complete table structure form the database and you
would need to re-create this table once again if you wish you store
some data.
• Syntax
• TRUNCATE TABLE table_name;
Example
• TRUNCATE TABLE CUSTOMERS;
Select Statement
The SQL SELECT Statement
• The SELECT statement is used to select data from a database.
• The data returned is stored in a result table, called the result-set.
• SELECT Syntax
• SELECT column1, column2, ... FROM table_name;
• Here, column1, column2, ... are the field names of the table you want
to select data from. If you want to select all the fields available in the
table, use the following syntax:
• SELECT * FROM table_name;
• Example 1:
• SELECT * FROM Customers;
• Example 2:
• SELECT City FROM Customers;
• Example 3:
• SELECT DISTINCT Country FROM Customers;
The SQL WHERE Clause
• The WHERE clause is used to filter records.
• It is used to extract only those records that fulfill a specified
condition.
• WHERE Syntax
• SELECT column1, column2, ...
FROM table_name
WHERE condition;
• Note: The WHERE clause is not only used in SELECT statements, it is
also used in UPDATE, DELETE, etc.!
WHERE Clause Example
•SELECT * FROM Customers
WHERE Country='Mexico';
•NOTE: SQL requires single quotes around text values (most
database systems will also allow double quotes). However,
numeric fields should not be enclosed in quotes:
•Example:
• SELECT * FROM Customers WHERE CustomerID=1;
Operators in The WHERE Clause
Example
• SELECT * FROM Products WHERE Price = 18;
• SELECT * FROM Customers WHERE City = 'Berlin' ;
• SELECT * FROM Products WHERE Price > 30;
• SELECT * FROM Products WHERE Price < 30;
• SELECT * FROM Products WHERE Price >= 30;
• SELECT * FROM Products WHERE Price <= 30;
• <>Not equal. Note: In some versions of SQL this operator may be
written as !=
• Example
• SELECT * FROM Products WHERE Price <> 18;
• BETWEEN Between a certain range
• SELECT * FROM Products WHERE Price BETWEEN 50 AND 60;

• LIKE Search for a pattern


• SELECT * FROM Customers WHERE City LIKE 's%';

• IN To specify multiple possible values for a column


• SELECT * FROM Customers WHERE City IN ('Paris','London');
Each comparison operator in SQL with proper
examples.
• SELECT * FROM EmployeeDetails WHERE empid = 1
SQL Not Equal (!=) Operator
• SELECT * FROM EmployeeDetails WHERE empid != 1

• SELECT * FROM EmployeeDetails WHERE empid <> 1

• Both != and <> operators are not equal operators and will return the
same result, but the != operator is not an ISO standard.
SQL AND, OR and NOT Operators
• The SQL AND, OR and NOT Operators
• The WHERE clause can be combined with AND, OR, and NOT
operators.
• The AND and OR operators are used to filter records based on more
than one condition:
• The AND operator displays a record if all the conditions separated by
AND are TRUE.
• The OR operator displays a record if any of the conditions separated
by OR is TRUE.
• The NOT operator displays a record if the condition(s) is NOT TRUE.
id FirstName LastName Age DateJoined Location

Los
1 Will Smith 52 2020-08-23
Angeles

San
2 Brad Pitt 56 2018-06-15
Francisco

San
3 Tom Hanks 64 2017-02-27
Diego

Los
4 Angelina Jolie 45 2019-04-02
Angeles

Manhatt
5 Meryl Streep 71 2014-03-21
an
• SELECT * FROM members WHERE Age < 50 AND Location = 'Los
Angeles';

id FirstName LastName Age DateJoined Location

4 Angelina Jolie 45 2019-04-02 Los Angeles


SQL OR Syntax
• When multiple conditions are combined using the OR operator, all
rows which meet any of the given conditions will be returned.

• SELECT * FROM members WHERE Location = 'Los Angeles' OR


LastName = 'Hanks'
id FirstName LastName Age DateJoined Location

Los
1 Will Smith 52 2020-08-23
Angeles

San
3 Tom Hanks 64 2017-02-27
Diego

Los
4 Angelina Jolie 45 2019-04-02
Angeles
SQL NOT Syntax
• When multiple conditions are combined using the NOT operator, all
rows which do not meet the given conditions will be returned.
• SELECT * FROM members WHERE NOT Location = 'Los Angeles'
id FirstName LastName Age DateJoined Location

San
2 Brad Pitt 56 2018-06-15
Francisco

San
3 Tom Hanks 64 2017-02-27
Diego

Manhatt
5 Meryl Streep 71 2014-03-21
an
Combining the AND, OR, and NOT operators
• SELECT * FROM members WHERE AGE > 50 AND (Location='Los
Angeles' OR Location='Manhattan')
id FirstName LastName Age DateJoined Location

Los
1 Will Smith 52 2020-08-23
Angeles

Manhatt
5 Meryl Streep 71 2014-03-21
an
BETWEEN
• The SQL BETWEEN condition allows you to easily test if an expression
is within a range of values (inclusive).
• The values can be text, date, or numbers. It can be used in a SELECT,
INSERT, UPDATE, or DELETE statement.
• The SQL BETWEEN Condition will return the records where expression
is within the range of value1 and value2.
• SELECT column_name(s) FROM table_name WHERE column_name
BETWEEN value1 AND value2;
• List all the Employee Fname, Lname who is having salary between
30000 and 45000.
• SELECT Fname, Lname FROM Employee WHERE Salary BETWEEN 30000 AND
45000;
• Using NOT operator with BETWEEN
• Find all the Employee name whose salary is not in the range of 30000
and 45000.
• SELECT Fname, Lname FROM Employee WHERE Salary NOT BETWEEN
30000 AND 45000;
IN
• IN operator allows you to easily test if the expression matches any
value in the list of values.
• It is used to remove the need of multiple OR condition in SELECT,
INSERT, UPDATE or DELETE.
• You can also use NOT IN to exclude the rows in your list. We should
note that any kind of duplicate entry will be retained.
• Find the Fname, Lname of the Employees who have Salary equal to
30000, 40000 or 25000.
• SELECT Fname, Lname FROM Employee WHERE Salary IN (30000, 40000,
25000);

• Find the Fname, Lname of all the Employee who have Salary not
equal to 25000 or 30000.
• SELECT Fname, Lname FROM Employee WHERE Salary NOT IN (25000,
30000);
Like Operator
• The SQL LIKE clause is used to compare a value to similar values using
wildcard operators.
• There are two wildcards used in conjunction with the LIKE operator.
• The percent sign (%)
• The underscore (_)
• SELECT FROM table_name WHERE column LIKE 'XXXX%'
or
• SELECT FROM table_name WHERE column LIKE '%XXXX%'
or
• SELECT FROM table_name WHERE column LIKE 'XXXX_'
or
• SELECT FROM table_name WHERE column LIKE '_XXXX'
or
• SELECT FROM table_name WHERE column LIKE '_XXXX_'
Update Statement
• The UPDATE statement is used to modify the existing records in a
table.
• 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!
CustomerID CustomerName ContactName Address City
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin
2 Ana Trujillo Emparedados Ana Trujillo Avda. de la Constitución México D.F.
y helados 2222
3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F.
4 Around the Horn Thomas Hardy 120 Hanover Sq. London
5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå
• UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;
CustomerID CustomerName ContactName Address City
1 Alfreds Futterkiste Alfred Schmidt Obere Str. 57 Frankfurt
2 Ana Trujillo Emparedados Ana Trujillo Avda. de la Constitución México D.F.
y helados 2222
3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F.
4 Around the Horn Thomas Hardy 120 Hanover Sq. London
5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå
• Update Warning!
• Be careful when updating records. If you omit the WHERE clause, ALL
records will be updated!

• UPDATE Customers
SET ContactName='Juan';
CustomerID CustomerName ContactName Address City
1 Alfreds Futterkiste Juan Obere Str. 57 Frankfurt
2 Ana Trujillo Emparedados Juan Avda. de la Constitución México D.F.
y helados 2222
3 Antonio Moreno Taquería Juan Mataderos 2312 México D.F.
4 Around the Horn Juan 120 Hanover Sq. London
5 Berglunds snabbköp Juan Berguvsvägen 8 Luleå
ORDER BY statement (Sorting the Output)
• The ORDER BY clause is used to get the sorted records on one or
more columns in ascending or descending order.
• The ORDER BY clause must come after the WHERE, GROUP BY, and
HAVING clause if present in the query.
• Use ASC or DESC to specify the sorting order after the column name.
Use ASC to sort the records in ascending order or use DESC for
descending order. By default, the ORDER BY clause sort the records in
ascending order if the order is not specified.
• The following query will fetch all the records from the Employee table
and sorts the result in ascending order of the FirstName values.
• SELECT * FROM Employee ORDER BY FirstName;
• The following query will return rows in the descending order of the
FirstName value.
• SELECT EmpId, FirstName, LastName FROM Employee ORDER BY
FirstName DESC;
Sort by Multiple Columns
• SELECT * FROM Employee ORDER BY DeptId, FirstName
• The above query will first sort the result by DeptId, and then the rows
having the same DeptId will be sorted by the FirstName. Remember,
we have not included ASC or DESC, So it will sort the result in
ascending order by default
Sorting Results by relative position
• You can also use the SQL ORDER BY clause to sort by relative position
in the result set, where the first field in the result set is 1, the second
field is 2, the third field is 3, and so on.
• In addition to being able to specify sort order using column names,
ORDER BY also supports ordering specified by relative column
position.
• SELECT product_id, product_name FROM products ORDER BY 1 DESC;

product_id product_name
7 Kleenex
6 Sliced Ham
5 Bread
4 Apple
3 Orange
2 Banana
1 Pear
SQL ALIASES (AS keyword)
• SQL aliases are used to give a table, or a column in a table, a
temporary name.
• Aliases are often used to make column names more readable.
• An alias only exists for the duration of that query.
• An alias is created with the AS keyword
Alias Column Syntax
• SELECT column_name AS alias_name
FROM table_name;
Example
• SELECT CustomerID AS ID, CustomerName AS Customer
FROM Customers;
Alias Table Syntax
• SELECT column_name(s)
FROM table_name AS alias_name;
Example
• SELECT [Link], [Link], [Link] FROM Customers
AS c, Orders AS o WHERE [Link]='Around the Horn' AND
[Link]=[Link];
Aggregate (Group) Functions
• In database management an aggregate function is a function where
the values of multiple rows are grouped together as input on certain
criteria to form a single value of more significant meaning.
• Aggregate function operate against a collection of values, but return a
single value.
• It is mainly used in summarizing the information stored in tables.
Various Aggregate Functions
• AVG(): Calculates the average of the set of values.
• COUNT(): Returns the count of rows.
• SUM(): Calculates the arithmetic sum of the set of numeric values.
• MAX(): From a group of values, returns the maximum value.
• MIN(): From a group of values, returns the minimum value.
AVG Function
• This function returns the average value of the numeric column that is
supplied as a parameter.
• Example: Write a query to select average salary from employee table.
• Select AVG(salary) from Employee
COUNT Function
• The count function returns the number of rows in the result. It does
not count the null values.
• Example: Write a query to return number of rows where salary >
20000.
• Select COUNT(*) from Employee where Salary > 20000;
• Types −
• COUNT(*): Counts all the number of rows of the table including null.
• COUNT( COLUMN_NAME): count number of non-null values in
column.
MAX Function
• The MAX function is used to find maximum value in the column that
is supplied as a parameter. It can be used on any type of data.
• Example − Write a query to find the maximum salary in employee
table.
• Select MAX(salary) from Employee
MIN function
• The MIN function is used to find minimum value in the column that is
supplied as a parameter. It can be used on any type of data.
• To get the minimum units in stock of products in the products table,
you use the MIN function as follows:
• SELECT MIN(unitsinstock) FROM products;
SUM Function
• This function sums up the values in the column supplied as a
parameter.
• Example: Write a query to get the total salary of employees
• Select SUM(salary) from Employee
Sid SName Marks
1 John 90
2 Martin 80
3 Carol 89
4 Jack 99
5 Rose 88
6 Mary 90
• Find total number of students
• SELECT COUNT(Sid) as COUNT FROM Exam_Marks
• Find total of marks scored by all students
• SELECT SUM(Marks) as SUM FROM Exam_Marks
• Find average marks of students
• SELECT AVG(Marks) as AVG FROM Exam_Marks
• Find minimum of marks scored by all students
• SELECT MIN(Marks) as MIN FROM Exam_Marks
• Find maximum of marks scored by all students
• SELECT MAX(Marks) as MAX FROM Exam_Marks
GROUP BY Clauses
• The GROUP BY Statement in SQL is used to arrange identical data into
groups with the help of some functions. i.e if a particular column has
same values in different rows then it will arrange these rows in a
group.
• Important Points:
• GROUP BY clause is used with the SELECT statement.
• In the query, GROUP BY clause is placed after the WHERE clause.
• In the query, GROUP BY clause is placed before ORDER BY clause if used any.
• Syntax
• SELECT column1, function_name(column2) FROM table_name
WHERE condition GROUP BY column1, column2 ORDER BY column1,
column2;
• SELECT NAME, SUM(SALARY) FROM Employee GROUP BY NAME;
HAVING clause
• if we want to place conditions on groups HAVING clause is used
• We can use HAVING clause to place conditions to decide which group
will be the part of final result-set
Syntax
• SELECT column1, function_name(column2) FROM table_name
WHERE condition GROUP BY column1, column2 HAVING condition
ORDER BY column1, column2;
• SELECT NAME, SUM(SALARY) FROM Employee
• GROUP BY NAME
• HAVING SUM(SALARY)>3000;
• Write the difference between WHERE and HAVING clause.
Displaying data from Multiple tables
Types of join
• Inner join
• Cross join
• Self join
• Natural join
• Outer join
• Left outer join
• Right outer join
• Full outer join
SQL Inner Join
• The INNER JOIN selects all rows from both participating tables as long
as there is a match between the columns.
• An SQL INNER JOIN is same as JOIN clause, combining rows from two
or more tables.

• SELECT * FROM table1 INNER JOIN table2 ON table1.column_name =
table2.column_name;
OR
• SELECT * FROM table1 JOIN table2 ON table1.column_name =
table2.column_name;
SQL CROSS JOIN
• The CROSS JOIN joined every row from the first table (T1) with every
row from the second table (T2).
• In other words, the cross join returns a Cartesian product of rows
from both tables.
CROSS JOIN Syntax
• SELECT column_name(s) FROM table1 CROSS JOIN table2;
SELF JOIN
• A self join is a join in which a table is joined with itself (which is also
called Unary relationships), especially when the table has a FOREIGN
KEY which references its own PRIMARY KEY.
• To join a table itself means that each row of the table is combined
with itself and with every other row of the table.
• The self join can be viewed as a join of two copies of the same table.
The table is not actually copied, but SQL performs the command as
though it were.
Syntax
• SELECT a.column_name, b.column_name... FROM table1 a, table1 b
WHERE a.common_filed = b.common_field;
Natural Join
• The SQL NATURAL JOIN is a type of EQUI JOIN and is structured in
such a way that, columns with the same name of associated tables
will appear once only.
• A natural join is a type of join operation that creates an implicit join
by combining tables based on columns with the same name and data
type.
• It is similar to the INNER or LEFT JOIN, but we cannot use the ON or
USING clause with natural join as we used in them.
Syntax
• SELECT * FROM table1 NATURAL JOIN table2;
Outer Join
• It is categorized in
• Left Outer Join
• Right Outer Join
• Full Outer Join
Left Outer Join
• Left outer join returns all rows from the left(first) table specified in
the ON condition and only those rows from the right (second) table
where join condition is met and set NULL to the unmatched rows of
second table.
• SELECT column1, column2... FROM table_A LEFT JOIN table_B ON
join_condition WHERE row_condition
Right Outer Join
• RIGHT JOIN is similar to LEFT JOIN. This join returns all the rows of
the table on the right side of the join and matching rows for the table
on the left side of join. The rows for which there is no matching row
on left side, the result-set will contain null. RIGHT JOIN is also known
as RIGHT OUTER JOIN.
• SELECT table1.column1,table1.column2,table2.column1,....
• FROM table1 RIGHT JOIN table2 ON table1.matching_column =
table2.matching_column;
FULL OUTER Join
•SQL full outer join returns:
• all rows in the left table table_A.
• all rows in the right table table_B.
• and all matching rows in both tables.
• SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition;
Example

OrderID CustomerID EmployeeID OrderDate ShipperID


10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
CustomerID CustomerName ContactName Address City PostalCode Country
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany

2 Ana Trujillo Ana Trujillo Avda. de la México D.F. 05021 Mexico


Emparedados y Constitución
helados 2222
3 Antonio Moreno Antonio Mataderos 2312 México D.F. 05023 Mexico
Taquería Moreno
SQL INNER JOIN Example
• SELECT [Link], [Link] FROM Orders
INNER JOIN Customers ON [Link] =
[Link];
MySQL CROSS JOIN Example
• SELECT [Link], [Link]
FROM Customers
CROSS JOIN Orders;
SQL Self Join Example
• SELECT a.emp_id AS "Emp_ID",a.emp_name AS "Employee Name",
b.emp_id AS "Supervisor ID",b.emp_name AS "Supervisor Name"
FROM employee a, employee b WHERE a.emp_supv = b.emp_id;
Natural Join examples
• SELECT * FROM foods NATURAL JOIN company;
Example of SQL Left Join
• SELECT [Link],StudentCourse.COURSE_ID FROM Student
LEFT JOIN StudentCourse ON StudentCourse.ROLL_NO =
Student.ROLL_NO;
• Note: The LEFT JOIN keyword returns all records from the left table
even if there are no matches in the right table.
RIGHT JOIN
• SELECT [Link],StudentCourse.COURSE_ID FROM Student
RIGHT JOIN StudentCourse ON StudentCourse.ROLL_NO =
Student.ROLL_NO;
FULL JOIN
• SELECT [Link],StudentCourse.COURSE_ID FROM Student
FULL JOIN StudentCourse ON StudentCourse.ROLL_NO =
Student.ROLL_NO;
NAME COURSE_ID
HARSH 1

PRATIK 2

RIYANKA 2

DEEP 3

SAPTARHI 1

DHANRAJ NULL

ROHIT NULL

NIRAJ NULL

NULL 4

NULL 5

NULL 4
• Get employee name, project name order by firstname from
"EmployeeDetail" and "ProjectDetail" for those employee which have
assigned project already.
• Get employee name, project name order by firstname from
"EmployeeDetail" and "ProjectDetail" for all employee even they have
not assigned project.
• Get employee name, project name order by firstname from
"EmployeeDetail" and "ProjectDetail" for all employee if project is not
assigned then display "-No Project Assigned".
• Get all project name even they have not matching any employeeid, in
left table, order by firstname from "EmployeeDetail" and
"ProjectDetail".
Nested Query in SQL
• A Subquery or Inner query or a Nested query is a query within
another SQL query and embedded within the WHERE clause.
• A subquery is used to return data that will be used in the main query
as a condition to further restrict the data to be retrieved.
• Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE
statements along with the operators like =, <, >, >=, <=, IN, BETWEEN,
etc.
There are a few rules that subqueries must
follow
• Subqueries must be enclosed within parentheses.
• A subquery can have only one column in the SELECT clause, unless multiple
columns are in the main query for the subquery to compare its selected columns.
• An ORDER BY command cannot be used in a subquery, although the main query
can use an ORDER BY. The GROUP BY command can be used to perform the same
function as the ORDER BY in a subquery.
• Subqueries that return more than one row can only be used with multiple value
operators such as the IN operator.
• The SELECT list cannot include any references to values that evaluate to a BLOB,
ARRAY, CLOB, or NCLOB.
• A subquery cannot be immediately enclosed in a set function.
• The BETWEEN operator cannot be used with a subquery. However, the BETWEEN
operator can be used within the subquery.
Types of Nested Queries in SQL
Non-correlated (or Independent) Nested
Queries
A non-correlated (or independent) nested query is a subquery that
does not depend on the outer query for its execution. The inner query
(subquery) is executed once, and its result is then used by the outer
query. Unlike correlated subqueries, a non-correlated subquery can be
executed independently, and it doesn't reference any columns from the
outer query.
Let's go over some examples and scenarios to
illustrate non-correlated nested queries:
Single Row Sub query
• Sub-query which returns single row output.
• They mark the usage of single row comparison operators, when used
in WHERE condition.
• A single-row subquery is used when the outer query results are based
on a single, unknown value.
Example
• SELECT agent_name, agent_code, phone_no FROM agents WHERE
agent_code =
• (SELECT agent_code FROM agents WHERE agent_name = 'Alex');
• SELECT first_name, salary, department_id FROM employees WHERE
salary =
• (SELECT MIN (salary) FROM employees);
Multiple Row Subquery
• Multiple-row subqueries are nested queries that can return more
than one row of results to the parent query.
• Multiple-row subqueries are used most commonly in WHERE and
HAVING clauses.
• Since it returns multiple rows, it must be handled by set comparison
operators (IN, ALL, ANY).
Examples
SELECT name FROM employees
WHERE id IN (
SELECT t_id
FROM students
WHERE id = 1
);
Correlated Subqueries
• There are also SQL subqueries where the inner query relies on
information obtained from the outer query. These are correlated
subqueries.
• Because of the interdependence between the main query and the
inner query, this type of subquery can be more challenging to
understand.
• A correlated subquery is evaluated once for each row processed by
the parent statement. The parent statement can be SELECT, UPDATE,
or DELETE statement.

Syntax
• SELECT column1, column2, ....
• FROM table1 outer
• WHERE column1 operator
• (SELECT column1, column2
• FROM table2
• WHERE expr1 =
• outer.expr2);
• A correlated subquery is one way of reading every row in a table and
comparing values in each row against related data.
• It is used whenever a subquery must return a different result or set of
results for each candidate row considered by the main query.
• In other words, you can use a correlated subquery to answer a
multipart question whose answer depends on the value in each row
processed by the parent statement.
EXAMPLE
• SELECT [Link]
• FROM EmployeeDetail e
• WHERE (SELECT COUNT(*)
• FROM ProjectDetail p
• WHERE [Link] = [Link]) > 1; explain this
SQL correlated subquery in the WHERE
clause example
• SELECT employee_id, first_name, last_name, salary, department_id
FROMemployees e WHERE salary >
• (SELECT AVG(salary) FROM employees WHERE department_id =
e.department_id) ORDER BY department_id , first_name , last_name;
• In this example, the outer query is:
• SELECT employee_id, first_name, last_name, salary, department_id
FROM employees e WHERE salary >
• and the correlated subquery is:
• SELECT AVG( list_price ) FROM products WHERE category_id =
p.category_id
SQL correlated subquery with EXISTS
operator example
• We often use a correlated subquery with the EXISTS operator.
• The EXISTS operator tests for existence of rows in the results set of
the subquery. If a subquery row value is found the condition is
flagged TRUE and the search does not continue in the inner query,
and if it is not found then the condition is flagged FALSE and the
search continues in the inner query.
• SELECT employee_id, first_name, last_name FROM employees e
WHERE NOT EXISTS
• ( SELECT * FROM dependents d WHERE d.employee_id =
e.employee_id) ORDER BY first_name , last_name;
SET operation in SQL
• SQL set operators are used to combine the results obtained from two
or more queries into a single result.
• There are four major types of SQL operators, namely:
• Union
• Union all
• Intersect
• Minus
Combines distinct results of two or more
Union
SELECT statements.

Combines all results of two or more SELECT


Union All
statements, including duplicates.

Returns only the common records obtained


Intersect
from two or more SELECT statements.

Returns only those records which are


Minus
exclusive to the first table.
Union Set Operator
• The UNION set operator is used to combine the results obtained from
two or more SELECT statements. Here is an example to illustrate the
use of the UNION Operator.
• Find the name of all the customers
• SELECT name FROM customers_dec UNION SELECT name FROM
customers_jan;
Union All Set Operator
• The UNION set operator is used to combine all the results obtained
from two or more SELECT statements. Unlike the Union operator, it
considers duplicate values and includes them in the final result.
• Find the names of all the customers who registered in December or
January.
• SELECT name FROM customers_dec UNION ALL SELECT name FROM
customers_jan;
Intersect Set Operator
• The intersect set operator used to combine all the results of two
SELECT statements. But returns only those records that are common
to both the SELECT statements.
• Find the details of customers who shopped in December and January.
• SELECT name, city FROM customers_dec INTERSECT SELECT name,
city FROM customers_jan;
Minus Set Operator
• The MINUS set operator used to combine all the results of two or
more SELECT statements. But returns only those records that are
present exclusively in the first table.
• Find the details of customers who shopped only in December but not
January.
• SELECT name, city FROM customers_dec EXCEPT SELECT name, city
FROM customers_jan;
DCL (DATA CONTROL LANGUAGE)
• The Data Control Language is a subset of the Structured Query
Language. Database administrators use DCL to configure security
access to relational databases. It complements the Data Definition
Language, which adds and deletes database objects, and the Data
Manipulation Language, which retrieves, inserts, and modifies the
contents of a database.
• DCL commands are as follows,
1. GRANT
2. REVOKE
It is used to grant or revoke access permissions from any database
user.
GRANT COMMAND
• GRANT command gives user's access privileges to the database.
• This command allows specified users to perform specific tasks.
• Syntax:
GRANT <privilege list>
ON <relation name or view name>
TO <user/role list>;
Example
• GRANT ALL ON employee TO ABC;

• In the above example, user 'ABC' has been given permission to view
and modify the records in the 'employee' table.
• Write SQL statement to grant SELECT, INSERT, UPDATE and DELETE
privilege on a table called students to a user name John.
• GRANT SELECT, INSERT UPDATE, DELETE ON Student TO John.
• Write a SQL statement to grant director role to user name sita
• GRANT director TO sita;
REVOKE COMMAND
• REVOKE command is used to cancel previously granted or denied
permissions.
• This command withdraw access privileges given with the GRANT
command.
• It takes back permissions from user.
• Syntax:
REVOKE <privilege list>
ON <relation name or view name>
FROM <user name>;
Example
• REVOKE UPDATE ON employee FROM ABC;
•Write a SQL statement to revoke INSERT and DELETE
privileges on a table called Students from a user name John
• REVOKE INSERT, DELETE ON Student FROM John.
• Write a SQL statement to REVOKE director role to user name sita
• REVOKE director FROM sita;
Creating and Altering View
• 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 statements and functions to a view and present the
data as if the data were coming from one single table.
• A view is created with the CREATE VIEW statement.
CREATE VIEW Syntax
• CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
SQL CREATE VIEW Examples
• CREATE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName
FROM Customers
WHERE Country = 'Brazil';
• CREATE VIEW [Products Above Average Price] AS
SELECT ProductName, Price
FROM Products
WHERE Price > (SELECT AVG(Price) FROM Products);
Alter view
• In SQL Server, you can use the ALTER VIEW statement to modify or
alter a view. The general syntax of the ALTER VIEW statement is:
• Syntax:
• ALTER VIEW <view name> AS <SELECT statement>
Example
• ALTER VIEW project_view AS SELECT project_no, project_name FROM
project WHERE project_no >= 'p3';

You might also like