Download Pclec04 - Monash University

Document related concepts

Microsoft Access wikipedia , lookup

Relational algebra wikipedia , lookup

Oracle Database wikipedia , lookup

Database wikipedia , lookup

Functional Database Model wikipedia , lookup

Microsoft Jet Database Engine wikipedia , lookup

Ingres (database) wikipedia , lookup

Entity–attribute–value model wikipedia , lookup

Clusterpoint wikipedia , lookup

Extensible Storage Engine wikipedia , lookup

Join (SQL) wikipedia , lookup

Open Database Connectivity wikipedia , lookup

Microsoft SQL Server wikipedia , lookup

Null (SQL) wikipedia , lookup

Database model wikipedia , lookup

Relational model wikipedia , lookup

SQL wikipedia , lookup

PL/SQL wikipedia , lookup

Transcript
Lecture 4 - More on SQL
We will be spending some time on the ‘interesting’
commands in SQL, and these will be based on a ‘political’
database (which I have loaded for you into the CSE7050
tablespace).
In this session you will see the effects of ‘nulls’ - attributes
with no values - on outputs of queries
There is also some comment on Rules and Triggers which
are used to strengthen the Integrity capabilities of a
database
There is an short exercise which introduces Primary and
Foreign key nomination, and also unique keys - not
necessarily the same thing.
Pclec04 / 1
SQL - An Introduction
• Some terms:
– A set. This is an unordered collection of items, all of the
same type and structure
In SQL these sets of data are called tables
– Their elements are called rows
– And rows are made up of columns - and the columns
have a name, which is called an attribute
Pclec04 / 2
SQL - An Introduction
• By contrast a file is a sequence or records which a
procedural program navigates. Such a program
– needs to ‘open a file’
– fetch a record at a time
– perform some work on each record accessed
– close the file (which may correspond to the last record
being processed).
– navigation is done by ‘next record’, ‘prior record’, ‘a
record position in the file.
• The data is stored in a physical model
Pclec04 / 3
SQL - An Introduction
• SQL connects a user (person or program) to the whole
named database, all at once
• A database generally consists of a number of tables
• Different vendors have different methods of data
management
– a single ‘file’ such as Sybase,
– multiple tables in a single disk allocation unit as
does DB2
– compressed bit vectors (Nucleus International)
(don’t get too carried away by all this - it’s just to illustrate that
there is a variety of management methods)
Pclec04 / 4
SQL - An Introduction
• With SQL, the user does not ‘open’ nor ‘close’ tables
• A user normally has a subset of tables to which access is
allowed, and privileges are granted to allow the user to
perform some specific functions
• A query (an access to data in a table or tables) returns the
whole result set all at once. All of the required rows are
updated, inserted or deleted - or none of the rows are.
• The whole set involved in the ‘transaction’ works, OR the
whole ‘transaction’ fails
Pclec04 / 5
SQL - An Introduction
• A table has no ordering - data is not ‘in ascending or
descending’ order or ‘date’ order ….
• Columns are referenced by name only, not by their relative
position in a table
• The columns of a table can be re-arranged, BUT the SQL
statements referencing this or these tables are not affected
Pclec04 / 6
SQL - An Introduction
There are however some very specific rules
• 1 is that every table has a structure
• Another rule is that insertion, updating and deletion of rows
in each table can only occur if all the rows have the same
structure as the rest of the rows in the table
• This reinforces the rule that
– A table is a set of rows of one particular type
Pclec04 / 7
SQL - An Introduction
• Let’s look at a simple example
A table has been created and contains this data
Column 1 Column 2
Column 3
1001
Fat Cat
Very lazy
1002
Manager
Issues orders
1003
Train Spotter Watches trains
This data would be accepted
1004
Driver
Drives things
This data would NOT be accepted
Inspector
1005
$50,000
Examines things
Pclec04 / 8
SQL - An Introduction
• SQL is quite happy to have a table with zero rows
• The columns which make up a row are always scalar - also
known as atomic
• they are complete in themselves, and can’t be broken into
smaller parts - which is part of good and careful design
• Columns can have CONSTRAINTS placed on them when the
table is created. These constraints are part of the database,
and are also a component of the design phase
Pclec04 / 9
SQL - An Introduction
• There are 3 sub-languages in SQL
1 is a ‘data definition language’ which is used to create,
drop and alter objects in a database
1 is a ‘data manipulation language’ which is used to insert,
delete, and update data, and which also performs queries
against the database contents
1 is a ‘data control language’ which provides security to a
database through privileges and other mechanisms - one
you have seen is the ‘constraint’ capability
Pclec04 / 10
SQL - An Introduction
Some more detail
Transaction Control
• A transaction in SQL is either completely finished OR it is not
done at all
• No partial results can be produced
• Work done can be committed - it becomes a permanent part
of the database or it can be rolled back - the database is
restored to the state prior to the transaction commencing
• SQL programmers need to be aware of the need for
concurrency control - that is the sharing of the database
contents among transactions (more about this later)
Pclec04 / 11
SQL - An Introduction
• Integrity
These are processes put in place to ensure that the data in
the database is complete, clear and comprehensive AND
that the data contents and the functions performed on it are
in accordance with a set of rules - which are frequently
called ‘The Business Rules’
However, there is more to Integrity than that.
Pclec04 / 12
SQL - An Introduction
• Syntax
– Every language has its syntax - the rules for expression
which lead to clear and accurate communication
– Computer languages have a somewhat stilted form and a
limited number of expressions - but they must be used in
accordance with the ‘syntax rules’ for correct execution of
a requirement
Pclec04 / 13
SQL - An Introduction
Some terms :
– A schema is the data, the operators and the rules of the
defined database
– Programmers (or users) handle data structures in tables
– Tables can be permanent (base tables) or virtual (views)
– Any operation in SQL will return a ‘result’ table
– A scalar value is a non-array value - one dimension
– A literal is a constant which is referred to by its value
– A Column Expression is a calculation which will return a
value for any data item within that column
Pclec04 / 14
SQL - An Introduction
• Each column in each table in a database has a ‘data type’
which determines the characteristic of data values in the
columns
• and which also adds to the integrity of data in the database
• these data type are definitions such as
– text
– character
– numeric
– integer
– date and so on. They are specific to each vendor but
are subject to an ISO/ASCII standard set
Pclec04 / 15
SQL - An Introduction
Ready for some more terms ?
Try these :-
Cardinality of a Tables = The number of rows which a table can
contain (may be equal to or greater than 0)
Degree of a table = The number of columns in a table (must be
equal to or greater than 1)
Pclec04 / 16
SQL - An Introduction
Domain Compatible Data Types. If 2 data types are ‘domain
compatible’, they can be converted into one common data
type - this has a bearing on ‘legal conversions’
Union Compatible Rows. 2 rows are said to be Union
Compatible if they have the same degree and their columns
have domain compatible data types in corresponding
positions (what this really means essentially is that they
have the same structure and could have come from the
same table)
Pclec04 / 17
SQL - An Introduction
• The term ‘database design’ has been already mentioned,
and was introduced to support or reinforce the principle that
the use of SQL comes AFTER the conditions relating to the
existence and use of data have been developed, designed
reviewed and approved
• In this lecture, we will move onto some of the SQL
statements - but make sure you get the order of progression
correct
– design correctly first
– then apply SQL
Pclec04 / 18
SQL - An Introduction
Some statements:
Create table :
The basic syntax is
<table definition> ::=
CREATE TABLE <table name> (<table element list>);
<table element list> ::=
<table element> | <table element>, <table element list>
<table element> ::=
<column definition> | <table constraint definition>
Pclec04 / 19
SQL - An Introduction
That probably looks terrible, but it illustrates the construction
stages of the statement.
The ‘create’ is the command verb, and
indexes,
triggers,
procedures,
packages,
relational objects,
sequences
as well as tables
can be ‘created’
Pclec04 / 20
SQL - An Introduction
An example :
create table myfirstone( col1 number(4) not null,
col2 number(4,1) not null,
col3 number not null);
The term ‘myfirstone’ is the table name
col1, col2, col3 is the <table element list>;
The number(n) is the column data type definition
The ‘not null’ is the column definition constraint
Pclec04 / 21
SQL - An Introduction
SQL Data Types
You will be pleased to see that there are 3 main data types
– Numeric
– Character
– Temporal
There are also ‘vendor specific types’ such as money,
currency, float, decimal, blobs and so on.
Pclec04 / 22
SQL - An Introduction
Numeric types:
Firstly, there is a wide range of numeric types - numeric,
decimal, integer, smallint
In SQL they are classified as either ‘exact’ or ‘approximate’
An ‘exact’ numeric value is one which has a precision p and
a scale s
The ‘precision’ is a positive integer which determines the
number of significant digits in a given base system (decimal,
octal, hexadecimal, binary)
The ‘scale’ is a non-negative integer which indicates the
number of ‘decimal’ places the number has.
Pclec04 / 23
SQL - An Introduction
An approximate numeric value consists of a mantissa and
an exponent.
The mantissa is a signed numeric value, and the exponent
is a signed integer which specifies the magnitude of the
mantissa.
An approximate numeric value has a precision which is the
positive integer which specifies the number of significant
binary digits in the mantissa
Pclec04 / 24
SQL - An Introduction
The value of an approximate numeric value is the mantissa
multiplied by 10 to the exponent.
Float, Real and Double Precision are approximate numeric
types
The 3 parts then of an approximate numeric value are
sign Excess + Exponent
Mantissa
The IEEE has introduced a floating point standard which,
when all vendors adopt it ,should make query result more
uniform across platforms (they also have a NaNs bit
configuration to represent overflow, underflow, errors and
missing values - wait for ‘not nulls’ to appear)
Pclec04 / 25
SQL - An Introduction
Character Types
The early version of SQL-89 defined a character(n) or
char(n) data type which represented a fixed length string of
(n) printable characters where (n) is always greater than 1
The characters are from the ASCII set
SQL-92 added the character varying (n) or varchar(n).
This represents a string which varies from 1 to (n) printable
characters. A zero length string cannot occur in a table.
Pclec04 / 26
SQL - An Introduction
Temporal Data Types
In SQL-92 these are the date/time data types
There is a very complete specification for Date, Time, and
Timestamp data types
There are rules for converting from numeric and character
strings into these temporal types, and there is also a time
zone table schema used for conversions (it hasn’t been
implemented yet, and has already been subsumed in SQL99)
All SQL implementations have a Date datatype - many also
have a Time and a Timestamp datatype.
Pclec04 / 27
SQL - An Introduction
The Default Clause ( be careful of this)
The syntax is <default clause> ::= DEFAULT <default option>
<default option> ::= <literal> | <system value> | null
(as an example a table could be created for employees where
unless they state a specific required credit, their credit
threshold would be a default value - say $500.00)
create table employee (col1 integer default 1, col2 integer(3,0)
default 500, col3 varchar2(8) default ‘newstart’);
Pclec04 / 28
SQL - An Introduction
Column Constraints
There are 4 different types. They are actually rules attached
to the table. All of the rows in the table are validated against
the constraints
1. Not null
You have seen the not null constraint which means that on
an insert and update the named column MUST acquire a
value
- which ensures that no missing values can occur in
constrained columns
- and which adds to integrity
Pclec04 / 29
SQL - An Introduction
2. Check() constraint
This tests the rows of a table against a logical expression
(known in SQL as a search expression). Intended rows
which don’t pass the test, (or in some cases existing rows
where a ‘new’ check has been installed) are rejected - again
adding to the integrity of the data
The syntax is
<check constraint definition> ::= CHECK <search condition>
create table customer(col1 varchar2(10) check creditlimit <
500);
or, create table person(gender varchar2(6) check gender in
(‘male’, ‘female’));
Pclec04 / 30
SQL - An Introduction
3. Unique and Primary Key Constraints
No duplicate values will be able to occur in any column of a
table where the ‘unique’ constrains has been set.
A Primary Key will ensure that each row of a table will have
a non-repeating access key
There may be many ‘unique’ columns set in a table, but only
one named Primary Key (which may contain multiple
columns) per table. A Primary Key, once nominated,
automatically inherits the Not Null constraint
A unique named column may contain nulls
Pclec04 / 31
SQL - An Introduction
4. Reference Specification
This in used with referential constraint definition - referential
integrity
This constraint relates 2 or more tables together, and is the
binding block of the relational database theory
It will appear again in Entity - Relationship modelling but
here is a synopsis:
‘If the value is in the column of the referencing table (say B),
then it must either be NULL, OR that same value must
appear somewhere in another table (say A) where it is the
Primary Key’
Pclec04 / 32
SQL - An Introduction
In the next few slides you will see the create table
statements for 3 tables - Customers, Inventory and Orders
It is verbose and (if I’ve remembered) you should have a
copy of the table structures on paper.
Pclec04 / 33
SQL - An Introduction
Create table Customers
(custid number(5,0) not null primary key,
custname varchar2(15) not null,
credit varchar2(1) not null check (credit in (‘a’, ‘b’, ‘c’)));
- watch the number of )’s used.
Create table Inventory
(partid number(7,0) not null primary key,
description varchar2(10) not null,
stockqty number(5,0) not null,
reorderpoint number(2,0),
price number(7,2), not null);
Pclec04 / 34
SQL - An Introduction
Create table Orders
(orderid number(6,0) not null primary key,
empid number(3,0) references salespersons (empid),
custid number(5,0) not null references Customers(custid),
salesdate date not null default sysdate,
item1 number(7,0) references Inventory(partid), qty1
number(5,0),
item2 number(7,0) references Inventory(partid), qty2
number(5,0),
item3 number(7,00 references Inventory(partid), qty3
number(5,0));
number(n,0) can be expressed as number(n)
Pclec04 / 35
SQL - An Introduction
Other Table Manipulation Commands
SQL-92 and SQL-99 define a number of options in the table
create command, most of which are not yet in vendor
products.
The main drive of these options is to create temporary
tables with local and/or global access
Further options deal with the handling of rows in these
tables after the end of a session - preserved or deleted
Pclec04 / 36
SQL - An Introduction
2. Drop Table
This gets rid of a table - its contents and its schema. It is
used to get rid of unwanted tables
There is no recovery, except by using database recovery
processes
Dropping a table will in many cases affect other related
tables
Other objects which can be dropped are view, schema,
constraint, trigger, procedure, package …..
Pclec04 / 37
SQL - An Introduction
3. Alter Table
This is a dangerous command as it adds, removes or
changes columns in a given table (Oracle 8i documentation
has approximately 65 pages on this command)
SQL-89 ignored this function, but it occurs in SQL-92 and
SQL-99
The SQL-92 syntax is
Alter table <table name> < alter table action>
Pclec04 / 38
SQL - An Introduction
<alter table action> ::=
<add column definition>
| <alter column definition>
| <drop column definition>
| <add table constraint definition>
| <drop table constraint definition>
Pclec04 / 39
SQL - An Introduction
A few ‘simple’ examples
alter table salespersons add phone integer not null
alter table salespersons drop phone
Oracle 8i uses a combination of the ‘drop’ with a ‘modify’
statement.
A column or columns in a table can also be dropped (but not
before the effects have been carefully investigated)
This command is rarely used by ‘normal query users’
Pclec04 / 40
SQL - Sample Database Schema
PRIME _MINISTER
PM_NAME BIRTH_YR YRS_SERVED DEATH_AGE STATE_BORN STATE_REP
MARRIAGE
PM_NAME SPOUSE_NAME MAR_YR PM_AGE NR_CHILDREN
MINISTRY
MIN_NR PM_NAME PARTY DAY_COMM MTH_COMM YR_COMM
Pclec04 / 41
Use of COUNT with DISTINCT
How many Liberal prime ministers were commissioned
between 1970 and 1980?
SELECT ‘Liberal PMs’, COUNT(*), COUNT(DISTINCT PM_NAME)
FROM MINISTRY
WHERE PARTY = ‘Liberal’
AND
YR_COMM BETWEEN 1970 AND 1980;
COUNT(*)
Liberal PMs
5
COUNT(DISTINCT PM_NAME)
2
Pclec04 / 42
Using the Logical Operators
Which prime ministers were born in Victoria before the turn
of the century?
SELECT PM_NAME, BIRTH_YR, STATE_BORN
FROM
PRIME_MINISTER
WHERE STATE_BORN=‘VIC’ AND BIRTH_YR < 1900;
PM_NAME
Deakin A
Bruce S M
Scullin J H
Menzies R G
Curtin J
BIRTH_YR
1856
1883
1876
1894
1885
STATE_BORN
VIC
VIC
VIC
VIC
VIC
Pclec04 / 43
Arithmetic Operators in a Select
List the name, birth year and year of death of each prime
minister who was born in New South Wales. List in order of
birth year.
SELECT PM_NAME, BIRTH_YR, BIRTH_YR + DEATH_AGE
FROM
PRIME_MINISTER
WHERE
STATE_BORN = ‘NSW’
ORDER BY BIRTH_YR;
PM_NAME
Barton E
Page E C G
Chifley J
Holt H E
McMahon W
Whitlam E G
BIRTH_YR
1849
1880
1885
1908
1908
1916
BIRTH_YR + DEATH_AGE
1920
1961
1951
1967
?
?
Pclec04 / 44
Combining Logical Operators
Which prime ministers were born in NSW and then
represented Victoria or have served two years or more?
SELECT
FROM
WHERE
AND
OR
PM_NAME, STATE_BORN, STATE_REP, YRS_SERVED
PRIME _MINISTER
STATE_REP = ‘VIC’
STATE_BORN = ‘NSW’
YRS_SERVED >= 2;
PM_NAME
Holt H E
Gorton J G
Whitlam E G
Fraser J M
STATE_BORN
NSW
VIC
NSW
VIC
STATE_REP
VIC
VIC
NSW
VIC
YRS_SERVED
1.88
3.17
2.92
7.33
Pclec04 / 45
A Search and Join Condition
For each prime minister born in or after 1900, give his name,
birth year and party.
SELECT
FROM
WHERE
P.PM_NAME, BIRTH_YR, PARTY
PRIME_MINISTER P, MINISTRY M
P.PM_NAME = M.PM_NAME AND BIRTH_YR >= 1900;
PM_NAME
Holt H E
Holt H E
McEwen J
Gorton J G
Gorton J G
Gorton J G
BIRTH_YR
1908
1908
1900
1911
1911
1911
PARTY
Liberal
Liberal
Country
Liberal
Liberal
Liberal
Pclec04 / 46
A Search and Join Condition
With ‘distinct’
For each prime minister born in or after 1900, give his name,
birth year and party.
SELECT
FROM
WHERE
DISTINCT P.PM_NAME, BIRTH_YR, PARTY
PRIME_MINISTER P, MINISTRY M
P.PM_NAME = M.PM_NAME AND BIRTH_YR >= 1900;
PM_NAME
Fraser J M
Gorton J G
Hawke R J L
Holt H E
McEwan J
McMahon W
Whitlam E G
BIRTH_YR
1930
1911
1929
1908
1900
1908
1916
PARTY
Liberal
Liberal
Labor
Liberal
Country
Liberal
Labor
Pclec04 / 47
Multiple Joins
Give the name, birth year, party and the year of marriage of
prime ministers born in or after 1900.
SELECT
FROM
WHERE
AND
AND
DISTINCT P.PM_NAME, BIRTH_YR, MAR_YR, PARTY
PRIME_MINISTER P, PM_MARRIAGE W, MINISTRY M
P.PM_NAME = W.PM_NAME
P.PM_NAME = M.PM_NAME
BIRTH_YR >= 1900;
PM_NAME
Fraser J M
Gorton J G
Hawke R J L
Holt H E
McEwen J
McEwen J
BIRTH_YR
1930
1911
1929
1908
1900
1900
MAR_YR
1956
1935
1956
1946
1921
1968
PARTY
Liberal
Liberal
Labor
Liberal
Country
Country
Pclec04 / 48
Use of GROUP BY
List the number of prime ministers from each party.
SELECT
PARTY, COUNT(*)
FROM
MINISTRY
GROUP BY PARTY;
PARTY
Country
Free Trade
Labor
Liberal
National Labor
Nationalist
Protectionist
COUNT(*)
3
1
15
17
1
3
5
Pclec04 / 49
Grouping by More Than One Column
Group prime ministers by their state born and by the state they
represented. Give the numbers of prime ministers and the total
numbers of years served.
SELECT STATE_BORN, STATE_REP, COUNT(*), SUM(YRS_SERVED)
FROM
PRIME_MINISTER
GROUP BY STATE_BORN, STATE_REP;
STATE_BORN
?
?
NSW
NSW
QLD
TAS
VIC
VIC
STATE_REP
NSW
QLD
NSW
VIC
QLD
TAS
VIC
WA
COUNT(*)
4
1
5
1
2
1
7
1
SUM(YRS_SERVED)
9.67
4.81
11.83
1.88
0.13
7.25
42.69
3.75
Pclec04 / 50
Grouping with the WHERE Clause
For prime ministers born after 1900, list the number of prime
ministers born in each state and the total number of years
served.
SELECT STATE_BORN, COUNT(*), SUM(YRS_SERVED)
FROM
PRIME_MINISTER
WHERE
BIRTH_YR > 1900
GROUP BY STATE_BORN;
STATE_BORN
WA
VIC
NSW
COUNT(*)
1
2
3
SUM(YRS_SERVED)
?
10.50
6.52
Pclec04 / 51
Grouping with the HAVING Clause
For each state where the total years served by prime ministers
born in that state is less than 10 years, give the number of
prime ministers born in that state and the total number of years
served.
SELECT STATE_BORN, COUNT(*), SUM(YRS_SERVED)
FROM
PRIME_MINISTER
GROUP BY STATE_BORN
HAVING
SUM(YRS_SERVED) < 10;
STATE_BORN
TAS
QLD
COUNT(*)
1
2
SUM(YRS_SERVED)
7.25
0.13
Pclec04 / 52
Subqueries
Give the name and death age for each prime minister who
died at an age less than the average death age of prime
ministers. List in ascending order of death age.
SELECT
FROM
WHERE
PM_NAME, DEATH_AGE
PRIME_MINISTER
DEATH_AGE < (SELECT AVG(DEATH_AGE)
FROM PRIME_MINISTER);
ORDER BY DEATH AGE;
PM_NAME
Holt H E
Lyons J A
Curtin J
Deakin A
DEATH_AGE
59
60
60
63
Pclec04 / 53
Subqueries
Which prime minister died the oldest? Give his name and
that age.
SELECT
FROM
WHERE
PM_NAME, DEATH_AGE
PRIME_MINISTER
DEATH_AGE = (SELECT MAX(DEATH_AGE)
FROM PRIME_MINISTER)
ORDER BY DEATH AGE;
PM_NAME
Forde F M
DEATH_AGE
93
Pclec04 / 54
Subquery With IN Operator
List the name and party of each deputy prime minister who was
also prime minister.
SELECT
FROM
WHERE
DISTINCT DEPUTY_NAME, PARTY
DEPUTY_PM
DEPUTY_NAME IN (SELECT PM_NAME
FROM PRIME_MINISTER);
DEPUTY_NAME
Chifley J B
Cook J
Cook J
Deakin A
PARTY
Labor
Free Trade
Nationalist
Protectionist
Pclec04 / 55
Multiple Nested Subqueries
Give the name and birth year of each prime minister who
was commisioned after Bob Hawke had turned 21.
Order by birth year.
SELECT
FROM
WHERE
PM_NAME, BIRTH_YR
PRIME_MINISTER
PM_NAME = ANY
(SELECT PM_NAME
FROM MINISTRY
WHERE YR_COMM >
(SELECT BIRTH_YR + 21
FROM PRIME_MINISTER
WHERE PM_NAME = ‘Hawke R J L’)
AND PM_NAME <> ‘Hawke R J L’)
ORDER BY BIRTH_YR;
Pclec04 / 56
Result of Previous Query
Give the name and birth year of each prime minister
who was commisioned after Bob Hawke had turned 21.
Order by birth year.
PM_NAME
BIRTH_YR
Menzies R G
1894
McEwan J
1900
Holt H E
1908
McMahon W
1908
GortonJ G
1911
Whitlam E G
1916
Pclec04 / 57
The Existential Operator
This is a test for Existence (or non-existence)
It differs from the IN operator in that it does not match a
column or columns used in a correlated sub-query
A query such as this : select name from workerskill
group by name having count (skill) > 1;
would give a list of workers who had more than 1 skill from a
table named workerskill.
Pclec04 / 58
The Existential Operator
However if we attempt to find both the Name and Skill, the
query will fail as the count is on the Primary Key, in this
example, skill.
There is only one Primary Key per row, and therefore the
COUNT > 1 cannot exceed 1, and the query must fail.
In using the Existential operator, we use a subterfuge and
that is to have the query think that the inspected table
occurs twice. (by correlation).
Pclec04 / 59
The Existential Operator
How is this done ?
Let’s look at this ‘solution’.
Select name, skill from workerskill ws
where exists (select * from workerskill
where ws.name = name
group by name
having count(skill) > 1);
as an exercise, you might like to try a solution with the
subquery such as ‘where name IN…... ‘ and then use a
similar construction to the above
There is an exercise tonight on this operator.
Pclec04 / 60
The Exists Operator
List the name, birth year and state represented of prime
ministers who were also deputy prime ministers.
SELECT
FROM
WHERE
PM_NAME, BIRTH_YR, STATE_REP
PRIME_MINISTER
EXISTS (SELECT *
FROM DEPUTY_PM
WHERE DEPUTY_NAME = PM_NAME ORDER BY BIRTH_YR);
Nb: The subquery uses SELECT * and here the correlation
column is PM_NAME. The condition is satisfied if at least one
row exists.
PM_NAME
Deakin A
Cook J
Hughes W M
BIRTH_YR
1856
1860
1862
STATE_REP
VIC
NSW
NSW
Pclec04 / 61
The NOT EXISTS operator
Give the name, state represented and death age of each
prime minister who has no recreation interests.
SELECT
FROM
WHERE
PM_NAME, STATE_REP, DEATH_AGE
PRIME_MINISTER P
NOT EXISTS (SELECT *
FROM PM_RECREATION
WHERE PM_NAME = P.PM_NAME);
Nb: The subquery returns rows from PM_RECREATION and
here the correlation column is PM_NAME. The condition is
satisfied if no row exists.
PM_NAME
Reid G H
Fisher A
Cook J
STATE_REP
NSW
QLD
NSW
DEATH_AGE
73
66
87
Pclec04 / 62
Advanced SQL examples
There will be a set of problems handed out for you to
attempt.
There will also be some answers to the queries.
Pclec04 / 63
SQL/PSM Standard
• As with most languages (procedural and non-procedural)
there is the need to ensure that the ‘user demands’ of data
associated with storage, retrieval and presentation are met.
• SQL has undergone, and is undergoing, reviews to ensure
that the volumes of data in the various data forms can be
handled and with a high degree of throughput.
• There are a number of developments in the association of
‘objects’ in Object Orientated database forms with Relational
Database. Watson’s ‘Data Management’ has some very
interesting information on this.
Pclec04 / 64
SQL/PSM Standard
• One of the ‘weaknesses’ of Relational Database is the
limitations of the methods of including ‘User Rules’ to
enhance and reinforce the integrity of data in a database.
• You will have heard the terms ‘Rules and Procedures’ and
‘Triggers and Constraints’ in this context.
• On 3rd October, 1996 the SQL/PSM section of SQL was
formally accepted and promoted by the X3H2 committee of
the ISO.
Pclec04 / 65
SQL/PSM Standard
PSM is the “Persistent Stored Module” of SQL.
It is a procedural language for writing procedures and
triggers.
Don’t get carried away - it will be some time before
vendors support such a language
Some vendors already have form s of procedural languages
for embedding procedures.
Vendors will probably ignore the new standard or mix it with
their existing languages.
Pclec04 / 66
Rules and Procedures
A procedure is a collection of database processing
statements which are managed as objects
Benefits :
Reduce amount of communication between
the applications and the DBMS
Provide the DBA with an extra level of
control over
- data access
- modifications
Permits Extended Referential Integrity processes
Pclec04 / 67
Rules and Procedures
ONE procedure may be used in MANY APPLICATIONS
Benefits :
Reduced coding development time
High level of accuracy
COMMANDS :
CREATE, PERMISSION, MESSAGE, EXECUTE,
DROP
The PROCEDURE is attached to the table nominated and effectively
becomes part of the database dictionary.
Invoked by a RULE
Pclec04 / 68
Rules and Procedures
Definition of a RULE
A RULE is a USER-DEFINED device which calls up a PROCEDURE
whenever the database is about to change
e.g.
INSERT, UPDATE, DELETE
- change to an existing attribute value
Other Inferences :
Referential Integrity
General Integrity
Rules are associated with a (limited) command set.
Pclec04 / 69
Rules and Procedures - Ingres style
An Example:
create rule input_member
after insert, update (mem_id) of member
execute procedure check_input_member
(member_id = new.mem_id)
The table name is member
part attributes are member_id, subs_term
Pclec04 / 70
Rules and procedures - Ingres style
create procedure check_input_member (member_id
vchar(4))
as declare val_check integer ; msg vchar(80) not null ;
begin
select count(*) into val_check from member
where mem_id = :member_id and subs_term <= ‘today’ ;
if val_check = 1 then
return ;
else
msg = ‘Warning - Member already exists’ ;
endif
end
Pclec04 / 71
Rules and Procedures - Oracle Style
Better known as PL/SQL Procedural Language for SQL
An example: The following script allows for the alteration of
a major for a student. If the student doesn’t exist, then a
new record must be created.
DECLARE
/* declare variables which will be used in SQL statements */
v_newmajor varchar2 (10) := ‘History’;
v_firstname varchar2 (10) := ‘Scott’;
v_lastname varchar2 (10) := ‘Urman’;
Pclec04 / 72
Rules and Procedures - Oracle Style
BEGIN
update students
SET major = v_newmajor
where first_name = v_firstname
and lastname = v_lastname
/* check to see if the record was found. If not, then we need
to insert this record */
If sql% notfound then
insert into students(ID,first_name,last_name,major)
values (10020, v_firstname, v_lastname,v_newmajor);
end if;
end;
Pclec04 / 73
Oracle Triggers
Oracle triggers are used to include more processing power
to the DBMS function for events which affect a database.
In the following example a Trigger will be set which ensures
that changes to employee records will only take place during
business hours on working days ( security ?)
See if you agree ...
Pclec04 / 74
Oracle Triggers
Create trigger emp_permit_change
before
delete or insert or update
on emp
declare dummy integer;
begin
/* if today is a Saturday or Sunday, then return an error*/
if (to_char(sysdate, ‘dy’) = ‘sat’ or
to_char (sysdate, ‘dy’) = ‘sun’)
then raise_application_error (-20501,
‘May not change employee table during the weekend’);
end if;
Pclec04 / 75
Oracle Triggers
Perhaps we need this as well :If (to_char(sysdate, ‘hh24’) < 8
or to_char(sysdate, ‘hh24’) >= 18)
then raise application_error (-20502,
‘May only change employee table during working hours’);
end if;
end;
which raises and interesting point - what happens with
flexible time and enterprise bargaining ?
Pclec04 / 76
Monash University - As seen in daytime
Pclec04 / 77