77
Pclec04 / 1 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 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

Embed Size (px)

Citation preview

Page 1: Pclec04 / 1 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

Pclec04 / 1

Lecture 4 - More on SQLLecture 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.

Page 2: Pclec04 / 1 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

Pclec04 / 2

SQL - An IntroductionSQL - 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

Page 3: Pclec04 / 1 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

Pclec04 / 3

SQL - An IntroductionSQL - 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

Page 4: Pclec04 / 1 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

Pclec04 / 4

SQL - An IntroductionSQL - 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)

Page 5: Pclec04 / 1 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

Pclec04 / 5

SQL - An IntroductionSQL - 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

Page 6: Pclec04 / 1 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

Pclec04 / 6

SQL - An IntroductionSQL - 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

Page 7: Pclec04 / 1 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

Pclec04 / 7

SQL - An IntroductionSQL - 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

Page 8: Pclec04 / 1 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

Pclec04 / 8

SQL - An IntroductionSQL - 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

Inspector1005 $50,000 Examines things

Page 9: Pclec04 / 1 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

Pclec04 / 9

SQL - An IntroductionSQL - 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

Page 10: Pclec04 / 1 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

Pclec04 / 10

SQL - An IntroductionSQL - 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

Page 11: Pclec04 / 1 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

Pclec04 / 11

SQL - An IntroductionSQL - 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)

Page 12: Pclec04 / 1 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

Pclec04 / 12

SQL - An IntroductionSQL - 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.

Page 13: Pclec04 / 1 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

Pclec04 / 13

SQL - An IntroductionSQL - 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

Page 14: Pclec04 / 1 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

Pclec04 / 14

SQL - An IntroductionSQL - 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

Page 15: Pclec04 / 1 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

Pclec04 / 15

SQL - An IntroductionSQL - 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

Page 16: Pclec04 / 1 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

Pclec04 / 16

SQL - An IntroductionSQL - 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)

Page 17: Pclec04 / 1 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

Pclec04 / 17

SQL - An IntroductionSQL - 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)

Page 18: Pclec04 / 1 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

Pclec04 / 18

SQL - An IntroductionSQL - 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

Page 19: Pclec04 / 1 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

Pclec04 / 19

SQL - An IntroductionSQL - 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>

Page 20: Pclec04 / 1 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

Pclec04 / 20

SQL - An IntroductionSQL - 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’

Page 21: Pclec04 / 1 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

Pclec04 / 21

SQL - An IntroductionSQL - 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

Page 22: Pclec04 / 1 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

Pclec04 / 22

SQL - An IntroductionSQL - 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.

Page 23: Pclec04 / 1 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

Pclec04 / 23

SQL - An IntroductionSQL - 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.

Page 24: Pclec04 / 1 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

Pclec04 / 24

SQL - An IntroductionSQL - 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

Page 25: Pclec04 / 1 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

Pclec04 / 25

SQL - An IntroductionSQL - 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)

Page 26: Pclec04 / 1 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

Pclec04 / 26

SQL - An IntroductionSQL - 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.

Page 27: Pclec04 / 1 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

Pclec04 / 27

SQL - An IntroductionSQL - 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 SQL-99)

All SQL implementations have a Date datatype - many also have a Time and a Timestamp datatype.

Page 28: Pclec04 / 1 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

Pclec04 / 28

SQL - An IntroductionSQL - 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’);

Page 29: Pclec04 / 1 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

Pclec04 / 29

SQL - An IntroductionSQL - 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

Page 30: Pclec04 / 1 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

Pclec04 / 30

SQL - An IntroductionSQL - 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’));

Page 31: Pclec04 / 1 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

Pclec04 / 31

SQL - An IntroductionSQL - 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

Page 32: Pclec04 / 1 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

Pclec04 / 32

SQL - An IntroductionSQL - 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’

Page 33: Pclec04 / 1 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

Pclec04 / 33

SQL - An IntroductionSQL - 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.

Page 34: Pclec04 / 1 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

Pclec04 / 34

SQL - An IntroductionSQL - 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);

Page 35: Pclec04 / 1 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

Pclec04 / 35

SQL - An IntroductionSQL - 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)

Page 36: Pclec04 / 1 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

Pclec04 / 36

SQL - An IntroductionSQL - 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

