Week 9 Advanced SQL

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 25

Chapter 8

Advanced SQL

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights
Reserved. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Learning Objectives (1 of 2)
• In this chapter, you will learn:
o How to use the advanced S QL JOIN operator syntax
o About the different types of subqueries and correlated queries
o How to use SQL functions to manipulate dates, strings, and other
data
o About the relational set operators UNION, UNION ALL, INTERSECT,
and MINUS

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Learning Objectives (2 of 2)
• In this chapter, you will learn:
o How to create and use views and updatable views
o How to create and use triggers and stored procedures
o How to create embedded S QL

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
SQL Join Operators
• Relational join operation merges rows from two tables and returns
rows with one of the following:
o Natural join - common values in common columns
o Equality or inequality - meet a given join condition
o Outer join – common values in common columns or no matching values
• Inner join: Rows that meet a given criterion are selected
o Equality condition (natural join or equijoin) or inequality condition (theta
join)
• Outer join: Returns matching rows and rows with unmatched attribute
values for one or both joined tables

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Table 8.1 – SQL Join Expression Styles (1 of 2)
JOIN JOIN SQL SYNTAX EXAMPLE DESCRIPTION
CLASSIFICATION TYPE
CROSS CROSS SELECT * Returns the Cartesian product of T1
JOIN FROM T1, T2 and T2 (old style)
SELECT * Returns the Cartesian product of T1
FROM T1 CROSS JOIN T2 and T2
INNER Old-style SELECT * Returns only the rows that meet the join
JOIN FROM T1, T2 condition in the WHERE clause (old
WHERE T1.C1=T2.C1 style); only
rows with matching values are selected
NATURAL SELECT * Returns only the rows with matching
JOIN FROM T1 NATURAL JOIN T2 values in the matching columns; the
matching columns must have the same
names and similar data types

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Table 8.1 – SQL Join Expression Styles (2 of 2)
JOIN SELECT * Returns only the rows with matching
USING FROM T1 JOIN T2 USING (C1) values in the columns indicated in the
USING clause
JOIN ON SELECT * Returns only the rows that meet the
FROM T1 JOIN T2 ON T1.C1=T2.C1 join Condition indicated in the ON
clause
OUTER LEFT SELECT * Returns rows with matching values and
JOIN FROM T1 LEFT OUTER JOIN T2 includes all rows from the left table
ON T1.C1=T2.C1 (T1) with unmatched values
RIGHT SELECT * Returns rows with matching values and
JOIN FROM T1 RIGHT OUTER JOIN T2 includes all rows from the right table
ON T1.C1=T2.C1 (T2) with unmatched Values
FULL SELECT * Returns rows with matching values and
JOIN FROM T1 FULL OUTER JOIN T2 includes all rows from both tables (T1
ON T1.C1=T2.C1 and T2) with unmatched Values

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Subqueries
• Subquery is a query inside another query
• Subquery can return:
o One single value - One column and one row
o A list of values - One column and multiple rows
o A virtual table - Multicolumn, multirow set of values
o No value - Output of the outer query might result in an error or a null
empty set

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Subqueries

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
WHERE Subqueries
• Uses inner SELECT subquery on the right side of a WHERE
comparison expression
• Value generated by the subquery must be of a comparable data
type
• If the query returns more than a single value, the DBMS will
generate an error

• Can be used in combination with joins

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
IN and HAVING Subqueries
• IN subqueries
o Used to compare a single attribute to a list of values

• HAVING subqueries
o HAVING clause restricts the output of a GROUP BY query by
applying conditional criteria to the grouped rows
o Unlike the WHERE clause, which filters rows before grouping,
HAVING filters groups after they have been formed.

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
IN and HAVING Subqueries
• WHERE Clause
o Purpose: Filters rows before any grouping operations.
o Usage: Used to specify conditions on individual rows.
o Execution: Applied before the GROUP BY clause.
o Syntax: SELECT ... FROM ... WHERE ...
• HAVING Clause
o Purpose: Filters groups after the grouping operation.
o Usage: Used to specify conditions on aggregated data (i.e., results of GROUP
BY)
o Execution: Applied after the GROUP BY clause.
o Syntax: SELECT ... FROM ... WHERE ... HAVING …..

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Multirow Subquery Operators: ANY and ALL
• ALL operator
o Allows comparison of a single value with a list of values returned by
the first subquery
• Uses a comparison operator other than equals
• ANY operator
o Allows comparison of a single value to a list of values and selects
only the rows for which the value is greater than or less than any
value in the list

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
FROM and Attribute List Subqueries
• FROM clause:
o Specifies the tables from which the data will be drawn
o Can use SELECT subquery
• SELECT statement uses attribute list to indicate what columns to
project in the resulting set
• Inline subquery
o Subquery expression included in the attribute list that must return
one value
• Column alias cannot be used in attribute list computation if alias is
defined in the same attribute list

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
FROM and Attribute List Subqueries
• Consider a scenario where you want to retrieve a list of employees along with the
total number of orders each employee has handled:
• In this example, the inline subquery (SELECT COUNT(*) FROM orders WHERE
orders.employee_id = employees.employee_id) is used to compute the total_orders
attribute for each employee
• The subquery must return a single value (the count of orders for each employee).
• Since the subquery is used within the attribute list, it is executed for each row of the
outer query to compute the total_orders value for that row
• it will create another column with for "total_orders"

