You are on page 1of 45

Advanced SQL

Some specificities of SET operations

 Example used database

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

 F <comp> all r t r (F <comp> t)

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

 SQL table (relation) is defined by create table comand:


create table r (A1 D1, A2 D2, ..., An Dn,
(integrity-constraint1),
...,
(integrity-constraintk))
– r name of relation
– each Ai is name of attribute in the relation schema of r
– Di is a type of data in the domain of values for attribute Ai
 Example:
create table branch
(branch-name char(15) not null,
branch-city char(30),
assets integer)

8
Integrity rules in table definition

 not null
 primary key (A1, ..., An)
 check (P), where P is a predicate

 Example: we declare branch-name as primary key for branch and ensure


assets >=0.
 create table branch
(branch-name char(15),
branch-city char(30)
assets integer,
primary key (branch-name),
check (assets >= 0))

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.

– example: create domain Dollars numeric(12, 2)


create domain Pounds numeric(12,2)
 We cannot assign or compare a value of type Dollars to a value of type
Pounds
– However, we can convert type as below
(cast r.A as Pounds)
(Should also multiply by the dollar-to-pound conversion-rate)

10
Integrity constraints

 Possibility of reduction of errors

– account must be greater than $10,000.00


– salary must be les than $4.00 per hour
– Client must have non-null phone number

11
One relation constraints

 not null
 primary key
 unique
 check (P ), where P is a predicate

12
Not Null constraint

 We define branch_name за branch is not null


branch_name char(15) not null

 We define domain on Dollars to be not null

create domain Dollars numeric(12,2) not null

13
Constraints on one relation

 unique ( A1, A2, …, Am)


 Asserts that attributes
A1, A2, … Am
form the key.
 Candidate keys can have null values (contrary to primary key)

14
Check clause

 check (P ), where P е predicate

Example (as before)

create table branch


(branch_name char(15),
branch_city char(30),
assets integer,
primary key (branch_name),
check (assets >= 0))

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

create table customer


(customer_name char(20),
customer_street char(30),
customer_city char(30),
primary key (customer_name ))

create table branch


(branch_name char(15),
branch_city char(30),
assets numeric(12,2),
primary key (branch_name ))

17
Referential Integrity in SQL – Example(1)

create table account


(account_number char(10),
branch_name char(15),
balance integer,
primary key (account_number),
foreign key (branch_name) references branch )

create table depositor


(customer_name char(20),
account_number char(10),
primary key (customer_name, account_number),
foreign key (account_number ) references account,
foreign key (customer_name ) references customer )

18
Assertions

 An assertion is a predicate expressing a condition that we wish the


database always to satisfy.
 An assertion in SQL takes the form
create assertion <assertion-name> check <predicate>
 When an assertion is made, the system tests it for validity, and tests it
again on every update that may violate the assertion
– This testing may introduce a significant amount of overhead;
hence assertions should be used with great care.
 Asserting
for all X, P(X)
is achieved in a round-about fashion using
not exists X such that not P(X)

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:

 Read authorization - allows reading, but not modification of data.


 Insert authorization - allows insertion of new data, but not modification
of existing data.
 Update authorization - allows modification, but not deletion of data.
 Delete authorization - allows deletion of data

Forms of authorization to modify the database schema:


 Index authorization - allows creation and deletion of indices.
 Resources authorization - allows creation of new relations.
 Alteration authorization - allows addition or deletion of attributes in a
relation.
 Drop authorization - allows deletion of relations.

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

create view v as <query expression>

v name of view
query expression is valid predicate (expression)

26
Example creating view

 View containing all the branches and their customers


create view all-customer as
(select branch-name, customer-name
from depositor, account
where depositor.account-number = account.account-number)
union
(select branch-name, customer-name
from borrower, loan
where borrower.loan-number = loan.loan-number)
 Query on view
select customer-name
from all-customer
where branch-name = ‘Perryridge’

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

 A trigger is a statement that is executed automatically by the system as a


side effect of a modification to the database.
 To design a trigger mechanism, we must:
– Specify the conditions under which the trigger is to be executed.
– Specify the actions to be taken when the trigger executes.
 It is related to table and views
 Tree types of trigger: BEFORE, INSTEAD OF and AFTER
 All three are declared for clauses INSERT, UPDATE, and/or DELETE
 When activated trigger in DBMS enable
– Old and new values for UPDATE
– New values for INSERTS
– Old values for DELETE

29
Use of triggers

 Enable more complex default values


 Enable control for restrictions and definition of default values
 Update views
 Enable referential integrity
 SQL Server support 6 types of triggers (only for AFTER and INSTEAD
OF trigger)