Page 37: Pclec04 / 1 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

Pclec04 / 37

SQL - An IntroductionSQL - 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 …..

Page 38: Pclec04 / 1 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

Pclec04 / 38

SQL - An IntroductionSQL - 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>

Page 39: Pclec04 / 1 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

Pclec04 / 39

SQL - An IntroductionSQL - An Introduction

<alter table action> ::=

<add column definition>

| <alter column definition>

| <drop column definition>

| <add table constraint definition>

| <drop table constraint definition>

Page 40: Pclec04 / 1 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

Pclec04 / 40

SQL - An IntroductionSQL - 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’

Page 41: Pclec04 / 1 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

Pclec04 / 41

SQL - Sample Database SchemaSQL - Sample Database Schema

MARRIAGE

PM_NAME SPOUSE_NAME MAR_YR PM_AGE NR_CHILDREN

MINISTRY

MIN_NR PM_NAME PARTY DAY_COMM MTH_COMM YR_COMM

PM_NAME BIRTH_YR YRS_SERVED DEATH_AGE STATE_BORN STATE_REP

PRIME _MINISTER

Page 42: Pclec04 / 1 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

Pclec04 / 42

Use of COUNT with DISTINCTUse of COUNT with DISTINCT

SELECT ‘Liberal PMs’, COUNT(*), COUNT(DISTINCT PM_NAME)FROM MINISTRYWHERE PARTY = ‘Liberal’AND YR_COMM BETWEEN 1970 AND 1980;

COUNT(*) COUNT(DISTINCT PM_NAME)

Liberal PMs 5 2

How many Liberal prime ministers were commissioned between 1970 and 1980?

Page 43: Pclec04 / 1 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

Pclec04 / 43

Using the Logical Operators

Which prime ministers were born in Victoria before the turn of the century?

SELECT PM_NAME, BIRTH_YR, STATE_BORNFROM PRIME_MINISTERWHERE STATE_BORN=‘VIC’ AND BIRTH_YR < 1900;

PM_NAME BIRTH_YR STATE_BORNDeakin A 1856 VICBruce S M 1883 VICScullin J H 1876 VICMenzies R G 1894 VICCurtin J 1885 VIC

Page 44: Pclec04 / 1 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

Pclec04 / 44

Arithmetic Operators in a SelectArithmetic 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_AGEFROM PRIME_MINISTERWHERE STATE_BORN = ‘NSW’ORDER BY BIRTH_YR;

PM_NAME BIRTH_YR BIRTH_YR + DEATH_AGEBarton E 1849 1920Page E C G 1880 1961Chifley J 1885 1951Holt H E 1908 1967McMahon W 1908 ?Whitlam E G 1916 ?

Page 45: Pclec04 / 1 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

Pclec04 / 45

Combining Logical OperatorsCombining Logical Operators

PM_NAME STATE_BORN STATE_REP YRS_SERVEDHolt H E NSW VIC 1.88Gorton J G VIC VIC 3.17Whitlam E G NSW NSW 2.92Fraser J M VIC VIC 7.33

Which prime ministers were born in NSW and then represented Victoria or have served two years or more?

SELECT PM_NAME, STATE_BORN, STATE_REP, YRS_SERVED

FROM PRIME _MINISTER

WHERE STATE_REP = ‘VIC’

AND STATE_BORN = ‘NSW’

OR YRS_SERVED >= 2;

Page 46: Pclec04 / 1 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

Pclec04 / 46

A Search and Join ConditionA Search and Join Condition

For each prime minister born in or after 1900, give his name, birth year and party.

SELECT P.PM_NAME, BIRTH_YR, PARTYFROM PRIME_MINISTER P, MINISTRY MWHERE P.PM_NAME = M.PM_NAME AND BIRTH_YR >= 1900;

PM_NAME BIRTH_YR PARTYHolt H E 1908 LiberalHolt H E 1908 LiberalMcEwen J 1900 CountryGorton J G 1911 LiberalGorton J G 1911 LiberalGorton J G 1911 Liberal

Page 47: Pclec04 / 1 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

Pclec04 / 47

A Search and Join Condition

For each prime minister born in or after 1900, give his name, birth year and party.

