Advanced SQL Functions and Triggers
Advanced SQL Functions and Triggers
Database System Concepts - 7th Edition 5.2 ©Silberschatz, Korth and Sudarshan
Functions and Procedures
Database System Concepts - 7th Edition 5.3 ©Silberschatz, Korth and Sudarshan
Functions and Procedures
Database System Concepts - 7th Edition 5.4 ©Silberschatz, Korth and Sudarshan
Declaring SQL Functions
▪ Define a function that, given the name of a department, returns the count of
the number of instructors in that department.
create function dept_count (dept_name varchar(20))
returns integer
begin
declare d_count integer;
select count (* ) into d_count
from instructor
where instructor.dept_name = dept_name
return d_count;
end
▪ The function dept_count can be used to find the department names and
budget of all departments with more that 12 instructors.
select dept_name, budget
from department
where dept_count (dept_name ) > 12
Database System Concepts - 7th Edition 5.5 ©Silberschatz, Korth and Sudarshan
Table Functions
▪ The SQL standard supports functions that can return tables as results; such
functions are called table functions
▪ Example: Return all instructors in a given department
create function instructor_of (dept_name char(20))
returns table (
ID varchar(5),
name varchar(20),
dept_name varchar(20),
salary numeric(8,2))
return table
(select ID, name, dept_name, salary
from instructor
where instructor.dept_name = instructor_of.dept_name)
▪ Usage
select *
from table (instructor_of ('Music'))
Database System Concepts - 7th Edition 5.6 ©Silberschatz, Korth and Sudarshan
Language Constructs for Procedures & Functions
▪ SQL supports constructs that gives it almost all the power of a general-
purpose programming language.
• Warning: most database systems implement their own variant of the
standard syntax below.
▪ Compound statement: begin … end,
• May contain multiple SQL statements between begin and end.
• Local variables can be declared within a compound statements
▪ While and repeat statements:
• while boolean expression do
sequence of statements ;
end while
• repeat
sequence of statements ;
until boolean expression
end repeat
Database System Concepts - 7th Edition 5.9 ©Silberschatz, Korth and Sudarshan
Language Constructs (Cont.)
▪ For loop
• Permits iteration over all results of a query
▪ Example: Find the budget of all departments
Database System Concepts - 7th Edition 5.10 ©Silberschatz, Korth and Sudarshan
Language Constructs – if-then-else
Database System Concepts - 7th Edition 5.11 ©Silberschatz, Korth and Sudarshan
External Language Routines
Database System Concepts - 7th Edition 5.13 ©Silberschatz, Korth and Sudarshan
External Language Routines (Cont.)
Database System Concepts - 7th Edition 5.14 ©Silberschatz, Korth and Sudarshan
Security with External Language Routines
Database System Concepts - 7th Edition 5.15 ©Silberschatz, Korth and Sudarshan
Triggers
Database System Concepts - 7th Edition 5.16 ©Silberschatz, Korth and Sudarshan
Triggers
Database System Concepts - 7th Edition 5.17 ©Silberschatz, Korth and Sudarshan
Triggering Events and Actions in SQL
Database System Concepts - 7th Edition 5.18 ©Silberschatz, Korth and Sudarshan
Trigger to Maintain credits_earned value
Database System Concepts - 7th Edition 5.19 ©Silberschatz, Korth and Sudarshan
Statement Level Triggers
Database System Concepts - 7th Edition 5.20 ©Silberschatz, Korth and Sudarshan
When Not To Use Triggers
Database System Concepts - 7th Edition 5.21 ©Silberschatz, Korth and Sudarshan
When Not To Use Triggers (Cont.)
Database System Concepts - 7th Edition 5.22 ©Silberschatz, Korth and Sudarshan
Recursive Queries
Database System Concepts - 7th Edition 5.23 ©Silberschatz, Korth and Sudarshan
Recursion in SQL
▪ SQL:1999 permits recursive view definition
▪ Example: find which courses are a prerequisite, whether directly or
indirectly, for a specific course
with recursive rec_prereq(course_id, prereq_id) as (
select course_id, prereq_id
from prereq
union
select rec_prereq.course_id, prereq.prereq_id,
from rec_rereq, prereq
where rec_prereq.prereq_id = prereq.course_id
)
select ∗
from rec_prereq;
This example view, rec_prereq, is called the transitive closure of the prereq
relation
Database System Concepts - 7th Edition 5.24 ©Silberschatz, Korth and Sudarshan
The Power of Recursion
Database System Concepts - 7th Edition 5.25 ©Silberschatz, Korth and Sudarshan
The Power of Recursion
Database System Concepts - 7th Edition 5.26 ©Silberschatz, Korth and Sudarshan
Example of Fixed-Point Computation
Database System Concepts - 7th Edition 5.27 ©Silberschatz, Korth and Sudarshan
Slide Break
Reminders:
Extra credit for attending the seminar tomorrow at 2pm over Teams
Details are in the optional assignment on Canvas
HW3 due Sunday!
Please make sure to verify the result of your queries and make sure your SQL
file runs!
Withdraw deadline is November 3rd (next Monday)
Recursive Query Syntax: SQL Example
with recursive query_name as (
select columns from table where condition
union all
select [Link] from table t inner join query_name on condition
)
select * from query_name;
Advanced Aggregation Features
Database System Concepts - 7th Edition 5.30 ©Silberschatz, Korth and Sudarshan
Limit Activity
• In Postgres, adding “limit N” to a query gives you only the first N results of that query
• E.g. “select * from student limit 10”
• Typically only used when also sorting
• e.g. to get the top 10 students who have the most credits:
• select * from student order by tot_cred desc limit 10;
• Alternatively, can use the official SQL syntax “fetch first N rows only”:
• select * from student order by tot_cred desc fetch first 10 rows only;
• Note: MySQL uses “top N”:
• select top 10 * from student order by tot_cred desc;
• Construct a query which gets the top 5 highest-paid instructors in the form (name, salary)!
instructor(id, name, dept_name, salary)
Limit Activity
• Adding “limit N” to a query gives you only the first N results of that query
• E.g. “select * from student limit 10”
• Typically only used when also sorting
• e.g. to get the top 10 students who have the most credits:
• select * from student order by tot_cred desc limit 10;
• Alternatively, can use the official SQL syntax “fetch first N rows only”:
• select * from student order by tot_cred desc fetch first 10 rows only;
• Note: MySQL uses “top N”:
• select top 10 * from student order by tot_cred desc;
• Construct a query which gets the top 5 highest-paid instructors in the form (name, salary)!
instructor(id, name, dept_name, salary)
• Construct a query which gets the top 5 highest-paid instructors in the form (name, salary)!
instructor(id, name, dept_name, salary)
…But what do you notice if you replace the “limit 5” with “limit 6”?
Limit Activity
• Adding “limit N” to a query gives you only the first N results of that query
• E.g. “select * from student limit 10”
• Typically only used when also sorting
• e.g. to get the top 10 students who have the most credits:
• select * from student order by tot_cred desc limit 10;
• Alternatively, can use the official SQL syntax “fetch first N rows only”:
• select * from student order by tot_cred desc fetch first 10 rows only;
• Note: MySQL uses “top N”:
• select top 10 * from student order by tot_cred desc;
• Construct a query which gets the top 5 highest-paid instructors in the form (name, salary)!
instructor(id, name, dept_name, salary)
…But what do you notice if you replace the “limit 5” with “limit 6”?
Instructors 5 and 6 make the same amount! We didn’t consider whether we should include both
or neither in our top 5 list or which one we should include.
Limit Activity
• Adding “limit N” to a query gives you only the first N results of that query
• E.g. “select * from student limit 10”
• Typically only used when also sorting
• e.g. to get the top 10 students who have the most credits:
• select * from student order by tot_cred desc limit 10;
• Alternatively, can use the official SQL syntax “fetch first N rows only”:
• select * from student order by tot_cred desc fetch first 10 rows only;
• Note: MySQL uses “top N”:
• select top 10 * from student order by tot_cred desc;
• Construct a query which gets the top 5 highest-paid instructors in the form (name, salary)!
instructor(id, name, dept_name, salary)
…But what do you notice if you replace the “limit 5” with “limit 6”?
Instructors 5 and 6 make the same amount! We didn’t consider whether we should include both
or neither in our top 5 list or which one we should include.
Database System Concepts - 7th Edition 5.36 ©Silberschatz, Korth and Sudarshan
Ranking
▪ Ranking can be done using basic SQL aggregation, but resultant query is
very inefficient
select ID, (1 + (select count(*)
from student_grades B
where [Link] > [Link])) as s_rank
from student_grades A
order by s_rank;
Database System Concepts - 7th Edition 5.37 ©Silberschatz, Korth and Sudarshan
Ranking (Cont.)
Database System Concepts - 7th Edition 5.38 ©Silberschatz, Korth and Sudarshan
Ranking (Cont.)
Database System Concepts - 7th Edition 5.39 ©Silberschatz, Korth and Sudarshan
Ranking (Cont.)
▪ For a given constant n, the ranking the function ntile(n) takes the tuples in
each partition in the specified order, and divides them into n buckets with
equal numbers of tuples.
▪ E.g.,
select ID, ntile(4) over (order by GPA desc) as quartile
from student_grades;
Database System Concepts - 7th Edition 5.40 ©Silberschatz, Korth and Sudarshan
Rank Activity
Syntax example:
select ID, rank() over (order by GPA desc) as s_rank
from student_grades
order by s_rank
Eric note: it seems like this extra “order by” might be unnecessary in Postgres?
• Get the top 5 highest-paid instructors and rank them by their salary in the form (rank, name,
salary), ordered from highest salary to lowest salary, including ties if necessary
Rank Activity
Syntax example:
select ID, rank() over (order by GPA desc) as s_rank
from student_grades
order by s_rank
Eric note: it seems like this extra “order by” might be unnecessary in Postgres?
• Get the top 5 highest-paid instructors and rank them by their salary in the form (rank, name,
salary), ordered from highest salary to lowest salary, including ties if necessary
• First: rank the salaries
• Second: only select the top 5
Rank Activity
Syntax example:
select ID, rank() over (order by GPA desc) as s_rank
from student_grades
order by s_rank
Eric note: it seems like this extra “order by” might be unnecessary in Postgres?
• Get the top 5 highest-paid instructors and rank them by their salary in the form (rank, name,
salary), ordered from highest salary to lowest salary, including ties if necessary
• First: rank the salaries
select rank() over (order by salary desc) as s_rank, name, salary from instructor
• Get the top 5 highest-paid instructors and rank them by their salary in the form (rank, name,
salary), ordered from highest salary to lowest salary, including ties if necessary
• First: rank the salaries
select rank() over (order by salary desc) as s_rank, name, salary from instructor
select * from
(select rank() over (order by salary desc) as s_rank, name, salary from instructor)
where s_rank<=5
Rank Activity
Syntax example:
select ID, rank() over (order by GPA desc) as s_rank
from student_grades
order by s_rank
Eric note: it seems like this extra “order by” might be unnecessary in Postgres?
• Get the top 5 highest-paid instructors and rank them by their salary in the form (rank, name,
salary), ordered from highest salary to lowest salary, including ties if necessary
• First: rank the salaries
select rank() over (order by salary desc) as s_rank, name, salary from instructor
select * from
(select rank() over (order by salary desc) as s_rank, name, salary from instructor)
where s_rank<=5
• Get the top 5 highest-paid instructors and rank them by their salary in the form (rank, name,
salary), ordered from highest salary to lowest salary, including ties if necessary
• First: rank the salaries
select rank() over (order by salary desc) as s_rank, name, salary from instructor
select * from
(select rank() over (order by salary desc) as s_rank, name, salary from instructor)
where s_rank<=5
Nothing, because our ties in rank 5 mean our next rank is rank 7
Can use “select dense_rank()” instead to avoid skipping a rank number
ntile
If we wanted to split the instructors into two brackets of higher and lower salaries, we would do
the following:
select ntile(2) over (order by salary desc) as partition, name, salary from instructor
ntile(2) tells it to split into two partitions. For quartiles, you would use ntile(4).
Windowing
Database System Concepts - 7th Edition 5.48 ©Silberschatz, Korth and Sudarshan
Windowing
Database System Concepts - 7th Edition 5.49 ©Silberschatz, Korth and Sudarshan
Windowing (Cont.)
Database System Concepts - 7th Edition 5.50 ©Silberschatz, Korth and Sudarshan
Attendance
OLAP
Database System Concepts - 7th Edition 5.52 ©Silberschatz, Korth and Sudarshan
Data Analysis and OLAP
Database System Concepts - 7th Edition 5.53 ©Silberschatz, Korth and Sudarshan
Example sales relation
Database System Concepts - 7th Edition 5.55 ©Silberschatz, Korth and Sudarshan
Data Cube
Database System Concepts - 7th Edition 5.56 ©Silberschatz, Korth and Sudarshan
Cross Tabulation With Hierarchy
Database System Concepts - 7th Edition 5.58 ©Silberschatz, Korth and Sudarshan
Relational Representation of Cross-tabs
Database System Concepts - 7th Edition 5.59 ©Silberschatz, Korth and Sudarshan
Extended Aggregation to Support OLAP
▪ The cube operation computes union of group by’s on every subset of the
specified attributes
▪ Example relation for this section
sales(item_name, color, clothes_size, quantity)
▪ E.g., consider the query
select item_name, color, size, sum(number)
from sales
group by cube(item_name, color, size)
This computes the union of eight different groupings of the sales relation:
{ (item_name, color, size), (item_name, color),
(item_name, size), (color, size),
(item_name), (color),
(size), ()}
where ( ) denotes an empty group by list.
▪ For each grouping, the result contains the null value
for attributes not present in the grouping.
Database System Concepts - 7th Edition 5.60 ©Silberschatz, Korth and Sudarshan
Online Analytical Processing Operations
Database System Concepts - 7th Edition 5.61 ©Silberschatz, Korth and Sudarshan
Online Analytical Processing Operations
Database System Concepts - 7th Edition 5.62 ©Silberschatz, Korth and Sudarshan
Extended Aggregation (Cont.)
Database System Concepts - 7th Edition 5.63 ©Silberschatz, Korth and Sudarshan
Rollup Example
What happens when we run this?
Row with null dept_name, null name: sum column shows the sum of all salaries
Any row with non-null dept_name, null name: sum column shows the sum of salaries in
that dept_name
Rows with non-null dept_name and non-null name: sum column shows that individual’s
salary
Extended Aggregation (Cont.)
Database System Concepts - 7th Edition 5.67 ©Silberschatz, Korth and Sudarshan
Online Analytical Processing Operations
Database System Concepts - 7th Edition 5.68 ©Silberschatz, Korth and Sudarshan
OLAP Implementation
Database System Concepts - 7th Edition 5.69 ©Silberschatz, Korth and Sudarshan
OLAP Implementation (Cont.)
▪ Early OLAP systems precomputed all possible aggregates in order to
provide online response
• Space and time requirements for doing so can be very high
▪ 2n combinations of group by
• It suffices to precompute some aggregates, and compute others on
demand from one of the precomputed aggregates
▪ Can compute aggregate on (item_name, color) from an aggregate
on (item_name, color, size)
• For all but a few “non-decomposable” aggregates such as
median
• is cheaper than computing it from scratch
▪ Several optimizations available for computing multiple aggregates
• Can compute aggregate on (item_name, color) from an aggregate on
(item_name, color, size)
• Can compute aggregates on (item_name, color, size),
(item_name, color) and (item_name) using a single sorting
of the base data
Database System Concepts - 7th Edition 5.70 ©Silberschatz, Korth and Sudarshan
Accessing SQL from a Programming Language
Database System Concepts - 7th Edition 5.71 ©Silberschatz, Korth and Sudarshan
Accessing SQL from a Programming Language
▪ Not all queries can be expressed in SQL, since SQL does not provide
the full expressive power of a general-purpose language.
▪ Non-declarative actions -- such as printing a report, interacting with a
user, or sending the results of a query to a graphical user interface --
cannot be done from within SQL.
Database System Concepts - 7th Edition 5.72 ©Silberschatz, Korth and Sudarshan
Accessing SQL from a Programming Language (Cont.)
Database System Concepts - 7th Edition 5.73 ©Silberschatz, Korth and Sudarshan
Python
How do we access Postgres with Python?
Below slides are helpful for other languages
These slides are not covered in class (and do not have material that is on the exam), but
may be useful if you’re interested in using a DBMS with Java or Embedded SQL
JDBC
Database System Concepts - 7th Edition 5.77 ©Silberschatz, Korth and Sudarshan
JDBC
Database System Concepts - 7th Edition 5.78 ©Silberschatz, Korth and Sudarshan
JDBC Code
Database System Concepts - 7th Edition 5.79 ©Silberschatz, Korth and Sudarshan
JDBC Code for Older Versions of Java/JDBC
public static void JDBCexample(String dbid, String userid, String passwd)
{
try {
[Link] ("[Link]");
Connection conn = [Link](
"jdbc:oracle:thin:@[Link]:univdb", userid, passwd);
Statement stmt = [Link]();
… Do Actual Work ….
[Link]();
[Link]();
}
catch (SQLException sqle) {
[Link]("SQLException : " + sqle);
}
}
NOTE: [Link] is not required from JDBC 4 onwards. The try with
resources syntax in prev slide is preferred for Java 7 onwards.
Database System Concepts - 7th Edition 5.80 ©Silberschatz, Korth and Sudarshan
JDBC Code (Cont.)
▪ Update to database
try {
[Link](
"insert into instructor values('77987', 'Kim', 'Physics', 98000)");
} catch (SQLException sqle)
{
[Link]("Could not insert tuple. " + sqle);
}
▪ Execute query and fetch and print results
ResultSet rset = [Link](
"select dept_name, avg (salary)
from instructor
group by dept_name");
while ([Link]()) {
[Link]([Link]("dept_name") + " " +
[Link](2));
}
Database System Concepts - 7th Edition 5.81 ©Silberschatz, Korth and Sudarshan
JDBC SUBSECTIONS
Database System Concepts - 7th Edition 5.82 ©Silberschatz, Korth and Sudarshan
JDBC Code Details
Database System Concepts - 7th Edition 5.83 ©Silberschatz, Korth and Sudarshan
Prepared Statement
Database System Concepts - 7th Edition 5.84 ©Silberschatz, Korth and Sudarshan
SQL Injection
Database System Concepts - 7th Edition 5.85 ©Silberschatz, Korth and Sudarshan
Metadata Features
▪ ResultSet metadata
▪ [Link] executing query to get a ResultSet rs:
• ResultSetMetaData rsmd = [Link]();
for(int i = 1; i <= [Link](); i++) {
[Link]([Link](i));
[Link]([Link](i));
}
▪ How is this useful?
Database System Concepts - 7th Edition 5.86 ©Silberschatz, Korth and Sudarshan
Metadata (Cont)
▪ Database metadata
▪ DatabaseMetaData dbmd = [Link]();
// Arguments to getColumns: Catalog, Schema-pattern, Table-pattern,
// and Column-Pattern
// Returns: One row for each column; row has a number of attributes
// such as COLUMN_NAME, TYPE_NAME
// The value null indicates all Catalogs/Schemas.
// The value “” indicates current catalog/schema
// The value “%” has the same meaning as SQL like clause
ResultSet rs = [Link](null, "univdb", "department", "%");
while( [Link]()) {
[Link]([Link]("COLUMN_NAME"),
[Link]("TYPE_NAME");
}
▪ And where is this useful?
Database System Concepts - 7th Edition 5.87 ©Silberschatz, Korth and Sudarshan
Metadata (Cont)
▪ Database metadata
▪ DatabaseMetaData dbmd = [Link]();
// Arguments to getTables: Catalog, Schema-pattern, Table-pattern,
// and Table-Type
// Returns: One row for each table; row has a number of attributes
// such as TABLE_NAME, TABLE_CAT, TABLE_TYPE, ..
// The value null indicates all Catalogs/Schemas.
// The value “” indicates current catalog/schema
// The value “%” has the same meaning as SQL like clause
// The last attribute is an array of types of tables to return.
// TABLE means only regular tables
ResultSet rs = [Link] (“”, "", “%", new String[] {“TABLES”});
while( [Link]()) {
[Link]([Link](“TABLE_NAME“));
}
▪ And where is this useful?
Database System Concepts - 7th Edition 5.88 ©Silberschatz, Korth and Sudarshan
Finding Primary Keys
while([Link]()){
// KEY_SEQ indicates the position of the attribute in
// the primary key, which is required if a primary key has multiple
// attributes
[Link]([Link](“KEY_SEQ”),
[Link]("COLUMN_NAME");
}
Database System Concepts - 7th Edition 5.89 ©Silberschatz, Korth and Sudarshan
Transaction Control in JDBC
Database System Concepts - 7th Edition 5.90 ©Silberschatz, Korth and Sudarshan
Other JDBC Features
Database System Concepts - 7th Edition 5.91 ©Silberschatz, Korth and Sudarshan
JDBC Resources
Database System Concepts - 7th Edition 5.92 ©Silberschatz, Korth and Sudarshan
SQLJ
Database System Concepts - 7th Edition 5.93 ©Silberschatz, Korth and Sudarshan
ODBC
Database System Concepts - 7th Edition 5.94 ©Silberschatz, Korth and Sudarshan
ODBC
Database System Concepts - 7th Edition 5.95 ©Silberschatz, Korth and Sudarshan
Embedded SQL
Database System Concepts - 7th Edition 5.96 ©Silberschatz, Korth and Sudarshan
Embedded SQL (Cont.)
▪ Before executing any SQL statements, the program must first connect to
the database. This is done using:
EXEC-SQL connect to server user user-name using password;
Here, server identifies the server to which a connection is to be
established.
▪ Variables of the host language can be used within embedded SQL
statements. They are preceded by a colon (:) to distinguish from SQL
variables (e.g., :credit_amount )
▪ Variables used as above must be declared within DECLARE section, as
illustrated below. The syntax for declaring the variables, however, follows
the usual host language syntax.
EXEC-SQL BEGIN DECLARE SECTION}
int credit-amount ;
EXEC-SQL END DECLARE SECTION;
Database System Concepts - 7th Edition 5.97 ©Silberschatz, Korth and Sudarshan
Embedded SQL (Cont.)
Database System Concepts - 7th Edition 5.98 ©Silberschatz, Korth and Sudarshan
Embedded SQL (Cont.)
Database System Concepts - 7th Edition 5.99 ©Silberschatz, Korth and Sudarshan
Embedded SQL (Cont.)
Database System Concepts - 7th Edition 5.100 ©Silberschatz, Korth and Sudarshan
Updates Through Embedded SQL
Database System Concepts - 7th Edition 5.101 ©Silberschatz, Korth and Sudarshan
End of Chapter 5
Database System Concepts - 7th Edition 5.102 ©Silberschatz, Korth and Sudarshan