BPA DBMS Chapter5 - Advanced SQL
BPA DBMS Chapter5 - Advanced SQL
SQL
• ⋈
Natural Join: R1 R2
• Theta Join: R1 R2
• Equi Join: When the theta condi;on is equal (=)
• Lek Outer Join: R L
• Right outer Join: R L
• Full Outer Join: R L
• Cross Join: R1 x R2
• Semi Join: R1 R2
• Self Join: R1 R1
Different types of Joins
• INNER JOIN
• OUTER JOIN
– LEFT OUTER JOIN or LEFT JOIN
– RIGHT OUTER JOIN or RIGHT JOIN
– FULL OUTER JOIN or FULL JOIN
• NATURAL JOIN
• CROSS JOIN
• SELF JOIN
SQL Joins
Cross JOIN or Cartesian Product
• This type of JOIN returns the – The class_info table,
cartesian product of rows from • ID Address
the tables in Join. It will return a • 1 Morang
• 2 Gorkha
table which consists of records • 3 Ilam
which combines each row from
the first table with each row of • Cross JOIN query will be,
the second table. – SELECT * from class,
CROSS JOIN class_info;
• Cross JOIN Syntax is,
• SELECT column-name-list – SELECT * from class ,
from table-name1 CROSS class_info;
JOIN table-name2; • The result table will look like,
• ID NAME ID Address
• The tables can be • 1 Bisnu 1 Morang
separated by comma also. • 2 Raisa 1 Morang
• Example of Cross JOIN • 4 Puja 1 Morang
– The class table, • 1 Bisnu 2 Gorkha
• ID NAME • 2 Raisa 2 Gorkha
• 4 Puja 2 Gorkha
• 1 Bisnu
• 2 Raisa • 1 Bisnu 3 Ilam
• 4 Puja • 2 Raisa 3 Ilam
• 4 Puja 3 Ilam
INNER Join – THETA/EQUI Join
• This is a simple JOIN in which the – The class_info table,
result is based on matched data • ID Address
as per the equality condi;on • 1 Gorkha
• 2 Morang
specified in the query. • 3 Nuwakot
• Inner Join Syntax is, • Inner JOIN query will be,
SELECT column-name-list from – SELECT * from class INNER JOIN
table-name1 class_info ON class.id =
INNER JOIN table-name2 class_info.id;
ON table-name1.column-name =
table-name2.column-name; – SELECT * from class, class_info
where class.id = class_info.id;
• Example of Inner JOIN
– The class table,
• The result table will look like,
• ID NAME ID Address
• ID NAME
• 1 Bisnu 1 Gorkha
• 1 Bisnu • 2 Raisa 2 Morang
• 2 Raisa • 3 Janu 3 Nuwakot
• 3 Janu
• 4 Puja • If the condi;on is supplied in inner join
it is called theta join. If condi;on
contains equal sign (=), it is called equi
join
Natural JOIN
• Natural Join is a type of Inner join • Example of Natural JOIN
which is based on column having – The class table,
same name and same datatype • ID NAME
present in both the tables to be • 1 Bisnu
joined. • 2 Raisa
• 3 Janu
• We don't need to provide join • 4 Mina
condi;on. It joins two tables – The class_info table,
automa;cally • ID Address
• Natural Join Syntax is, • 1 Gorkha
• 2 Morang
– SELECT * from table-name1
• 3 Nuwakot
NATURAL JOIN table-name2;
• In the given example, • Natural join query will be,
– both the tables being joined have – SELECT * from class
ID column(same name and same NATURAL JOIN class_info;
datatype), • The result table will look like,
– hence the records for which value • ID NAME Address
of ID matches in both the tables • 1 Bisnu Gorkha
will be the result of Natural Join • 2 Raisa Morang
• 3 Janu Nuwakot
Outer JOIN
• Outer Join is based on both matched and
unmatched data. Outer Joins subdivide
further into,
– Lek Outer Join
– Right Outer Join
– Full Outer Join
LeG Outer Join
• The lek outer join returns a result – The class_info table,
table with the matched data of two • ID Address
tables then remaining rows of the leG • 1 Gorkha
• 2 Morang
table and null for the right table's
• 3 Nuwakot
column. • 7 Sunsari
• Lek Outer Join syntax is, • 8 Ilam
SELECT column-name-list • LeG Outer Join query will be,
from table-name1 – SELECT * FROM class
LEFT OUTER JOIN table-name2 LEFT OUTER JOIN class_info
ON table-name1.column-name = ON class.id=class_info.id;
table-name2.column-name;
• Lek outer Join Syntax for Oracle is, • The result table will look like,
• ID NAME ID Address
select column-name-list • 1 Bisnu 1 Gorkha
from table-name1, table-name2
on table-name1.column-name = • 2 Raisa 2 Morang
table-name2.column-name(+); • 3 Janu 3 Nuwakot
• 4 Mina null null
• Example of Lek Outer Join with the • 5 Puja null null
class table,
• ID NAME
• 1 Bisnu
• 2 Raisa
• 3 Janu
• 4 Mina
• 5 Puja
Right Outer Join
• The right outer join returns a result – The class_info table,
table with the matched data of two • ID Address
tables then remaining rows of the • 1 Gorkha
• 2 Morang
right table and null for the leG table's
• 3 Nuwakot
columns. • 7 Sunsari
• Right Outer Join Syntax is, • 8 Ilam
– select column-name-list from table- • Right Outer Join query will be,
name1 – SELECT * FROM class
RIGHT OUTER JOIN table-name2 RIGHT OUTER JOIN class_info
ON table-name1.column-name = table- ON (class.id=class_info.id);
name2.column-name;
– Right outer Join Syntax for Oracle is, • The result table will look like,
– select column-name-list from table- • ID NAME ID Address
name1, table-name2 • 1 Bisnu 1 Gorkha
on table-name1.column-name(+) = • 2 Raisa 2 Morang
table-name2.column-name; • 3 Janu 3 Nuwakot
• null null 7 Sunsari
• Example of Lek Outer Join with the • null null 8 Ilam
class table,
• ID NAME
• 1 Bisnu
• 2 Raisa
• 3 Janu
• 4 Mina
• 5 Puja
Full Outer Join
• The full outer join returns a result – The class_info table,
table with the matched data of • ID Address
two table then remaining rows of • 1 Gorkha
• 2 Morang
both leG table and then the right • 3 Nuwakot
table. • 7 Sunsari
• Full Outer Join Syntax is, • 8 Ilam
– select column-name-list from • Full Outer Join query will be like,
table-name1 – SELECT * FROM class
FULL OUTER JOIN table-name2 FULL OUTER JOIN class_info
ON table-name1.column-name = ON (class.id=class_info.id);
table-name2.column-name;
• The result table will look like,
• Example of Lek Outer Join with • ID NAME ID Address
the class table, • 1 Bisnu 1 Gorkha
• ID NAME • 2 Raisa 2 Morang
• 1 Bisnu • 3 Janu 3 Nuwakot
• 2 Raisa • 4 Mina null null
• 3 Janu • 5 Puja null null
• 4 Mina • null null 7 Sunsari
• 5 Puja • null null 8 Ilam
Self Join
• Self join is regular join in • E.g.: table client
which a table is joined – id name phone zone
(compared) to itself. – 1 Pragya 9853 Koshi
• One prac;cal use for self- – 2 Mina 9833 Bagma;
joins: obtaining running – 3 Januka 9754 Bagma;
counts and running totals – 4 Raisa 9841 Koshi
in an SQL query. – 5 Bishnu 9767 Gandaki
• To write the query, • Match client names from same
– select from same table zone
twice with different SELECT A.name AS n1, B.name
aliases, AS n2
– set up the comparison, and FROM client AS A, client AS B
– eliminate cases where a WHERE a.id <> b.id
par;cular value would be AND A.zone = b.zone
equal to itself. ORDER BY A.zone
Semi Join/an; join
• A join where the result only contains the columns from one
of the joined tables
– Used for reducing communica;on cost in distributed database
– Semi-joins are wripen using EXISTS or IN.
• An INNER JOIN returns the columns from both tables. A
LEFT SEMI JOIN only returns the records from the lek-hand
table.
• It has following form:
– SELECT ... FROM outer_tables WHERE expr IN/
EXISTS (SELECT ... FROM inner_tables ...)
– E.g. SELECT name FROM table_1 as a
WHERE EXISTS( SELECT * FROM table_2 as b WHERE
(a.name=b.name))
• If we replace EXISTS with NOT EXISTS, or IN with NOT IN,
then it is called an; join
Semi Join Example
• SELECT * FROM Country
WHERE Continent='Europe'
AND Country.Code IN (SELECT
City.country FROM City WHERE
City.Population>1000000);
Semi join example
• Give list of departments with at least one employee
• Tradi;onal join:
– SELECT d.deptno, d.dname from dept as d,
emp as e where e.deptno=d.deptno;
• With semi join
– SELECT d.deptno, d.dname FROM dept D where
EXISTS (SELECT 1 from Emp E WHERE
e.deptno=d.deptno);
• If we use semi join, no department appear more than
once and once DBMS finds one department, it stops
processing other department so it might be slightly
faster. if we use tradi;onal join, we have to use dis;nct
SET opera;ons
• SQL supports few Set opera;ons to be
performed on table data. These are used to
get meaningful results from data, under
different special condi;ons.
– Union
– Union All
– Intersect
– Minus
UNION
• UNION is used to combine the results of
two or more Select statements. However it
will eliminate duplicate rows from its result
set. In case of union, number of columns
and datatype must be same in both the
tables.
• Example of UNION
Om • The First table,
Sita • ID Name
Ram Om • 1 Ram
• 2 Om
– The Second table,
• ID Name
• 2 Om
• 3 Sita
• Union SQL query will be,
– select * from First
UNION
select * from second
• The result table will look like,
– ID NAME
– 1 Ram
– 2 Om
– 3 Sita
UNION ALL
• This opera;on is similar to Union.
But it also shows the duplicate
rows.
• Example of Union All
– The First table,
• ID NAME
• 1 Ram
Om Sita • 2 Om
Ram Om – The Second table,
• ID NAME
• 2 Om
• 3 Sita
• Union All query will be like,
– select * from First
UNION ALL
select * from second
• The result table will look like,
• ID NAME
• 1 Ram
• 2 Om
• 2 Om
• 3 Sita
INTERSECT
• Intersect opera;on 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. MySQL does not
support INTERSECT operator.
• Example of Intersect
Om – The First table,
Sita • ID Name
Ram Om • 1 Ram
• 2 Om
– The Second table,
• ID Name
• 2 Om
• 3 Sita
• SELECT query
– select * from First
INTERSECT
select * from second
• The result table will look like
• ID NAME
• 2 Om
MINUS
• Minus opera;on combines result of
two Select statements and return
only those result which belongs to
first set of result. MySQL does not
support INTERSECT operator. Some
implementa;on use EXCEPT
• Example of Minus
Om – The First table,
Sita • ID Name
Ram Om • 1 Ram
• 2 Om
– The Second table,
• ID Name
• 2 Om
• 3 Sita
• Minus query will be,
– select * from First
MINUS /EXCEPT
select * from second
• The result table will look like,
• ID NAME
• 1 Ram
SQL VIEW
• A view in SQL is a logical subset of data from
one or more tables. View is also used to
restrict data access.
• Syntax for crea;ng a View,
– CREATE or REPLACE
view view_name AS
SELECT column_name(s)
FROM table_name
WHERE condi3on
Example of CreaDng a View
• Consider following Sale table,
• oid order_name previous_balance customer address
• 11 ord1 2000 Bishnu Gorkha
• 12 ord2 1000 Raisa Morang
• 13 ord3 2000 Janu Nuwakot
• 14 ord4 1000 Puja Gorkha
• 15 ord5 2000 Subarna Gorkha
• SQL Query to Create View
– CREATE VIEW sale_view as
select * from Sale
where address= 'Gorkha';
• The data fetched from select statement will be stored in another object
called sale_view. We can use create separately and replace too but using
both together works beper.
• Displaying a View: Syntax of displaying a view is similar to fetching data from
table using Select statement.
– SELECT * from sale_view
• The right of viewing this view can be given to area sales manager of Gorkha.
Thus protec;ng data from other area
Force View CreaDon
• FORCE keyword is used while crea;ng a view.
– This keyword force to create View even if the
table does not exist.
– Aker crea;ng a force View if we create the base
table and enter values in it, the view will be
automa;cally updated.
• Syntax for forced View is,
– CREATE / REPLACE force
view view_name AS
SELECT column_name(s)
FROM table_name
WHERE condi3on
Update a View
• Update command for view is same as for
tables.
• Syntax to Update a View is,
– UPDATE view-name
SET field-name = value
WHERE condi;on;
• If we update a view it also updates base table
data automa;cally.
Read-Only View
• We can create a view with read-only op;on to restrict
access to the view.
• Syntax to create a view with Read-Only Access
– CREATE / REPLACE force
VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condi3on
WITH read-only
• The above syntax will create view for read-only
purpose, we cannot Update or Insert data into read-
only view. It will throw an error.
Types of View
• There are two types of view,
– Simple View
• Created from one table
• Does not contain func;ons
• Does not contain groups of data
– Complex View
• Created from one or more table
• Contain func;ons
• Contains groups of data
SQL FuncDons
• SQL provides many built-in func;ons to perform
opera;ons on data. These func;ons are useful while
performing mathema;cal calcula;ons, string
concatena;ons, sub-strings etc. SQL func;ons are
divided into two categories,
• Aggregate FuncDons: These func;ons return a single
value aker calcula;ng from a group of values. Some
frequently used Aggregate func;ons.
– AVG(), COUNT(), SUM(), FIRST(), LAST(), MAX(), MIN()
• Scalar FuncDons: Scalar func;ons return a single value
from an input value. Some frequently used Scalar
Func;ons.
– UCASE(), LCASE(), MID(), ROUND()
Aggregate FuncDons
• These func;ons return a single value aker calcula;ng from a group
of values. Following are some frequently used Aggregate func;ons.
• AVG(): Average returns average value aker calcula;ng from values in
a numeric column.
• COUNT(): Count returns the number of rows present in the table
either based on some condi;on or without condi;on.
• FIRST(): First func;on returns first value of a selected column
• LAST(): LAST return the return last value from selected column
• MAX(): MAX func;on returns maximum value from selected column
of the table.
• MIN(): MIN func;on returns minimum value from a selected column
of the table.
• SUM(): SUM func;on returns total sum of a selected columns
numeric values.
COUNT()
• Count returns the number of rows present in the table either based on
some condi;on or without condi;on.
• Its general Syntax is,
– SELECT COUNT(column_name) from table-name
• Example: Consider following Emp table
• eid name age salary
• 401 Bishnu 22 9000
• 402 Pragya 29 8000
• 403 Puja 34 6000
• 404 Saroj 44 10000
• 405 Shyam 35 8000
• SQL query to count employees, sa;sfying specified condi;on is,
– SELECT COUNT(name) from Emp where salary > 8000;
• count(name)
• 2
• Example of COUNT(disDnct)
– SELECT COUNT(disDnct salary) from emp;
• count(dis;nct salary)
• 4
AVG()
• AVG: (Average) returns average value aker calcula;ng from
values in a numeric column.
• Its general Syntax is,
– SELECT AVG(column_name) from table_name
• Example: Consider following Emp table
• eid name age salary
• 401 Bishnu 22 9000
• 402 Pragya 29 8000
• 403 Puja 34 6000
• 404 Saroj 44 10000
• 405 Shyam 35 8000
• SQL query to find average of salary will be,
– SELECT avg(salary) from Emp;
• Result of the above query will be,
• avg(salary)
• 8200
SUM()
• SUM func;on returns total sum of a selected columns numeric
values.
• Syntax for SUM is,
– SELECT SUM(column_name) from table-name
• Example of SUM()
• Consider following Emp table
• eid name age salary
• 401 Bishnu 22 9000
• 402 Pragya 29 8000
• 403 Puja 34 6000
• 404 Saroj 44 10000
• 405 Shyam 35 8000
• SQL query to find sum of salaries will be,
– SELECT SUM(salary) from emp;
• Result of above query is,
• SUM(salary)
• 41000
FIRST(), LAST()
• First func;on returns first value of a selected column and Last func;on
returns the last value
• Syntax for FIRST func;on is,
– SELECT FIRST(column_name) from table-name
– SELECT LAST(column_name) from table-name
• Example: Consider following Emp table
• eid name age salary
• 401 Bishnu 22 9000
• 402 Pragya 29 8000
• 403 Puja 34 6000
• 404 Saroj 44 10000
• 405 Shyam 35 8000
• SQL query and result
– SELECT FIRST(salary) from Emp;
• first(salary)
• 9000
– SELECT LAST(salary) from EMP;
• last(salary)
• 8000
MAX(), MIN()
• MAX func;on returns maximum and MIN func;on returns minimum value
from selected column of the table.
• Syntax
– SELECT MAX(column_name) from table-name
– SELECT MIN(column_name) from table-name
• Example: Consider following Emp table
• eid name age salary
• 401 Bishnu 22 9000
• 402 Pragya 29 8000
• 403 Puja 34 6000
• 404 Saroj 44 10000
• 405 Shyam 35 8000
• SQL query to find Maximum and Minimum salary is,
– SELECT MAX(salary) from emp;
• MAX(salary)
• 10000
– SELECT MAX(salary) from emp;
• MIN(salary)
• 6000
Scalar FuncDons
• Scalar func;ons return a single value from an
input value. Following are some frequently used
Scalar Func;ons.
– UCASE(): UCASE func;on is used to convert value of
string column to Uppercase character.
– LCASE(): LCASE func;on is used to convert value of
string column to Lowercase character.
– MID(): MID func;on is used to extract substrings from
column values of string type in a table.
– ROUND(): ROUND func;on is used to round a numeric
field to number of nearest integer. It is used on
Decimal point values.
UCASE(), LCASE()
• UCASE func;on is used to • SQL query
convert value of string column – SELECT UCASE(name) from emp;
to Uppercase character. • UCASE(name)
• BISHNU
• Syntax
• PRAGYA
– SELECT UCASE(column_name) • PUJA
from table-name • SAROJ
– SELECT LCASE(column_name) • SHYAM
from table-name – SELECT LCASE(name) from emp;
• Example: Consider following • LCASE(name)
Emp table • bishnu
• eid name age salary • pragya
• 401 Bishnu 22 9000 • puja
• 402 Pragya 29 8000 • saroj
• 403 Puja 34 6000 • shyam
• 404 Saroj 44 10000
• 405 Shyam 35 8000
MID()
• MID func;on is used to • SQL query will be,
extract substrings from – select MID(name,2,2) from emp;
column values of string type • MID(name,2,2)
in a table. • is
• ra
• Syntax for MID func;on is, • uj
– SELECT MID(column_name, • ar
start, length) from table-name • hy
• Example: Consider following
Emp table
• eid name age salary
• 401 Bishnu 22 9000
• 402 Pragya 29 8000
• 403 Puja 34 6000
• 404 Saroj 44 10000
• 405 Shyam 35 8000
ROUND()
• ROUND func;on is used to round a numeric field to number of nearest
integer. It is used on Decimal point values. Syntax of Round func;on is,
– SELECT ROUND(column_name, decimals) from table-name
• Example of ROUND(): Consider following Emp table
• eid name age salary
• 401 anu 22 9000.67
• 402 shane 29 8000.98
• 403 rohan 34 6000.45
• 404 scop 44 10000
• 405 Tiger 35 8000.01
• SQL query is,
– SELECT ROUND(salary) from emp;
• ROUND(salary)
• 9001
• 8001
• 6000
• 10000
• 8000
SQL Sequence
• Sequence is a feature supported by some • Example to create Sequence
database systems to produce unique • The sequence query is following
values on demand. Some DBMS like – CREATE Sequence seq_1
MySQL supports AUTO_INCREMENT in start with 1
place of Sequence. AUTO_INCREMENT is increment by 1
applied on columns, it automa;cally maxvalue 999
increments the column value by 1 each cycle ;
;me a new record is entered into the • Example to use Sequence
table. Sequence is also some what similar – The class table,
to AUTO_INCREMENT but its has some • ID NAME
extra features. • 1 abhi
• 2 adam
• CreaDng Sequence • 4 alex
– CREATE Sequence sequence-name
start with ini3al-value • The sql query will be,
increment by increment-value – INSERT into class
maxvalue maximum-value value(seq_1.nextval,'anu');
cycle|nocycle • ID NAME
– Start, increment, maxvalue carry similar • 1 abhi
meaning • 2 adam
– Cycle specifies that if the maximum value • 4 alex
exceeds, sequence will restart its cycle from • 1 anu
the begining. • Once you use nextval the sequence will
– No cycle specifies that if sequence exceeds increment even if you don't Insert any
maxvalue an error will be thrown. record into the table.
Sequence and auto increment
• Auto increment is used to increment some fields
automa;cally on every insert opera;on. If
nothing is supplied for that column, the dbms
automa;cally inserts next value in that field.
• Mysql: CREATE TABLE person(id int
AUTO_INCREMENT PRIMARY KEY, name
varchar(200))
• SQL Server: CREATE TABLE person( id int
IDENTITY(1,1) PRIMARY KEY, name varchar(200))
Crea;ng user
• The user must be created at first to login into database and execute
queries. CREATE USER command is used for that
• Syntax for oracle, mysql: CREATE USER <username> IDENTIFIED BY
<password>
• Syntax for postgresql: CREATE USER <username> WITH SYSID uid |
CREATEDB | NOCREATEDB | CREATEUSER | NOCREATEUSER | IN
GROUP groupname [, ...] | [ ENCRYPTED |
UNENCRYPTED ]PASSWORD 'password' | VALID UNTIL ';me'
• SQL Server: CREATE USER username WITH SYSID uid | CREATEDB |
NOCREATEDB | CREATEUSER | NOCREATEUSER | IN GROUP
groupname [, ...] | [ ENCRYPTED | UNENCRYPTED ]PASSWORD
'password' | VALID UNTIL ';me'
• Example: CREATE USER prabin IDENTIFIED BY abc=123
Changing password
• If you want to change the password, you can do it
with following commands on specific
implementa;on of DBMS
• oracle: ALTER USER <username> IDENTIFIED BY
<password>
• Mysql: SET PASSWORD FOR <username> =
PASSWORD('password')
• PostgreSQL: ALTER USER <username> WITH
PASSWORD <password>
• SQL Server: ALTER LOGIN <loginName> WITH
PASSWORD = password
INDEX
• Indexes are used to retrieve data from the database very
fast. The users cannot see the indexes, they are just used to
speed up searches/queries.
• Syntax: CREATE INDEX <index_name> ON table_name
(column1, column2,…)
• E.g. CREATE INDEX idx_firstname ON person(firstname)
• Syntax: DROP INDEX <index_name>
• e.g. Oracle: DROP INDEX idx_firstname
• e.g. Mysql: ALTER TABLE person DROP INDEX idx_firstname
• e.g. SQL Server: DROP INDEX table_name.index_name
• e.g. Access: DROP INDEX index_name ON table_name