Advanced SQL
Advanced SQL
2
Definition of Some Clause
(F <comp> some r) t r such that (F <comp> t)
Where <comp> can be:
0
(5< some 5 ) = true
(5 < some tuple in the relation)
6
0
(5< some 5 ) = false
0
(5 = some 5 ) = true
0
(5 some 5 ) = true (since 0 5)
Note (= some) in
However ( some) not in
3
Definition of all Clause
0
(5< all 5 ) = false
6
6
(5< all 10 ) = true
4
(5 = all 5 ) = false
4
(5 all 6 ) = true (since 5 4 and 5 6)
( all) not in
however (= all) in
4
Example Query
Find the names of all branches that have greater assets than all of the
branches located in Brooklyn.
select branch-name
from branch
where assets > all
(select assets
from branch
where branch-city = ‘Brooklyn’)
5
Example Query
Find the names of branches that have greater assets than some of the
branches located in Brooklyn.
.
select branch-name
from branch
where assets > some
(select assets
from branch
where branch-city = ‘Brooklyn’)
Same query as
select distinct T.branch-name
from branch as T, branch as S
where T.assets > S.assets and
S.branch-city = ‘Brooklyn’
6
Test for Absence of Duplicate rows
The unique construct tests whether a sub-query has any duplicate
tuples in its result.
Find all customers who have at most one account at the Perryridge
branch.
select T.customer-name
from depositor as T
where unique (
select R.customer-name
from account, depositor as R
where T.customer-name = R.customer-name and
R.account-number = account.account-number and
account.branch-name = ‘Perryridge’)
7
Table creation
8
Integrity rules in table definition
not null
primary key (A1, ..., An)
check (P), where P is a predicate
9
Domain Constraints
Integrity constraints guard against accidental damage to the database, by
ensuring that authorized changes to the database do not result in a loss of data
consistency.
Domain constraints are the most elementary form of integrity constraint.
They test values inserted in the database, and test queries to ensure that the
comparisons make sense.
New domains can be created from existing data types.
10
Integrity constraints
11
One relation constraints
not null
primary key
unique
check (P ), where P is a predicate
12
Not Null constraint
13
Constraints on one relation
14
Check clause
15
Referential integrity
Ensures that a value that appears in one relation for a given set of
attributes also appears for a certain set of attributes in another relation.
– Example: If “Perryridge” is a branch name appearing in one of the
tuples in the account relation, then there exists a tuple in the branch
relation for branch “Perryridge”.
Primary, candidate keys and foreign keys are defined as part of SQL
create table clause:
– primary key clause list attributes that form a primary key.
– unique key clause list attributes that are candidate keys.
– foreign key clause list attributes that are foreign keys and the name
of relation that is referred. By default refere primary key attribute in
referred relation.
16
Referential Integrity in SQL – Example
17
Referential Integrity in SQL – Example(1)
18
Assertions
19
Assertion example
Every loan has at least one borrower who maintains an account with a
minimum balance or $1000.00
create assertion balance_constraint check
(not exists (
select *
from loan
where not exists (
select *
from borrower, depositor, account
where loan.loan_number = borrower.loan_number
and borrower.customer_name = depositor.customer_name
and depositor.account_number = account.account_number
and account.balance >= 1000)))
20
Assertion example (1)
The sum of all loan amounts for each branch must be less than the
sum of all account balances at the branch.
.
create assertion sum_constraint check
(not exists (select *
from branch
where (select sum(amount )
from loan
where loan.branch_name =
branch.branch_name )
>= (select sum (balance )
from account
where loan.branch_name =
branch.branch_name )))
21
Authorization
Forms of authorization on parts of the database:
22
Authorization specification in SQL
grant clause for autorization
grant <list of privilegies>
on <name relation or view> to <user list>
<user list> е:
– user-id
– public, to all valid users
– role
Granted privileges on views do not means granted privileges to
relations
Authority that gives privileges must have the same or greater
privileges (administrator of DB)
23
Privileges in SQL
select: allows read access to relation,or the ability to query using the
view
– Example: grant users U1, U2, and U3 select authorization on the
branch relation:
grant select on branch to U1, U2, U3
insert: the ability to insert tuples
update: the ability to update using the SQL update statement
delete: the ability to delete tuples.
references: ability to declare foreign keys when creating relations.
usage: In SQL-92; authorizes a user to use a specified domain
all privileges: used as a short form for all the allowable privileges
24
Revoking Authorization in SQL
The revoke statement is used to revoke authorization.
revoke<privilege list>
on <relation name or view name> from <user list> [restrict|
cascade]
Example:
revoke select on branch from U1, U2, U3 cascade
< privilege list > could be all for all privileges.
If<revoke-list> include public, all the user lose privileges except
those granted it explicitly
If the same privilege was granted twice to the same user by different
grantees, the user may retain the privilege after the revocation.
All privileges that depend on the privilege being revoked are also
revoked.
25
SQL Views
SQL view is virtual table constructed of other real tables in DB. Do not
have own data, in the time of usage (execution) take data from existing
tables or views.
Role
– Hide columns or rows
– Show results of calculations
– Ease complex queries in SQL
– Different levels of access to same tables
– Different triggers for different views on the same table
v name of view
query expression is valid predicate (expression)
26
Example creating view
27
Update of a View
Update view is allowed if:
– View is based on one table without columns with null values in view
– Updates on more complex views can be difficult or may even be impossible to
evaluate, and are disallowed.
– Most SQL implementations allow updates only on simple views (without
aggregates) defined on a single relation
Example: Create a view of all loan data in the loan relation, hiding the amount
attribute
create view branch-loan as
select branch-name, loan-number
from loan
Add new row to view branch-loan
insert into branch-loan
values (‘Perryridge’, ‘L-307’)
This insertion must be represented by the insertion of the row
(‘L-307’, ‘Perryridge’, null)
in the table loan on which the view is based 28
Triggers
29
Use of triggers
On INSERT clause, virtual table with name INSERTED for table authors with related
attributes is cdreated.
On insert each row in the table authors trigger is executed that write massage: New author
“name” is added
31
Example (1)
For trigger testing on the command line of Query Analyzer (Start -> Programs ->
Microsoft SQL Server 7.0 -> Query Analyzer) and connection to the database:
USE pubs
GO
SET NOCOUNT ON
INSERT INTO authors(au_id, au_lname, au_fname, phone, address, city, state, zip, contract)
VALUES('172-85-4534', 'Doe', 'John', '123456', '1 Black Street', 'Doeville', 'CA', '90210', 0)
32
Example (3)
33
Example UPDATE
CREATE TRIGGER trig_updateAuthor
ON authors
FOR UPDATE
AS
PRINT 'Name changed from "' + @oldName + '" to "' + @newName + '"'
Се креираат две нови променливи: oldName (ќе содржи вредности пред промената) и newName ќе содржи
вредности по промената. UPDATE тригер проверува дали "au_fName" и "au_lName“ полиња се ажурирани со
"UPDATE" SQL query. Се извршува тригер "trig_updateAuthor" trigger. Ако нема ажурирање се враќа контрола на
SQL server. Ако има ажурирање и на двете полиња au_fName и au_lName се земаат нивни стари имиња од
табелата DELETED I se ставаат во променливата oldName, додека новите ажурирани вредности се земаат од
34
тавелата INSERTED и се ставаат во newName. Потоа и двете вредности се печатат
Example trigger constraint definition
36
Stored Procedures
For creating
– ORACLE in PL/SQL or Java
– SQL Server inTRANSACT-SQL
For calling:
– In ORACLE PL/SQL or Java
– In scripting languages JavaScript, VBScript
– On SQL command prompt (SQL*Plus ORACLE, Query Analyzer SQL Server
37
Advantages of stored procedure
38
Creating and calling stored procedure
39
Example 1. (select)
Повикување :
exec SelectPerson2 ‘Sonja‘, ‘Georgieva ’
41
Example 3 (insert)
Повикување:
exec InsertPerson 110,‘Igor', ‘Stojanovski'
42
Example
43
Performers (PerformerID, PerformerName, Street, City, State, Zip, ActivityID)
Triggers
Are code (program) called by DBMS only on INSERT, UPDATE and
DELITE commands
Related are to specific table or view
Depending on DBMS could be more than one trigger for one table or view
With one call of trigger (e.g for INSERT) other trigger can be invoked
Stored procedures
Code (program) called by user or DB administrator
Is related to database nor specific table or view
Could be used also with INSERT, UPDATE and DELITE commands
Could be used for administration, statistic purposes, but also as a part of an
application
45