SELECT DISTINCT P.PM_NAME, BIRTH_YR, PARTYFROM PRIME_MINISTER P, MINISTRY MWHERE P.PM_NAME = M.PM_NAME AND BIRTH_YR >= 1900;

PM_NAME BIRTH_YR PARTYFraser J M 1930 LiberalGorton J G 1911 LiberalHawke R J L 1929 LaborHolt H E 1908 LiberalMcEwan J 1900 CountryMcMahon W 1908 LiberalWhitlam E G 1916 Labor

With ‘distinct’

Page 48: Pclec04 / 1 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

Pclec04 / 48

Multiple Joins

Give the name, birth year, party and the year of marriage of prime ministers born in or after 1900.

SELECT DISTINCT P.PM_NAME, BIRTH_YR, MAR_YR, PARTYFROM PRIME_MINISTER P, PM_MARRIAGE W, MINISTRY MWHERE P.PM_NAME = W.PM_NAMEAND P.PM_NAME = M.PM_NAMEAND BIRTH_YR >= 1900;

PM_NAME BIRTH_YR MAR_YR PARTYFraser J M 1930 1956 LiberalGorton J G 1911 1935 LiberalHawke R J L 1929 1956 LaborHolt H E 1908 1946 LiberalMcEwen J 1900 1921 CountryMcEwen J 1900 1968 Country

Page 49: Pclec04 / 1 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

Pclec04 / 49

Use of GROUP BY

List the number of prime ministers from each party.

SELECT PARTY, COUNT(*)FROM MINISTRYGROUP BY PARTY;

PARTY COUNT(*)Country 3Free Trade 1Labor 15Liberal 17National Labor 1Nationalist 3Protectionist 5

Page 50: Pclec04 / 1 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

Pclec04 / 50

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_MINISTERGROUP BY STATE_BORN, STATE_REP;

STATE_BORN STATE_REP COUNT(*) SUM(YRS_SERVED)? NSW 4 9.67? QLD 1 4.81NSW NSW 5 11.83NSW VIC 1 1.88QLD QLD 2 0.13TAS TAS 1 7.25VIC VIC 7 42.69VIC WA 1 3.75

Page 51: Pclec04 / 1 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

Pclec04 / 51

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_MINISTERWHERE BIRTH_YR > 1900GROUP BY STATE_BORN;

STATE_BORN COUNT(*) SUM(YRS_SERVED)WA 1 ?VIC 2 10.50NSW 3 6.52

Page 52: Pclec04 / 1 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

Pclec04 / 52

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_MINISTERGROUP BY STATE_BORNHAVING SUM(YRS_SERVED) < 10;

STATE_BORN COUNT(*) SUM(YRS_SERVED)TAS 1 7.25QLD 2 0.13

Page 53: Pclec04 / 1 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

Pclec04 / 53

SubqueriesSubqueries

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 PM_NAME, DEATH_AGEFROM PRIME_MINISTERWHERE DEATH_AGE < (SELECT AVG(DEATH_AGE) FROM PRIME_MINISTER);ORDER BY DEATH AGE;

PM_NAME DEATH_AGEHolt H E 59Lyons J A 60Curtin J 60Deakin A 63

Page 54: Pclec04 / 1 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

Pclec04 / 54

SubqueriesSubqueries

Which prime minister died the oldest? Give his name and that age.

SELECT PM_NAME, DEATH_AGEFROM PRIME_MINISTERWHERE DEATH_AGE = (SELECT MAX(DEATH_AGE) FROM PRIME_MINISTER)ORDER BY DEATH AGE;

PM_NAME DEATH_AGEForde F M 93

Page 55: Pclec04 / 1 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

Pclec04 / 55

Subquery With IN Operator

SELECT DISTINCT DEPUTY_NAME, PARTYFROM DEPUTY_PMWHERE DEPUTY_NAME IN (SELECT PM_NAME FROM PRIME_MINISTER);

DEPUTY_NAME PARTYChifley J B LaborCook J Free Trade Cook J Nationalist Deakin A Protectionist

List the name and party of each deputy prime minister who was also prime minister.

Page 56: Pclec04 / 1 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

Pclec04 / 56

Multiple Nested SubqueriesMultiple 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 PM_NAME, BIRTH_YR FROM PRIME_MINISTER WHERE 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;