Generic syntax (reduced) for trigger

CREATE TRIGGER trigger_name


ON table_or_view_name
AFTER | BEFORE | INSTEAD OF
INSERT | UPDATE | DELETE
AS
trigger_code
30
Example

CREATE TRIGGER trig_addAuthor Create new trigger with name


trig_addAuthor for table authors activated
ON authors on INSERT
FOR INSERT
Definition could be in the same time for
AS INSERT, DELITE, UPDATE

-- Get the first and last name of new author


DECLARE @newName VARCHAR(100)
SELECT @newName = (SELECT au_fName + ‘ ' + au_lName FROM Inserted)

-- Print the name of the new author


PRINT 'New author "' + @newName + '" added.'

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)

 pubs is name of database in which there is table authors

 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

DECLARE @oldName VARCHAR(100)


DECLARE @newName VARCHAR(100)

IF NOT UPDATE(au_fName) AND NOT UPDATE(au_lName)


BEGIN
RETURN
END

SELECT @oldName = (SELECT au_fName + ' ' + au_lName FROM Deleted)


SELECT @newName = (SELECT au_fName + ' ' + au_lName FROM Inserted)

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

Arenas (ArenaID, ArenaName, City, ArenaCapacity), ArenaCapacity >= 5000

CREATE TRIGGER minseating ON Arenas /*trigger associated to Arenas*/


FOR INSERT /*executed after an insert*/
AS
DECLARE @capacity as int /*variable declarations */

SELECT @capacity = ArenaCapacity /* get values inserted */


FROM inserted
if @capacity < 5000
BEGIN
ROLLBACK /*undo the insert*/
Print 'Arena too small‘ /*message for the user*/
END
35
Example trigger for referential integrity

36
Stored Procedures

 Is programm stored on the server with database is compiled in moment of usage


 Could receive parameters and return values
 Could be called from:
– standard langue
– scripting language
– SQL command prompt

 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

 More secure, because they are stored on the DB server


 SQL is optimized by DBMS compiler
 Less traffic in network
 Division of the code results in:
– Less work
– Standardisation in processing
– Specialization of the development team

38
Creating and calling stored procedure

CREATE PROCEDURE proc_name


@Parameter1 type(x),
@Parameter2 type(x)
.....
AS proc_code
……

exec proc_name [@param1 = ]value1, …

Variations in SQL in various DBMS

39
Example 1. (select)

CREATE TABLE Person


(
PID numeric(9) PRIMARY KEY,
Name char(15) NOT NULL,
Surname char(15), calling
City char(15), exec SelectPerson ‘Sonja'
Faculty char(10)
)
CREATE PROCEDURE SelectPerson1
@Criteria varchar(30)
AS
Select PID, Name, Surname
FROM Person
WHERE ( Name = @Criteria)
40
Example 2

CREATE PROCEDURE SelectPerson2


@Criteria1 varchar(30),
@Criteria2 varchar(30)
AS
Select PID, Name, Surname
FROM Person
WHERE ( (Name = @Criteria1) OR (Surname = @Criteria2) )

Повикување :
exec SelectPerson2 ‘Sonja‘, ‘Georgieva ’

41
Example 3 (insert)

CREATE PROCEDURE InsertPerson


@ID int,
@Ime varchar(20),
@Prezim echar(20)
AS
INSERT INTO Person(PID, Name, Surname)
VALUES (@ID, @Ime, @Prezime)

Повикување:
exec InsertPerson 110,‘Igor', ‘Stojanovski'

42
Example

Performers (PerformerID, PerformerName, Street, City, State, Zip)


Description: Performer is inserted only if there is no name and zip in the table

43
Performers (PerformerID, PerformerName, Street, City, State, Zip, ActivityID)

CREATE PROCEDURE performer_Insert


(@ID int, IF @Count > 0
@NewName char(20), BEGIN
@street char(20), PRINT 'Performer is already in the
Database'
@city char(15),
RETURN
@state char(2), END
@NewZip int) BEGIN TRANSACTION
AS INSERT INTO
DECLARE @Count as int Performers(PerformerID,
PerformerName, Street, City, State, Zip)
VALUES (@ID, @NewName, @street,
SELECT @Count = Count(*) @city, @state, @NewZip)
FROM Performers PRINT 'Performer added to database'
WHERE PerformerName=@NewName COMMIT
AND Zip = @NewZip

exec performer_Insert @ID = 10, @NewName = 'James Brown', @street ='Main',


@city ='Aiken', @state ='SC', @NewZip = 54322 44
Triggers vs. Stored Procedures

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

You might also like