SlideShare a Scribd company logo
1 of 50
Database Systems: Design,
Implementation, and
Management
Eighth Edition
Chapter 8
Advanced SQL
Database Systems, 8th
Edition 2
Objectives
• In this chapter, you will learn:
– About the relational set operators UNION,
UNION ALL, INTERSECT, and MINUS
– How to use the advanced SQL JOIN operator
syntax
– About the different types of subqueries and
correlated queries
– How to use SQL functions to manipulate dates,
strings, and other data
Database Systems, 8th
Edition 3
Objectives (continued)
• In this chapter, you will learn: (continued)
– How to create and use updatable views
– How to create and use triggers and stored
procedures
– How to create embedded SQL
Database Systems, 8th
Edition 4
Relational Set Operators
• UNION
• INTERSECT
• MINUS
• Work properly if relations are union-
compatible
– Names of relation attributes must be the same
and their data types must be identical
Database Systems, 8th
Edition 5
UNION
• Combines rows from two or more queries
without including duplicate rows
– Example:
SELECT CUS_LNAME, CUS_FNAME,
CUS_INITIAL, CUS_AREACODE,
FROM CUSTOMER
UNION
SELECT CUS_LNAME, CUS_FNAME,
CUS_INITIAL, CUS_AREACODE,
FROM CUSTOMER_2
• Can be used to unite more than two queries
Database Systems, 8th
Edition 6
UNION ALL
• Produces a relation that retains duplicate rows
– Example query:
SELECT CUS_LNAME, CUS_FNAME,
CUS_INITIAL, CUS_AREACODE,
FROM CUSTOMER
UNION ALL
SELECT CUS_LNAME, CUS_FNAME,
CUS_INITIAL, CUS_AREACODE,
FROM CUSTOMER_2;
• Can be used to unite more than two queries
Database Systems, 8th
Edition 7
Intersect
• Combines rows from two queries, returning only
the rows that appear in both sets
• Syntax: query INTERSECT query
– Example query:
SELECT CUS_LNAME, CUS_FNAME,
CUS_INITIAL, CUS_AREACODE,
FROM CUSTOMER
INTERSECT
SELECT CUS_LNAME, CUS_FNAME,
CUS_INITIAL, CUS_AREACODE,
FROM CUSTOMER_2
Database Systems, 8th
Edition 8
Database Systems, 8th
Edition 9
Minus
• Combines rows from two queries
– Returns only the rows that appear in the first set
but not in the second
• Syntax: query MINUS query
– Example:
SELECT CUS_LNAME, CUS_FNAME,
CUS_INITIAL, CUS_AREACODE,
FROM CUSTOMER
MINUS
SELECT CUS_LNAME, CUS_FNAME,
CUS_INITIAL, CUS_AREACODE,
FROM CUSTOMER_2
Database Systems, 8th
Edition 10
Syntax Alternatives
• IN and NOT IN subqueries can be used in
place of INTERSECT
• Example:
SELECT CUS_CODE FROM CUSTOMER
WHERE CUS_AREACODE = ‘615’ AND
CUS_CODE IN (SELECT
DISTINCT CUS_CODE
FROM
INVOICE);
Database Systems, 8th
Edition 11
SQL Join Operators
• Join operation merges rows from two tables
and returns the rows with one of the following:
– Have common values in common columns
• Natural join
– Meet a given join condition
• Equality or inequality
– Have common values in common columns or
have no matching values
• Outer join
• Inner join: only return rows meeting criteria
Database Systems, 8th
Edition 12
Cross Join
• Performs relational product of two tables
– Also called Cartesian product
• Syntax:
– SELECT column-list FROM table1 CROSS JOIN
table2
• Perform a cross join that yields specified
attributes
Database Systems, 8th
Edition 13
Natural Join
• Returns all rows with matching values in the
matching columns
– Eliminates duplicate columns
• Used when tables share one or more common
attributes with common names
• Syntax:
SELECT column-list FROM table1 NATURAL
JOIN table2
Database Systems, 8th
Edition 14
Join USING Clause
• Returns only rows with matching values in the
column indicated in the USING clause
• Syntax:
SELECT column-list FROM table1 JOIN table2
USING (common-column)
• JOIN USING operand does not require table
qualifiers
– Oracle returns error if table name specified
Database Systems, 8th
Edition 15
JOIN ON Clause
• Used when tables have no common attributes
• Returns only rows that meet the join condition
– Typically includes equality comparison
expression of two columns
• Syntax: SELECT column-list FROM table1
JOIN table2 ON join-condition
Database Systems, 8th
Edition 16
Outer Joins
• Returns rows matching the join condition
• Also returns rows with unmatched attribute
values for tables to be joined
• Three types
– Left
– Right
– Full
• Left and right designate order in which tables
are processed
Database Systems, 8th
Edition 17
Outer Joins (continued)
• Left outer join
– Returns rows matching the join condition
– Returns rows in left side table with unmatched
values
– Syntax: SELECT column-list FROM table1 LEFT
[OUTER] JOIN table2 ON join-condition
• Right outer join
– Returns rows matching join condition
– Returns rows in right side table with unmatched
values
Database Systems, 8th
Edition 18
Outer Joins (continued)
• Full outer join
– Returns rows matching join condition
– Returns all rows with unmatched values in either
side table
– Syntax:
SELECT column-list
FROM table1 FULL [OUTER] JOIN table2
ON join-condition
Database Systems, 8th
Edition 19
Database Systems, 8th
Edition 20
Subqueries and Correlated Queries
• Often necessary to process data based on
other processed data
• Subquery is a query inside a query, normally
inside parentheses
• First query is the outer query
– Inside query is the inner query
• Inner query executed first
• Output of inner query used as input for outer
query
• Sometimes referred to as a nested query
Database Systems, 8th
Edition 21
WHERE Subqueries
• Most common type uses inner SELECT
subquery on right side of WHERE comparison
– Requires a subquery that returns only one single
value
• Value generated by subquery must be of
comparable data type
• Can be used in combination with joins
Database Systems, 8th
Edition 22
IN Subqueries
• Used when comparing a single attribute to a list
of values
Database Systems, 8th
Edition 23
HAVING Subqueries
• HAVING clause restricts the output of a
GROUP BY query
– Applies conditional criterion to the grouped rows
Database Systems, 8th
Edition 24
Multirow Subquery Operators:
ANY and ALL
• Allows comparison of single value with a list of
values using inequality comparison
• “Greater than ALL” equivalent to “greater than
the highest in list”
• “Less than ALL” equivalent to “less than lowest”
• Using equal to ANY operator equivalent to IN
operator
Database Systems, 8th
Edition 25
FROM Subqueries
• Specifies the tables from which the data will be
drawn
• Can use SELECT subquery in the FROM
clause
– View name can be used anywhere a table is
expected
Database Systems, 8th
Edition 26
Attribute List Subqueries
• SELECT statement uses attribute list to indicate
columns to project resulting set
– Columns can be attributes of base tables
– Result of aggregate function
• Attribute list can also include subquery
expression: inline subquery
– Must return one single value
• Cannot use an alias in the attribute list
Database Systems, 8th
Edition 27
Correlated Subqueries
• Subquery that executes once for each row in
the outer query
• Correlated because inner query is related to the
outer query
– Inner query references column of outer
subquery
• Can also be used with the EXISTS special
operator
Database Systems, 8th
Edition 28
SQL Functions
• Generating information from data often requires
many data manipulations
• SQL functions similar to functions in
programming languages
• Functions always use numerical, date, or string
value
• Value may be part of a command or attribute in
a table
• Function may appear anywhere in an SQL
statement
Database Systems, 8th
Edition 29
Date and Time Functions
• All SQL-standard DBMSs support date and
time functions
• Date functions take one parameter and return a
value
• Date/time data types implemented differently by
different DBMS vendors
• ANSI SQL standard defines date data types,
but not how data types are stored
Database Systems, 8th
Edition 30
Numeric Functions
• Grouped in different ways
– Algebraic, trigonometric, logarithmic, etc.
• Do not confuse with aggregate functions
– Aggregate functions operate over sets
– Numeric functions operate over single row
• Numeric functions take one numeric parameter
and return one value
Database Systems, 8th
Edition 31
Database Systems, 8th
Edition 32
String Functions
• String manipulations most used functions in
programming
• String manipulation function examples:
– Concatenation
– Printing in uppercase
– Finding length of an attribute
Database Systems, 8th
Edition 33
Conversion Functions
• Take a value of given data type and convert it
to the equivalent value in another data type
• Oracle conversion functions:
– TO_CHAR: takes a date value, converts to
character string
– TO_DATE: takes character string representing a
date, converts it to actual date in Oracle format
• SQL Server uses CAST and CONVERT
functions
Database Systems, 8th
Edition 34
Oracle Sequences
• MS Access AutoNumber data type fills a
column with unique numeric values
• Oracle sequences
– Independent object in the database
– Named, used anywhere a value expected
– Not tied to a table or column
– Generate numeric values that can be assigned
to any column in any table
– Created and deleted any time
Database Systems, 8th
Edition 35
Database Systems, 8th
Edition 36
Updatable Views
• Batch update routine pools multiple
transactions into a single batch
– Update master table field in a single operation
• Updatable view is a view that can be used to
update attributes in the base tables
• Not all views are updatable
– GROUP BY expressions or aggregate functions
cannot be used
– Cannot use set operators
– Most restrictions based on use of JOINs
Database Systems, 8th
Edition 37
Procedural SQL
• SQL does not support conditional execution
• Isolate critical code
– All applications access shared code
– Better maintenance and logic control
• Persistent stored module (PSM) is a block of
code containing:
– Standard SQL statements
– Procedural extensions
– Stored and executed at the DBMS server
Database Systems, 8th
Edition 38
Procedural SQL (continued)
• Procedural SQL (PL/SQL) makes it possible to:
– Store procedural code and SQL statements in
database
– Merge SQL and traditional programming
constructs
• Procedural code executed by DBMS when
invoked by end user
– Anonymous PL/SQL blocks and triggers
– Stored procedures and PL/SQL functions
Database Systems, 8th
Edition 39
Triggers
• Procedural SQL code automatically invoked by
RDBMS on data manipulation event
• Trigger definition:
– Triggering timing: BEFORE or AFTER
– Triggering event: INSERT, UPDATE, DELETE
– Triggering level:
• Statement-level trigger
• Row-level trigger
– Triggering action
• DROP TRIGGER trigger_name
Database Systems, 8th
Edition 40
Stored Procedures
• Named collection of procedural and SQL
statements
• Advantages
– Substantially reduce network traffic and increase
performance
• No transmission of individual SQL statements
over network
– Reduce code duplication by means of code
isolation and code sharing
• Minimize chance of errors and cost of application
development and maintenance
Database Systems, 8th
Edition 41
PL/SQL Processing with Cursors
• Cursor: special construct in procedural SQL to
hold data rows returned by SQL query
• Implicit cursor: automatically created when
SQL returns only one value
• Explicit cursor: holds the output of an SQL
statement that may return two or more rows
• Cursor-style processor retrieves data from
cursor one row at a time
– Current row copied to PL/SQL variables
Database Systems, 8th
Edition 42
PL/SQL Stored Functions
• Named group of procedural and SQL
statements that returns a value
• Syntax:
CREATE FUNCTION function_name
(argument IN data-type, …) RETURN data-
type [IS]
BEGIN
PL/SQL statements;
…
RETURN (value or expression);
END;
Database Systems, 8th
Edition 43
Embedded SQL
• Key differences between SQL and procedural
languages:
– Run-time mismatch
• SQL executed one instruction at a time
• Host language typically runs at client side in its
own memory space
– Processing mismatch
• Host language processes one data element at
a time
– Data type mismatch
Database Systems, 8th
Edition 44
Embedded SQL (continued)
• Embedded SQL framework defines:
– Standard syntax to identify embedded SQL code
within host language
– Standard syntax to identify host variables
– Communication area exchanges status and
error information between SQL and host
language
Database Systems, 8th
Edition 45
Database Systems, 8th
Edition 46
Embedded SQL (continued)
• Static SQL
– Embedded SQL in which programmer uses
predefined SQL statements and parameters
• End users of programs are limited to actions that
were specified in application programs
– SQL statements will not change while
application is running
Database Systems, 8th
Edition 47
Embedded SQL (continued)
• Dynamic SQL
– SQL statement is not known in advance, but instead
is generated at run time
– Program can generate SQL statements at run time
that are required to respond to ad hoc queries
– Attribute list and condition are not known until end
user specifies them
– Tends to be much slower than static SQL
– Requires more computer resources
Database Systems, 8th
Edition 48
Summary
• Relational set operators combine output of two
queries to generate new relation
• Operations that join tables classified as inner
joins and outer joins
• Natural join returns all rows with matching
values in the matching columns
– Eliminates duplicate columns
• Subqueries and correlated queries process
data based on other processed data
Database Systems, 8th
Edition 49
Summary (continued)
• Most subqueries are executed in serial fashion
• SQL functions are used to extract or transform
data
• Oracle sequences may be used to generate
values to be assigned to a record
• PL/SQL can be used to create triggers, stored
procedures, and PL/SQL functions
• A stored procedure is a named collection of
SQL statements
Database Systems, 8th
Edition 50
Summary (continued)
• When SQL statements return more than one
value inside the PL/SQL code, cursor is needed
• Embedded SQL uses SQL statements within an
application programming language