Page 57: Pclec04 / 1 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

Pclec04 / 57

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

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.

Page 58: Pclec04 / 1 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

Pclec04 / 58

The Existential OperatorThe 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.

Page 59: Pclec04 / 1 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

Pclec04 / 59

The Existential OperatorThe 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).

Page 60: Pclec04 / 1 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

Pclec04 / 60

The Existential OperatorThe Existential Operator

How is this done ?Let’s look at this ‘solution’.

Select name, skill from workerskill wswhere 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 aboveThere is an exercise tonight on this operator.

Page 61: Pclec04 / 1 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

Pclec04 / 61

The Exists OperatorThe Exists Operator

List the name, birth year and state represented of prime ministers who were also deputy prime ministers.

SELECT PM_NAME, BIRTH_YR, STATE_REPFROM PRIME_MINISTERWHERE EXISTS (SELECT * FROM DEPUTY_PM WHERE DEPUTY_NAME = PM_NAME ORDER BY BIRTH_YR);

PM_NAME BIRTH_YR STATE_REPDeakin A 1856 VICCook J 1860 NSWHughes W M 1862 NSW

Nb: The subquery uses SELECT * and here the correlation column is PM_NAME. The condition is satisfied if at least one row exists.

Page 62: Pclec04 / 1 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

Pclec04 / 62

The NOT EXISTS operatorThe NOT EXISTS operator

Give the name, state represented and death age of each prime minister who has no recreation interests.

SELECT PM_NAME, STATE_REP, DEATH_AGEFROM PRIME_MINISTER PWHERE NOT EXISTS (SELECT * FROM PM_RECREATION WHERE PM_NAME = P.PM_NAME);

PM_NAME STATE_REP DEATH_AGEReid G H NSW 73Fisher A QLD 66Cook J NSW 87

Nb: The subquery returns rows from PM_RECREATION and here the correlation column is PM_NAME. The condition is satisfied if no row exists.

Page 63: Pclec04 / 1 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

Pclec04 / 63

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.

Page 64: Pclec04 / 1 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

Pclec04 / 64

SQL/PSM StandardSQL/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.

Page 65: Pclec04 / 1 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

Pclec04 / 65

SQL/PSM StandardSQL/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.

Page 66: Pclec04 / 1 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

Pclec04 / 66

SQL/PSM StandardSQL/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.

Page 67: Pclec04 / 1 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

Pclec04 / 67

Rules and ProceduresRules 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

Page 68: Pclec04 / 1 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

Pclec04 / 68

Rules and ProceduresRules 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

Page 69: Pclec04 / 1 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

Pclec04 / 69

Rules and ProceduresRules 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.

Page 70: Pclec04 / 1 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

Pclec04 / 70

Rules and Procedures - Ingres styleRules and Procedures - Ingres style

An Example:

create rule input_memberafter insert, update (mem_id) of memberexecute procedure check_input_member(member_id = new.mem_id)

The table name is memberpart attributes are member_id, subs_term

Page 71: Pclec04 / 1 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

Pclec04 / 71

Rules and procedures - Ingres styleRules 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 thenreturn ;else

msg = ‘Warning - Member already exists’ ;endif

end

Page 72: Pclec04 / 1 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

Pclec04 / 72

Rules and Procedures - Oracle StyleRules and Procedures - Oracle Style

Better known as PL/SQL Procedural Language for SQLAn 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’;

Page 73: Pclec04 / 1 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

Pclec04 / 73

Rules and Procedures - Oracle StyleRules and Procedures - Oracle Style

BEGINupdate students

SET major = v_newmajorwhere first_name = v_firstnameand lastname = v_lastname

/* check to see if the record was found. If not, then we need to insert this record */

If sql% notfound theninsert into students(ID,first_name,last_name,major)values (10020, v_firstname,

v_lastname,v_newmajor);end if;end;

Page 74: Pclec04 / 1 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

Pclec04 / 74

Oracle TriggersOracle 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 ...

Page 75: Pclec04 / 1 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

Pclec04 / 75

Oracle TriggersOracle 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;

Page 76: Pclec04 / 1 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

Pclec04 / 76

Oracle TriggersOracle 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 ?

Page 77: Pclec04 / 1 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

Pclec04 / 77

Monash University - As seen in daytime