employee_id employee_name total_orders


1 Alice 13
2 Bob 8
3 Charlie 4

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
SQL Functions (1 of 2)
• Function's that can be used for data manipulation, string
operations, mathematical calculations, date and time handling,
and more.
• Value may be part of a command or may be an attribute located in
a table
• Function may appear anywhere in an S QL statement where a
value or an attribute can be used

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
SQL Functions (2 of 2) String Functions
UPPER(): Converts a string to uppercase.
Aggregate Functions LOWER(): Converts a string to lowercase.
• COUNT(): Counts the number of rows or non-null LENGTH(): Returns the length of a string.
values in a column.
SUBSTR(): Extracts a substring from a string.
• SUM(): Calculates the sum of values in a column.
TRIM(): Removes leading and trailing spaces from
• AVG(): Computes the average of values in a
column. a string.
• MIN(): Finds the minimum value in a column. Date and Time Functions
• MAX(): Finds the maximum value in a column. CURRENT_TIMESTAMP: Returns the current date
Mathematical Functions and time.
• ABS(): Returns the absolute value of a number. DATE(): Extracts the date part from a date or
• ROUND(): Rounds a number to a specified number datetime value.
of decimal places.
TIME(): Extracts the time part from a datetime
• RANDOM(): Generates a random integer between
0 and 1. value.
• SQRT(): Computes the square root of a number. strftime(): Formats date and time values
according to a specified format
Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Relational Set Operators (1 of 3)
• SQL data manipulation commands are set-oriented
o Set-oriented: Operate over entire sets of rows and columns at once
• UNION, INTERSECT, and Except (MINUS) work properly when
relations are union-compatible
o Union-compatible: Number of attributes are the same and their
corresponding data types are alike
• UNION
o Combines rows from two or more queries without including duplicate
rows

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Relational Set Operators (2 of 3)
o Syntax - query UNION query
• UNION ALL
o Produces a relation that retains duplicate rows
o Can be used to unite more than two queries
• INTERSECT
o Combines rows from two queries, returning only the rows that
appear in both sets
o Syntax - query INTERSECT query

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Relational Set Operators (3 of 3)
• EXCEPT (MINUS)
o Combines rows from two queries and returns only the rows that
appear in the first set
o Syntax
• query EXCEPT query
• query MINUS query
• Syntax alternatives
o IN and NOT IN subqueries can be used in place of INTERSECT

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Relational Set Operators (3 of 3)

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Relational Set Operators (3 of 3)

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Virtual Tables: Creating a View
• View: Virtual table based on a SELECT query
• Base tables: Tables on which the view is based
• CREATE VIEW statement: Data definition command that stores
the subquery specification in the data dictionary
o CREATE VIEW command
• CREATE VIEW viewname AS SELECT query

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Virtual Tables: Creating a View
Create a virtual view named "it_employees" to show employees in the IT department
CREATE VIEW it_employees AS
SELECT employee_id, employee_name
FROM employees
WHERE department_id = 1;
This CREATE VIEW statement creates a virtual view named “it_employees”. It selects employee_id
and employee_name columns from the employees table where the department_id is equal to 1
(representing the IT department).
• After creating this virtual view, you can use it in your queries just like a regular table:
• Select all employees from the virtual view "it_employees"
SELECT * FROM it_employees;
• This query will retrieve all employees who belong to the IT department using the virtual view
it_employees

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Updatable Views
• Used to update attributes in any base tables used in the view
• Batch update routine: Pools multiple transactions into a single
batch to update a master table field in a single operation
• Updatable view restrictions
o GROUP BY expressions or aggregate functions cannot be used
o Set operators cannot be used
o JOINs or group operators cannot be used

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.
Thank you

Coronel/Morris, Database Systems: Design, Implementation, & Management, 12th Edition. © 2017 Cengage. All Rights Reserved.
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

You might also like