More Related Content

What's hot

ER model to Relational model mapping
ER model to Relational model mappingER model to Relational model mapping
ER model to Relational model mapping
Shubham Saini
 

What's hot (20)

SQL Join Basic
SQL Join BasicSQL Join Basic
SQL Join Basic
 
SQL Joins.pptx
SQL Joins.pptxSQL Joins.pptx
SQL Joins.pptx
 
Types Of Keys in DBMS
Types Of Keys in DBMSTypes Of Keys in DBMS
Types Of Keys in DBMS
 
Relational algebra ppt
Relational algebra pptRelational algebra ppt
Relational algebra ppt
 
SQL(DDL & DML)
SQL(DDL & DML)SQL(DDL & DML)
SQL(DDL & DML)
 
Procedure and Functions in pl/sql
Procedure and Functions in pl/sqlProcedure and Functions in pl/sql
Procedure and Functions in pl/sql
 
SQL JOIN
SQL JOINSQL JOIN
SQL JOIN
 
Aggregate function
Aggregate functionAggregate function
Aggregate function
 
Sql join
Sql  joinSql  join
Sql join
 
SQL, Embedded SQL, Dynamic SQL and SQLJ
SQL, Embedded SQL, Dynamic SQL and SQLJSQL, Embedded SQL, Dynamic SQL and SQLJ
SQL, Embedded SQL, Dynamic SQL and SQLJ
 
PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts
 
Joins in SQL
Joins in SQLJoins in SQL
Joins in SQL
 
Triggers
TriggersTriggers
Triggers
 
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with ExamplesDML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
 
Advanced SQL
Advanced SQLAdvanced SQL
Advanced SQL
 
Oracle Database Sequence
Oracle Database SequenceOracle Database Sequence
Oracle Database Sequence
 
ER model to Relational model mapping
ER model to Relational model mappingER model to Relational model mapping
ER model to Relational model mapping
 
Stored procedure
Stored procedureStored procedure
Stored procedure
 
Oracle Database Trigger
Oracle Database TriggerOracle Database Trigger
Oracle Database Trigger
 
Subqueries
SubqueriesSubqueries
Subqueries
 

Viewers also liked

Intro oracle10gexpress
Intro oracle10gexpressIntro oracle10gexpress
Intro oracle10gexpress
jatin Sareen
 
Oracle intro to designer abridged
Oracle intro to designer abridgedOracle intro to designer abridged
Oracle intro to designer abridged
FITSFSd
 
T sql語法之 cte 20140214
T sql語法之 cte 20140214T sql語法之 cte 20140214
T sql語法之 cte 20140214
LearningTech
 

Viewers also liked (20)

Advanced SQL - Lecture 6 - Introduction to Databases (1007156ANR)
Advanced SQL - Lecture 6 - Introduction to Databases (1007156ANR)Advanced SQL - Lecture 6 - Introduction to Databases (1007156ANR)
Advanced SQL - Lecture 6 - Introduction to Databases (1007156ANR)
 
