Transcript SQL

Lecture plan
• Oracle architecture
• SQL
– Data definition
– Queries
– Insert, delete and update
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
1
Oracle
• Relational database
– Each table column is independent and identified
by name
– Ordering of rows is unimportant
– All operations should be relational, i.e. generate
new relations from old ones
– System supports at least one JOIN operation
• Based on a client-server architecture
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
2
Oracle architecture
• Oracle server consists of:
– Database (raw data)
• Logical structure = database schema
• Physical structure = file structure
– Instance (processes and system memory)
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
3
Logical database structure
• Organised into:
–
–
–
–
–
Tablespaces
Schemas
Data blocks
Extents
Segments
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
4
Tablespaces
• Group related logical structures together
• SYSTEM tablespace created automatically
– Holds the data dictionary
• Meta-data in machine-readable format
• Includes security information, schema object
information, space allocation, etc
• May also have one or more user tablespaces
• Each table belongs to a specific tablespace
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
5
Schemas
• A named collection of schema objects
associated with a particular user
• Equivalent to a user’s personal space
• Created automatically when a user account
is set up
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
6
Data blocks
• Corresponds to a specific number of bytes
of disk space
• Size can be set for each database at creation
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
7
Extents
• Specific number of contiguous data blocks
allocated for storing a specific type of
information
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
8
Segments
• A set of extents allocated for a certain
logical structure
• Oracle dynamically allocates extents to
segments as existing extents fill up
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
9
Physical database structure
• Consists of:
– Datafiles (e.g. table and index data)
• One or more datafiles form a tablespace
– Redo log files (usually multiplexed)
• Record all changes made to the data
• Used in recovery
– Control files (usually multiplexed)
• Contain a list of all other files in the database
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
10
Oracle instance
• Consists of:
– Processes
• User processes
• Oracle processes
– Shared memory used by processes
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
11
User processes
• Manipulate the user’s input
• Communicate with the Oracle server
process
• Display the information requested by the
user
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
12
Oracle processes
• Perform functions for users:
– Server processes handle requests from
connected user processes
– Background processes perform asynchronous
I/O and provide increased parallelism
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
13
Shared memory [1]
• Used for caching data, indexes and storing
shared program code
• Organised into memory structures of a fixed
size created on instance startup:
– System global area (SGA)
• Used to store data and control information for one
Oracle instance
• Holds database buffer cache, redo log buffer and
shared pool
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
14
Shared memory [2]
– Program global area
• Used to store data and control information for the
Oracle server processes
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
15
SQL
• Standard for commercial relational DBs
• High-level declarative language interface
– User specifies what the result should be
– Optimisation and query execution decisions left
to DBMS
• Based on tuple relational calculus, with
some relational algebra features
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
16
SQL versions
• Standard version accepted by ANSI / ISO
• Current version is SQL3
– Not all relational DBMSs support SQL3 (may
support SQL-92, i.e. version 2)
– Contains some object-oriented features
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
17
SQL in Oracle
• Oracle’s own version of SQL - SQLPlus
–
–
–
–
–
–
–
DDL and DML statements
View definition
Security and authorisation specification
Definition of integrity constraints
Transaction control specification
Session and system control statements
Embedding SQL into programming languages
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
18
Data definition
• Objects
– Table
• Commands
– CREATE
– ALTER
– DROP
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
19
Tables in SQL [1]
• Created by CREATE TABLE statement
CREATE TABLE EMPLOYEE
• Known as base tables
• Attributes ordered by creation order
• Rows not ordered
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
20
Tables in SQL [2]
• CREATE TABLE specifies new relation by
– Relation name
– Attributes
• Name
• Data type
• Attribute constraints
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
21
Tables in SQL [3]
• Key/entity/referential integrity constraints
– Can be specified in CREATE TABLE
– Can be added later using ALTER TABLE
• Table can be deleted by DROP TABLE
statement
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
22
Data types [1]
• Numeric
– Integer: INTEGER
– Real: FLOAT
• Character-string
– Fixed length: CHAR(n)
– Varying length: VARCHAR(n) / VARCHAR2
(n)
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
23
Data types [2]
• DATE
– Has main components YEAR, MONTH, DAY
– Also stores century, hour, minute, second
– Has format DD-MON-YYYY
E.g. 05-FEB-2001
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
24
Domains
• Like a type declaration
• Advantages
– Easier to change data type
– Improves schema readability
– Can have optional default specification
CREATE DOMAIN SSN_TYPE AS CHAR(9);
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
25
Attribute constraints
• Specified by CONSTRAINT
• Example constraint: NOT NULL
– Should always be specified for primary keys
• Constraint may be given optional name
– Specified by CONSTRAINT <name>
– Must be unique within a schema
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
26
Default values
• Specified by DEFAULT <value>
• Used if no explicit value assigned to
attribute
• NULL unless otherwise stated
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
27
Table constraints [1]
• PRIMARY KEY
• UNIQUE (secondary key)
• FOREIGN KEY (referential integrity)
– Referential integrity constraints can be violated
by
• Insertion or deletion of tuples
• Foreign key value modified
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
28
Table constraints [2]
– Referential triggered action
• Can be added to foreign key constraint to cause
automatic update ON DELETE
• Options are SET NULL, CASCADE and SET
DEFAULT
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
29
DROP TABLE
• Option
– CASCADE CONSTRAINTS
DROP TABLE DEPENDENT CASCADE CONSTRAINTS;
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
30
ALTER TABLE [1]
• Command which allows
– Adding column
ALTER TABLE EMPLOYEE ADD JOB VARCHAR(12);
– Dropping column
ALTER TABLE EMPLOYEE DROP ADDRESS CASCADE;
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
31
ALTER TABLE [2]
– Changing column definition (add/drop default)
ALTER TABLE DEPARTMENT ALTER MGRSSN
DROP DEFAULT;
ALTER TABLE DEPARTMENT ALTER MGRSSN
SET DEFAULT ‘11111111’;
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
32
ALTER TABLE [3]
– Adding / dropping table constraints
ALTER TABLE EMPLOYEE DROP CONSTRAINT EMPSUPERFK
CASCADE;
ALTER TABLE EMPLOYEE ADD CONSTRAINT EMPSUPERFK;
FOREIGN KEY(SUPERSSN) REFERENCES EMPLOYEE(SSN)
ON DELETE SET NULL;
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
33
Queries
• SQL allows two or more identical tuples in
a relation
• Table is thus a multi-set / bag of tuples
• Table can be constrained to be a set by
– Use of a key constraint
– DISTINCT option
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
34
SELECT statement [1]
• Basic syntax is
SELECT <attribute list>
FROM <table list>
WHERE <condition>
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
35
SELECT statement [2]
• Example - query 0
• Similar effect to relational algebra
SELECT-PROJECT combination
– SELECT clause specifies projection attributes
– WHERE clause specifies selection condition
– SQL may retrieve duplicate tuples, however
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
36
SELECT statement [3]
• Example - query 1
• Similar effect to relational algebra
SELECT-PROJECT-JOIN combination
– SELECT clause specifies projection attributes
– WHERE clause specifies selection condition
– Condition DNUMBER = DNO is join condition
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
37
SELECT statement [4]
• Example - query 2
• Multiple select and join conditions possible
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
38
Ambiguous attribute names
• Attributes with same name in different
relations
– Names must be qualified with relation name
• Example - query 1A
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
39
Aliasing [1]
• Queries can refer to same relation twice
– One-level recursive query
– Not possible to have infinitely recursive query
• Aliases / tuple variables can be declared
• Example - query 8
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
40
Aliasing [2]
• Also possible to rename relation attributes
EMPLOYEE AS E (FN, MI, LN, SSN, BD, ADDR, SEX, SAL, SSSN,
DNO)
• This ‘shorthand’ can be used in any query
• Example - query 1B
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
41
No WHERE clause
• No condition on tuple selection
• Example - query 9
• More than one relation in FROM clause
means cross product
• Example - query 10
• Similar to relational algebra cross product PROJECT combination
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
42
Use of asterisk
• Used to retrieve all attribute values in
SELECT clause
• Examples - queries 1C, 1D, 10A
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
43
Tables as sets [1]
• Duplicate elimination not automatic
–
–
–
–
Expensive
Sometimes unnecessary or unwise
Not suitable for use with aggregate functions
Can be achieved by DISTINCT in SELECT
clause
• Example - queries 11, 11A
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
44
Tables as sets [2]
• Set union (UNION) and other set operations
sometimes available, e.g. EXCEPT,
CON TAINS, but are non-standard
• Example - queries 3, 4
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
45
Substring comparison
•
•
•
•
Uses LIKE comparison operator
% replaces any number of characters
_ replaces a single character
Examples - queries 12, 12A
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
46
Arithmetic operators
• Standard arithmetic operators can be
applied
• Example - query 13
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
47
Other operators
•
•
•
•
•
String concatenation ||
Numeric value range BETWEEN
Example - query 14
Ordering by value of one or more attributes
Example - query 15
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
48
Nested queries [1]
• Complete SELECT-FROM-WHERE block
inside WHERE of outer query
• Ambiguity among attributes of same name
– Assumed they belong to relation in innermost
nested query
• Correlated queries
– Condition in inner WHERE references “outer”
attribute
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
49
Nested queries [2]
• Queries with nested SELECT-FROMWHERE blocks using IN can usually be
expressed as single block query
• Example - query 4A
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
50
Set comparison [1]
• Comparison operator IN / NOT IN can
compare
– Value with multi-set of values
– Tuple of values with multi-set of unioncompatible tuples
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
51
Set comparison [2]
SELECT DISTINCT ESSN
FROM WORKS_ON
WHERE (PNO, HOURS) IN
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
(SELECT PNO, HOURS
FROM WORKS_ON
WHERE SSN = ‘123456789’);
52
Other comparison operators
• >, >=, <, <=, <>
• Can be used with ANY, SOME, ALL
SELECT LNAME, FNAME
FROM EMPLOYEE
WHERE SALARY > ALL
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
(SELECT SALARY
FROM
EMPLOYEE
WHERE DNO = 5);
53
Functions in SQL
• EXISTS / NOT EXISTS
– Evaluates to Boolean value
– Indicates if result of a correlated, nested query
is empty
– Example - queries 16B, 6, 7
• UNIQUE
– Evaluates to Boolean value
– Indicates if there are duplicate tuples
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
54
WHERE clause variations
• Explicit set of values
• Example - query 17
• Use of NULL
– Used with IS / IS NOT
– Equality comparison (=) not appropriate
• Example - query 18
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
55
Aggregate functions
• Built-in functions
–
–
–
–
–
COUNT
SUM
MAX
MIN
AVG
• Example - queries 19, 20, 21, 22, 23, 5
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
56
GROUP BY clause
• Group tuples with same value for an
attribute
– E.g. for averaging across categories of tuples
(rather than across all tuples)
• Example - query 24, 25
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
57
HAVING clause
• Places condition on selection of tuple
groups specified by GROUP BY clause
• Example - queries 26, 28
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
58
Summary of SQL queries [1]
SELECT <attribute and function list>
FROM <table list>
[WHERE <condition>]
[GROUP BY <grouping attribute(s)>]
[HAVING <group condition>]
[ORDER BY <attribute list>]
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
59
Summary of SQL queries [2]
• Order of conceptual evaluation
–
–
–
–
–
–
FROM clause
WHERE clause
GROUP BY clause
HAVING clause
ORDER BY clause
SELECT clause
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
60
INSERT [1]
• Possible to insert
– Single tuple
– Multiple tuples
• Specify
– Relation name
– List of values for the tuple
• In same order as attributes specified
• Example - update 1
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
61
INSERT [2]
• Can specify limited subset of attributes
– Must include all NOT NULL / non-default ones
• Example - update 1A
• DBMS may not enforce all integrity
constraints
– User must enforce the others
• Examples - updates 2, 2A
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
62
DELETE
• Possible to delete
– Single tuple
– Multiple tuples
• Tuples in other tables may be deleted by
referential triggered action
• Includes WHERE clause
• Examples - updates 4A, 4B, 4C
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
63
UPDATE [1]
• Possible to modify attribute values of
– Single tuple
– Multiple tuples
• Tuples in other tables may be modified by
referential triggered action
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
64
UPDATE [2]
• Includes
– WHERE clause
– SET clause, which specifies
• Attributes to be modified
• New attribute values (NULL / DEFAULT possible)
• Example - updates 6, 5
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
65
Views
• Simplifies query specification
• Always up-to-date
• Virtual tables derived from defining tables
– Other virtual table(s)
– Base tables(s)
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
66
Creating views
• View definition includes
– Name
– List of attribute names
– Query to specify contents
• Created using CREATE VIEW
• Examples - view 1, 2
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
67
Querying and deleting views
•
•
•
•
SQL queries can be specified on views
Example - query view 1
Deleted using DROP VIEW
Example - view 1A
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
68
Updating views [1]
• View update often ambiguous
– DBMS may choose best option
– User may be asked to specify preferred options
during view definition
• Example - update view 1
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
69
Updating views [2]
• View with single defining table is updatable
if view attributes contain primary key
• Not possible to update
– View defined on multiple queries using joins
– View defined using grouping / aggregate
functions
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
70
Assertions [1]
• More general constraints can be specified
via declarative assertions
• Created using CREATE ASSERTION
• Deleted using DROP ASSERTION
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
71
Assertions [2]
CREATE ASSERTION SALARY_CONSTRAINT
CHECK (NOT EXISTS (SELECT * FROM EMPLOYEE E,
EMPLOYEE M, DEPARTMENT D
WHERE E.SALARY > M.SALARY AND
E.DNO = D.DNUMBER AND
D.MGRSSN = M.SSN) );
• CHECK clause can be used with CREATE
DOMAIN statement
CREATE DOMAIN D_NUM AS INTEGER
CHECK (D_NUM > 0 AND D_NUM < 21);
Jane Reid, BSc/IT DB,
QMUL, 28/1/02
72