Advanced SQL Webinar
Advanced SQL WebinarAdvanced SQL Webinar
Advanced SQL Webinar
 
OOW2016: Exploring Advanced SQL Techniques Using Analytic Functions
OOW2016: Exploring Advanced SQL Techniques Using Analytic FunctionsOOW2016: Exploring Advanced SQL Techniques Using Analytic Functions
OOW2016: Exploring Advanced SQL Techniques Using Analytic Functions
 
Exploring Advanced SQL Techniques Using Analytic Functions
Exploring Advanced SQL Techniques Using Analytic FunctionsExploring Advanced SQL Techniques Using Analytic Functions
Exploring Advanced SQL Techniques Using Analytic Functions
 
Step By Step How To Install Oracle XE
Step By Step How To Install Oracle XEStep By Step How To Install Oracle XE
Step By Step How To Install Oracle XE
 
Intro to Application Express
Intro to Application ExpressIntro to Application Express
Intro to Application Express
 
Tutorial Instalisasi Oracle 10g dan Setting User
Tutorial Instalisasi Oracle 10g dan Setting UserTutorial Instalisasi Oracle 10g dan Setting User
Tutorial Instalisasi Oracle 10g dan Setting User
 
Intro oracle10gexpress
Intro oracle10gexpressIntro oracle10gexpress
Intro oracle10gexpress
 
Data models
Data modelsData models
Data models
 
IBM Informix Database SQL Set operators and ANSI Hash Join
IBM Informix Database SQL Set operators and ANSI Hash JoinIBM Informix Database SQL Set operators and ANSI Hash Join
IBM Informix Database SQL Set operators and ANSI Hash Join
 
Oracle intro to designer abridged
Oracle intro to designer abridgedOracle intro to designer abridged
Oracle intro to designer abridged
 
Project management IT Project Management
Project management IT Project Management Project management IT Project Management
Project management IT Project Management
 
Chap01 introduction to project management
Chap01 introduction to project managementChap01 introduction to project management
Chap01 introduction to project management
 
Sql server ___________ (advance sql)
Sql server  ___________  (advance sql)Sql server  ___________  (advance sql)
Sql server ___________ (advance sql)
 
Time-Based Blind SQL Injection using Heavy Queries
Time-Based Blind SQL Injection using Heavy QueriesTime-Based Blind SQL Injection using Heavy Queries
Time-Based Blind SQL Injection using Heavy Queries
 
Oracle database introduction
Oracle database introductionOracle database introduction
Oracle database introduction
 
Managing Oracle Streams Using Enterprise Manager Grid Control
Managing Oracle Streams Using Enterprise Manager Grid ControlManaging Oracle Streams Using Enterprise Manager Grid Control
Managing Oracle Streams Using Enterprise Manager Grid Control
 
T sql語法之 cte 20140214
T sql語法之 cte 20140214T sql語法之 cte 20140214
T sql語法之 cte 20140214
 
Chap03 the project management process groups
Chap03 the project management process groupsChap03 the project management process groups
Chap03 the project management process groups
 
Transaction
TransactionTransaction
Transaction
 

Similar to Advanced sql

Fundamentals of Database ppt ch03
Fundamentals of Database ppt ch03Fundamentals of Database ppt ch03
Fundamentals of Database ppt ch03
Jotham Gadot
 
Using SQL Queries to Insert, Update, Delete, and View Data.ppt
Using SQL Queries to Insert, Update, Delete, and View Data.pptUsing SQL Queries to Insert, Update, Delete, and View Data.ppt
Using SQL Queries to Insert, Update, Delete, and View Data.ppt
MohammedJifar1
 
02 database oprimization - improving sql performance - ent-db
02  database oprimization - improving sql performance - ent-db02  database oprimization - improving sql performance - ent-db
02 database oprimization - improving sql performance - ent-db
uncleRhyme
 
MySQL Query And Index Tuning
MySQL Query And Index TuningMySQL Query And Index Tuning
MySQL Query And Index Tuning
Manikanda kumar
 

Similar to Advanced sql (20)

Introduction to structured query language (sql)
Introduction to structured query language (sql)Introduction to structured query language (sql)
Introduction to structured query language (sql)
 
15925 structured query
15925 structured query15925 structured query
15925 structured query
 
Lec 1 = introduction to structured query language (sql)
Lec 1 = introduction to structured query language (sql)Lec 1 = introduction to structured query language (sql)
Lec 1 = introduction to structured query language (sql)
 
Introduction to Structured Query Language (SQL) (1).ppt
Introduction to Structured Query Language (SQL) (1).pptIntroduction to Structured Query Language (SQL) (1).ppt
Introduction to Structured Query Language (SQL) (1).ppt
 
Session 1 - Databases-JUNE 2023.pdf
Session 1 - Databases-JUNE 2023.pdfSession 1 - Databases-JUNE 2023.pdf
Session 1 - Databases-JUNE 2023.pdf
 
Fundamentals of Database ppt ch03
Fundamentals of Database ppt ch03Fundamentals of Database ppt ch03
Fundamentals of Database ppt ch03
 
Views, Triggers, Functions, Stored Procedures, Indexing and Joins
Views, Triggers, Functions, Stored Procedures,  Indexing and JoinsViews, Triggers, Functions, Stored Procedures,  Indexing and Joins
Views, Triggers, Functions, Stored Procedures, Indexing and Joins
 
chapter03.ppt
chapter03.pptchapter03.ppt
chapter03.ppt
 
Using SQL Queries to Insert, Update, Delete, and View Data.ppt
Using SQL Queries to Insert, Update, Delete, and View Data.pptUsing SQL Queries to Insert, Update, Delete, and View Data.ppt
Using SQL Queries to Insert, Update, Delete, and View Data.ppt
 
The relational database model
The relational database modelThe relational database model
The relational database model
 
Sql performance tuning
Sql performance tuningSql performance tuning
Sql performance tuning
 
Unit I Database concepts - RDBMS & ORACLE
Unit I  Database concepts - RDBMS & ORACLEUnit I  Database concepts - RDBMS & ORACLE
Unit I Database concepts - RDBMS & ORACLE
 
02 database oprimization - improving sql performance - ent-db
02  database oprimization - improving sql performance - ent-db02  database oprimization - improving sql performance - ent-db
02 database oprimization - improving sql performance - ent-db
 
Relational databases.pdf
Relational databases.pdfRelational databases.pdf
Relational databases.pdf
 
MS SQL Server.ppt
MS SQL Server.pptMS SQL Server.ppt
MS SQL Server.ppt
 
MySQL JOIN & UNION
MySQL JOIN & UNIONMySQL JOIN & UNION
MySQL JOIN & UNION
 
MySQL Query And Index Tuning
MySQL Query And Index TuningMySQL Query And Index Tuning
MySQL Query And Index Tuning
 
Sql server introduction to sql server
Sql server introduction to sql server Sql server introduction to sql server
Sql server introduction to sql server
 
Sql Tutorials
Sql TutorialsSql Tutorials
Sql Tutorials
 
1. dml select statement reterive data
1. dml select statement reterive data1. dml select statement reterive data
1. dml select statement reterive data
 

More from Dhani Ahmad

Opportunities, threats, industry competition, and competitor analysis
Opportunities, threats, industry competition, and competitor analysisOpportunities, threats, industry competition, and competitor analysis
Opportunities, threats, industry competition, and competitor analysis
Dhani Ahmad
 
Information system
Information systemInformation system
Information system
Dhani Ahmad
 
Information resource management
Information resource managementInformation resource management
Information resource management
Dhani Ahmad
 

More from Dhani Ahmad (20)

Strategic planning
Strategic planningStrategic planning
Strategic planning
 
Strategic information system planning
Strategic information system planningStrategic information system planning
Strategic information system planning
 
Opportunities, threats, industry competition, and competitor analysis
Opportunities, threats, industry competition, and competitor analysisOpportunities, threats, industry competition, and competitor analysis
Opportunities, threats, industry competition, and competitor analysis
 
Information system
Information systemInformation system
Information system
 
Information resource management
Information resource managementInformation resource management
Information resource management
 
Types of islamic institutions and records
Types of islamic institutions and recordsTypes of islamic institutions and records
Types of islamic institutions and records
 
Islamic information seeking behavior
Islamic information seeking behaviorIslamic information seeking behavior
Islamic information seeking behavior
 
Islamic information management
Islamic information managementIslamic information management
Islamic information management
 
Islamic information management sources in islam
Islamic information management sources in islamIslamic information management sources in islam
Islamic information management sources in islam
 
The need for security
The need for securityThe need for security
The need for security
 
The information security audit
The information security auditThe information security audit
The information security audit
 
Security technologies
Security technologiesSecurity technologies
Security technologies
 
Security policy
Security policySecurity policy
Security policy
 
Security and personnel
Security and personnelSecurity and personnel
Security and personnel
 
Secure
SecureSecure
Secure
 
Risk management ii
Risk management iiRisk management ii
Risk management ii
 
Risk management i
Risk management iRisk management i
Risk management i
 
Privacy & security in heath care it
Privacy & security in heath care itPrivacy & security in heath care it
Privacy & security in heath care it
 
Physical security
Physical securityPhysical security
Physical security
 
Legal, ethical & professional issues
Legal, ethical & professional issuesLegal, ethical & professional issues
Legal, ethical & professional issues
 

Recently uploaded

Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
amitlee9823
 
FESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfFESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdf
MarinCaroMartnezBerg
 
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al BarshaAl Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
AroojKhan71
 
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in  KishangarhDelhi 99530 vip 56974 Genuine Escort Service Call Girls in  Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Call Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts Service
Call Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts ServiceCall Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts Service
Call Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Recently uploaded (20)

Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdfMarket Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
 
Invezz.com - Grow your wealth with trading signals
Invezz.com - Grow your wealth with trading signalsInvezz.com - Grow your wealth with trading signals
Invezz.com - Grow your wealth with trading signals
 
Discover Why Less is More in B2B Research
Discover Why Less is More in B2B ResearchDiscover Why Less is More in B2B Research
Discover Why Less is More in B2B Research
 
Introduction-to-Machine-Learning (1).pptx
Introduction-to-Machine-Learning (1).pptxIntroduction-to-Machine-Learning (1).pptx
Introduction-to-Machine-Learning (1).pptx
 
VIP Model Call Girls Hinjewadi ( Pune ) Call ON 8005736733 Starting From 5K t...
VIP Model Call Girls Hinjewadi ( Pune ) Call ON 8005736733 Starting From 5K t...VIP Model Call Girls Hinjewadi ( Pune ) Call ON 8005736733 Starting From 5K t...
VIP Model Call Girls Hinjewadi ( Pune ) Call ON 8005736733 Starting From 5K t...
 
(NEHA) Call Girls Katra Call Now 8617697112 Katra Escorts 24x7
(NEHA) Call Girls Katra Call Now 8617697112 Katra Escorts 24x7(NEHA) Call Girls Katra Call Now 8617697112 Katra Escorts 24x7
(NEHA) Call Girls Katra Call Now 8617697112 Katra Escorts 24x7
 
Smarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptxSmarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptx
 
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% SecureCall me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
 
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
 
FESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfFESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdf
 
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al BarshaAl Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
 
Generative AI on Enterprise Cloud with NiFi and Milvus
Generative AI on Enterprise Cloud with NiFi and MilvusGenerative AI on Enterprise Cloud with NiFi and Milvus
Generative AI on Enterprise Cloud with NiFi and Milvus
 
Carero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptxCarero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptx
 
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in  KishangarhDelhi 99530 vip 56974 Genuine Escort Service Call Girls in  Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
 
Halmar dropshipping via API with DroFx
Halmar  dropshipping  via API with DroFxHalmar  dropshipping  via API with DroFx
Halmar dropshipping via API with DroFx
 
Best VIP Call Girls Noida Sector 39 Call Me: 8448380779
Best VIP Call Girls Noida Sector 39 Call Me: 8448380779Best VIP Call Girls Noida Sector 39 Call Me: 8448380779
Best VIP Call Girls Noida Sector 39 Call Me: 8448380779
 
Zuja dropshipping via API with DroFx.pptx
Zuja dropshipping via API with DroFx.pptxZuja dropshipping via API with DroFx.pptx
Zuja dropshipping via API with DroFx.pptx
 
VidaXL dropshipping via API with DroFx.pptx
VidaXL dropshipping via API with DroFx.pptxVidaXL dropshipping via API with DroFx.pptx
VidaXL dropshipping via API with DroFx.pptx
 
Call Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts Service
Call Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts ServiceCall Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts Service
Call Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts Service
 
Digital Advertising Lecture for Advanced Digital & Social Media Strategy at U...
Digital Advertising Lecture for Advanced Digital & Social Media Strategy at U...Digital Advertising Lecture for Advanced Digital & Social Media Strategy at U...
Digital Advertising Lecture for Advanced Digital & Social Media Strategy at U...
 

Advanced sql

  • 1. Database Systems: Design, Implementation, and Management Eighth Edition Chapter 8 Advanced SQL
  • 2. Database Systems, 8th Edition 2 Objectives • In this chapter, you will learn: – About the relational set operators UNION, UNION ALL, INTERSECT, and MINUS – How to use the advanced SQL JOIN operator syntax – About the different types of subqueries and correlated queries – How to use SQL functions to manipulate dates, strings, and other data
  • 3. Database Systems, 8th Edition 3 Objectives (continued) • In this chapter, you will learn: (continued) – How to create and use updatable views – How to create and use triggers and stored procedures – How to create embedded SQL
  • 4. Database Systems, 8th Edition 4 Relational Set Operators • UNION • INTERSECT • MINUS • Work properly if relations are union- compatible – Names of relation attributes must be the same and their data types must be identical
  • 5. Database Systems, 8th Edition 5 UNION • Combines rows from two or more queries without including duplicate rows – Example: SELECT CUS_LNAME, CUS_FNAME, CUS_INITIAL, CUS_AREACODE, FROM CUSTOMER UNION SELECT CUS_LNAME, CUS_FNAME, CUS_INITIAL, CUS_AREACODE, FROM CUSTOMER_2 • Can be used to unite more than two queries
  • 6. Database Systems, 8th Edition 6 UNION ALL • Produces a relation that retains duplicate rows – Example query: SELECT CUS_LNAME, CUS_FNAME, CUS_INITIAL, CUS_AREACODE, FROM CUSTOMER UNION ALL SELECT CUS_LNAME, CUS_FNAME, CUS_INITIAL, CUS_AREACODE, FROM CUSTOMER_2; • Can be used to unite more than two queries
  • 7. Database Systems, 8th Edition 7 Intersect • Combines rows from two queries, returning only the rows that appear in both sets • Syntax: query INTERSECT query – Example query: SELECT CUS_LNAME, CUS_FNAME, CUS_INITIAL, CUS_AREACODE, FROM CUSTOMER INTERSECT SELECT CUS_LNAME, CUS_FNAME, CUS_INITIAL, CUS_AREACODE, FROM CUSTOMER_2
  • 9. Database Systems, 8th Edition 9 Minus • Combines rows from two queries – Returns only the rows that appear in the first set but not in the second • Syntax: query MINUS query – Example: SELECT CUS_LNAME, CUS_FNAME, CUS_INITIAL, CUS_AREACODE, FROM CUSTOMER MINUS SELECT CUS_LNAME, CUS_FNAME, CUS_INITIAL, CUS_AREACODE, FROM CUSTOMER_2
  • 10. Database Systems, 8th Edition 10 Syntax Alternatives • IN and NOT IN subqueries can be used in place of INTERSECT • Example: SELECT CUS_CODE FROM CUSTOMER WHERE CUS_AREACODE = ‘615’ AND CUS_CODE IN (SELECT DISTINCT CUS_CODE FROM INVOICE);
  • 11. Database Systems, 8th Edition 11 SQL Join Operators • Join operation merges rows from two tables and returns the rows with one of the following: – Have common values in common columns • Natural join – Meet a given join condition • Equality or inequality – Have common values in common columns or have no matching values • Outer join • Inner join: only return rows meeting criteria
  • 12. Database Systems, 8th Edition 12 Cross Join • Performs relational product of two tables – Also called Cartesian product • Syntax: – SELECT column-list FROM table1 CROSS JOIN table2 • Perform a cross join that yields specified attributes
  • 13. Database Systems, 8th Edition 13 Natural Join • Returns all rows with matching values in the matching columns – Eliminates duplicate columns • Used when tables share one or more common attributes with common names • Syntax: SELECT column-list FROM table1 NATURAL JOIN table2
  • 14. Database Systems, 8th Edition 14 Join USING Clause • Returns only rows with matching values in the column indicated in the USING clause • Syntax: SELECT column-list FROM table1 JOIN table2 USING (common-column) • JOIN USING operand does not require table qualifiers – Oracle returns error if table name specified
  • 15. Database Systems, 8th Edition 15 JOIN ON Clause • Used when tables have no common attributes • Returns only rows that meet the join condition – Typically includes equality comparison expression of two columns • Syntax: SELECT column-list FROM table1 JOIN table2 ON join-condition
  • 16. Database Systems, 8th Edition 16 Outer Joins • Returns rows matching the join condition • Also returns rows with unmatched attribute values for tables to be joined • Three types – Left – Right – Full • Left and right designate order in which tables are processed
  • 17. Database Systems, 8th Edition 17 Outer Joins (continued) • Left outer join – Returns rows matching the join condition – Returns rows in left side table with unmatched values – Syntax: SELECT column-list FROM table1 LEFT [OUTER] JOIN table2 ON join-condition • Right outer join – Returns rows matching join condition – Returns rows in right side table with unmatched values
  • 18. Database Systems, 8th Edition 18 Outer Joins (continued) • Full outer join – Returns rows matching join condition – Returns all rows with unmatched values in either side table – Syntax: SELECT column-list FROM table1 FULL [OUTER] JOIN table2 ON join-condition
  • 20. Database Systems, 8th Edition 20 Subqueries and Correlated Queries • Often necessary to process data based on other processed data • Subquery is a query inside a query, normally inside parentheses • First query is the outer query – Inside query is the inner query • Inner query executed first • Output of inner query used as input for outer query • Sometimes referred to as a nested query
  • 21. Database Systems, 8th Edition 21 WHERE Subqueries • Most common type uses inner SELECT subquery on right side of WHERE comparison – Requires a subquery that returns only one single value • Value generated by subquery must be of comparable data type • Can be used in combination with joins
  • 22. Database Systems, 8th Edition 22 IN Subqueries • Used when comparing a single attribute to a list of values
  • 23. Database Systems, 8th Edition 23 HAVING Subqueries • HAVING clause restricts the output of a GROUP BY query – Applies conditional criterion to the grouped rows
  • 24. Database Systems, 8th Edition 24 Multirow Subquery Operators: ANY and ALL • Allows comparison of single value with a list of values using inequality comparison • “Greater than ALL” equivalent to “greater than the highest in list” • “Less than ALL” equivalent to “less than lowest” • Using equal to ANY operator equivalent to IN operator
  • 25. Database Systems, 8th Edition 25 FROM Subqueries • Specifies the tables from which the data will be drawn • Can use SELECT subquery in the FROM clause – View name can be used anywhere a table is expected
  • 26. Database Systems, 8th Edition 26 Attribute List Subqueries • SELECT statement uses attribute list to indicate columns to project resulting set – Columns can be attributes of base tables – Result of aggregate function • Attribute list can also include subquery expression: inline subquery – Must return one single value • Cannot use an alias in the attribute list
  • 27. Database Systems, 8th Edition 27 Correlated Subqueries • Subquery that executes once for each row in the outer query • Correlated because inner query is related to the outer query – Inner query references column of outer subquery • Can also be used with the EXISTS special operator
  • 28. Database Systems, 8th Edition 28 SQL Functions • Generating information from data often requires many data manipulations • SQL functions similar to functions in programming languages • Functions always use numerical, date, or string value • Value may be part of a command or attribute in a table • Function may appear anywhere in an SQL statement
  • 29. Database Systems, 8th Edition 29 Date and Time Functions • All SQL-standard DBMSs support date and time functions • Date functions take one parameter and return a value • Date/time data types implemented differently by different DBMS vendors • ANSI SQL standard defines date data types, but not how data types are stored
  • 30. Database Systems, 8th Edition 30 Numeric Functions • Grouped in different ways – Algebraic, trigonometric, logarithmic, etc. • Do not confuse with aggregate functions – Aggregate functions operate over sets – Numeric functions operate over single row • Numeric functions take one numeric parameter and return one value
  • 32. Database Systems, 8th Edition 32 String Functions • String manipulations most used functions in programming • String manipulation function examples: – Concatenation – Printing in uppercase – Finding length of an attribute
  • 33. Database Systems, 8th Edition 33 Conversion Functions • Take a value of given data type and convert it to the equivalent value in another data type • Oracle conversion functions: – TO_CHAR: takes a date value, converts to character string – TO_DATE: takes character string representing a date, converts it to actual date in Oracle format • SQL Server uses CAST and CONVERT functions
  • 34. Database Systems, 8th Edition 34 Oracle Sequences • MS Access AutoNumber data type fills a column with unique numeric values • Oracle sequences – Independent object in the database – Named, used anywhere a value expected – Not tied to a table or column – Generate numeric values that can be assigned to any column in any table – Created and deleted any time
  • 36. Database Systems, 8th Edition 36 Updatable Views • Batch update routine pools multiple transactions into a single batch – Update master table field in a single operation • Updatable view is a view that can be used to update attributes in the base tables • Not all views are updatable – GROUP BY expressions or aggregate functions cannot be used – Cannot use set operators – Most restrictions based on use of JOINs
  • 37. Database Systems, 8th Edition 37 Procedural SQL • SQL does not support conditional execution • Isolate critical code – All applications access shared code – Better maintenance and logic control • Persistent stored module (PSM) is a block of code containing: – Standard SQL statements – Procedural extensions – Stored and executed at the DBMS server
  • 38. Database Systems, 8th Edition 38 Procedural SQL (continued) • Procedural SQL (PL/SQL) makes it possible to: – Store procedural code and SQL statements in database – Merge SQL and traditional programming constructs • Procedural code executed by DBMS when invoked by end user – Anonymous PL/SQL blocks and triggers – Stored procedures and PL/SQL functions
  • 39. Database Systems, 8th Edition 39 Triggers • Procedural SQL code automatically invoked by RDBMS on data manipulation event • Trigger definition: – Triggering timing: BEFORE or AFTER – Triggering event: INSERT, UPDATE, DELETE – Triggering level: • Statement-level trigger • Row-level trigger – Triggering action • DROP TRIGGER trigger_name
  • 40. Database Systems, 8th Edition 40 Stored Procedures • Named collection of procedural and SQL statements • Advantages – Substantially reduce network traffic and increase performance • No transmission of individual SQL statements over network – Reduce code duplication by means of code isolation and code sharing • Minimize chance of errors and cost of application development and maintenance
  • 41. Database Systems, 8th Edition 41 PL/SQL Processing with Cursors • Cursor: special construct in procedural SQL to hold data rows returned by SQL query • Implicit cursor: automatically created when SQL returns only one value • Explicit cursor: holds the output of an SQL statement that may return two or more rows • Cursor-style processor retrieves data from cursor one row at a time – Current row copied to PL/SQL variables
  • 42. Database Systems, 8th Edition 42 PL/SQL Stored Functions • Named group of procedural and SQL statements that returns a value • Syntax: CREATE FUNCTION function_name (argument IN data-type, …) RETURN data- type [IS] BEGIN PL/SQL statements; … RETURN (value or expression); END;
  • 43. Database Systems, 8th Edition 43 Embedded SQL • Key differences between SQL and procedural languages: – Run-time mismatch • SQL executed one instruction at a time • Host language typically runs at client side in its own memory space – Processing mismatch • Host language processes one data element at a time – Data type mismatch
  • 44. Database Systems, 8th Edition 44 Embedded SQL (continued) • Embedded SQL framework defines: – Standard syntax to identify embedded SQL code within host language – Standard syntax to identify host variables – Communication area exchanges status and error information between SQL and host language
  • 46. Database Systems, 8th Edition 46 Embedded SQL (continued) • Static SQL – Embedded SQL in which programmer uses predefined SQL statements and parameters • End users of programs are limited to actions that were specified in application programs – SQL statements will not change while application is running
  • 47. Database Systems, 8th Edition 47 Embedded SQL (continued) • Dynamic SQL – SQL statement is not known in advance, but instead is generated at run time – Program can generate SQL statements at run time that are required to respond to ad hoc queries – Attribute list and condition are not known until end user specifies them – Tends to be much slower than static SQL – Requires more computer resources
  • 48. Database Systems, 8th Edition 48 Summary • Relational set operators combine output of two queries to generate new relation • Operations that join tables classified as inner joins and outer joins • Natural join returns all rows with matching values in the matching columns – Eliminates duplicate columns • Subqueries and correlated queries process data based on other processed data
  • 49. Database Systems, 8th Edition 49 Summary (continued) • Most subqueries are executed in serial fashion • SQL functions are used to extract or transform data • Oracle sequences may be used to generate values to be assigned to a record • PL/SQL can be used to create triggers, stored procedures, and PL/SQL functions • A stored procedure is a named collection of SQL statements
  • 50. Database Systems, 8th Edition 50 Summary (continued) • When SQL statements return more than one value inside the PL/SQL code, cursor is needed • Embedded SQL uses SQL statements within an application programming language