Download SQLSpecial

Document related concepts

DBase wikipedia , lookup

Concurrency control wikipedia , lookup

Tandem Computers wikipedia , lookup

Microsoft Access wikipedia , lookup

Relational algebra wikipedia , lookup

Oracle Database wikipedia , lookup

Ingres (database) wikipedia , lookup

Extensible Storage Engine wikipedia , lookup

Entity–attribute–value model wikipedia , lookup

Functional Database Model wikipedia , lookup

Database wikipedia , lookup

Microsoft Jet Database Engine wikipedia , lookup

Null (SQL) wikipedia , lookup

Clusterpoint wikipedia , lookup

Microsoft SQL Server wikipedia , lookup

Open Database Connectivity wikipedia , lookup

Database model wikipedia , lookup

Relational model wikipedia , lookup

SQL wikipedia , lookup

PL/SQL wikipedia , lookup

Transcript
An Introduction
My Name is
: Rod Simpson
My Faculty is
: Information Technology
My School is
My Home Campus is
: Computer Science and Software
Engineering
: Caulfield
My Office is
: C Block, Room 4.46 (C4.46)
My Phone Number is
: (03) 99032352
My email is
: [email protected]
Special SQL 1 of
Which stands for
School of Computer Science and Software Engineering
Faculty of Information Technology
Special SQL 2 of
Special Session - An Introduction
This session, we are going to explore some of the aspects of
a language known as SQL - Structured Query Language
Why are ‘Computer Languages’ necessary ?
They are the way in which computers can be organised to
process those applications and procedures which we, the
humans, want them to do
Computer Languages are a communication bridge
Special SQL 3 of
Language Forms
Computer commands can be:
– Triggered by Icons as in Windows processing
– or Set up in text form. We will be using this method
in today’s session
Special SQL 4 of
Communicating
LOGICAL
PHYSICAL
Translation
Model
User’s World
Computer’s World
Human Languages
Physical Structures
Special SQL 5 of
Database
Logical
Business Rules
and Definitions
Presentation
Layer
Different
Client
User
Runtime
Interfaces
Modules
Client Hardware
PHYSICAL
Data Access
Layer
Server
Different
Runtime
Database
Modules
Interfaces
Server Hardware
Special SQL 6 of
Managing Data
An important component in any processing is Data
Data needs to be ‘managed’.
Which means that
– Data is available
– Data in accurate
– Data is complete
– Data is accessible only to those who have ‘access
privileges’ (rights)
– Data is representative of the process application
A very formal and widely used technology of managing data
is a Database, which is managed by a Database
Management System
Special SQL 7 of
Database
So what is a Database ?
More importantly, what is a Relational Database ?
The next few overheads will (hopefully) explain
– What a Relational Database is
– And how one can be developed for a particular purpose
Special SQL 8 of
Database
A Database is a shared collection of Inter-Related data
designed to meet the needs of multiple types of users and
applications.
This implies that multiple user VIEWS can be defined
DATABASE = Stored Collection of Related Data
May be physically distributed
Special SQL 9 of
Definition of a
Relational Database
• A relational database is a collection of relations or
two-dimensional tables.
Database
Table Name: EMP
EMPNO
ENAME
JOB
7839
7698
7782
7566
KING
BLAKE
CLARK
JONES
EXECUTIVE
MANAGER
MANAGER
MANAGER
DEPTNO
10
30
10
20
Table Name: DEPT
DEPTNO
10
20
30
40
DNAME
ACCOUNTING
RESEARCH
SALES
OPERATIONS
LOC
CLAYTON
CAULFIELD
PENINSULA
GIPPSLAND
Special SQL 10 of
Data Models
Model of
system
in client’s
mind
Entity model of
client’s model
Table model
of entity model
Server
Tables on disk
Special SQL 11 of
Communicating with a RDBMS
Using SQL
SQL statement
is entered
SQL> SELECT loc
FROM dept;
Statement is sent to
database
Database
Data is displayed
LOC
------------CLAYTON
CAULFIELD
PENINSULA
GIPPSLAND
Special SQL 12 of
Relational Database Management
System
Server
User tables
Data
dictionary
Special SQL 13 of
A Relational Database Model
table
A
table
B
table
C
table
D
table
E
Any table(s) can be joined to any other table(s), provided there
is a means of effecting the join
Primary key / Foreign key concept. Data redundancy
No fixed linkages
Special SQL 14 of
What is ‘Related Data’ ?
Student
Student Name……………..Peirrot
Student I.D………………….614236
Course Enrolled…………….6234
Course Start Date…………03/07/90
Semester Number (Current)…..2
Campus ……………………Clayton
Year of Study …………………..3
Contact Phone…..…03 9934762
Address (In Melbourne)
Address (Home Address)
Unit 1 Code ……………..
Unit 2 Code ...…………...
Unit 3 Code ……………..
Table
Table
Unit (Subject)
Unit 1 Code Psychology 1 Clayton
Unit 2 Code JavaScripts Caulfield
Unit 3 Code Data Mining Caulfield
Unit 4 Code Unit Name Campus
Unit 5 Code Unit Name Campus
Unit 6 Code Unit Name Campus
Unit 7 Code Unit Name Campus
Unit 8 Code Unit Name Campus
Unit 9 Code Unit Name Campus
Unit 10 Code Unit Name Campus
Unit 11 Code Unit Name Campus
Unit 12 Code Unit Name Campus
Unit 13 Code Unit Name Campus
Unit 14 Code Unit Name Campus
Special SQL 15 of
Database Management Software
A DBMS is SOFTWARE which provides access to the database in
an integrated and controlled manner
A DBMS must contain :
1. Data Definition and Structure capabilities
2. Data Manipulation capabilities
Special SQL 16 of
Data Definition and Manipulation
Data Definition Language (DDL)
used to describe data at the database level
Schema level - complete database description
Sub-Schema level - user views (restricted)
Data Manipulation Language (DML)
Provides for these
Create (object)
capabilities
Update
Delete
Modify
Report
Insert
Retrieve (extract)
Drop
Calculation
Special SQL 17 of
Database
In designing a database there is the need to understand
what requirements are made of data analyses, who needs
these analyses, when and in what form.
In all this there is an expectation that the results of ‘queries’,
which is the same as saying data supported by the
database, are accurate, timely and complete.
You will see how these requirements can be built into a
database - which is a model which accurately reflects data
as it occurs and is processed in the ‘real world’.
Special SQL 18 of
Some Thoughts on Data Storage
A major benefit of Computing is the ability to STORE and
RETRIEVE large amounts of data
However, there are a number of processes and other
considerations which need to be worked together to
maximise this benefit
Some very early items are
– What data ?
– What are its sources ?
– What are the volumes / frequency ?
– How long is it to be stored and why this period ?
Special SQL 19 of
Some Thoughts on Data Retrieval
Is the data to be freely available ?
– Are there some limitations on access ?
– How are these access limitations managed ?
What value is inherent in the data ?
Special SQL 20 of
Some General Thoughts
• How is input access to be controlled ?
• When and why is data deleted - who authorises such
deletions ?
• What does the ‘data’ consist of - characters, objects, audio
visual, TV, audio, animation ?
• What is the optimum method of storage (organisation) ?
Special SQL 21 of
DBMS Requirements
Querying Capabilities
Data Displays (Presentation)
Data entry
Data Validation
Data Deletion
AND Data Integrity, Security, Consistency and Concurrency
Capabilities
Special SQL 22 of
A quick introduction to the developer of
the Relational Data Base
Dr. E. Codd
Special SQL 23 of
A Primary Key - What’s that ?
• McFadden, Hoffer and Prescott define a Primary Key as :
An attribute (or combination of attributes) which uniquely
identifies each row in a relation. (table)
• Richard T. Watson has this to say:
The primary key definition block specifies a set of column
values comprising the primary key. Once a Primary Key is
defined, the system enforces its uniqueness by checking
that the Primary Key of any new row does not already exist
in the table.
Special SQL 24 of
And - A Foreign Key ??
• McFadden, Hoffer and Prescott’s definition:
An attribute (or attributes) in a relation (table) of a database
which serves as the Primary Key of another relation (table)
in the same database.
• Richard T. Watson says:
An attribute (or attributes) that is a Primary Key in the same
table, or another table. It is the method of recording relations
in a relational database.
And, both the Primary and Foreign Key(s) should be drawn
from the same Domain.
Special SQL 25 of
2 relations (tables)
EMPNUM
NAME
Date of Birth
DEPTNUM
3
JONES
16-05-1956
605
Referencing
7
SMITH
23-09-1965
432
Table
11
ADAMS
11-08-1972
201
15
NGUYEN
23-10-1964
314
18
PHAN
16-11-1976
201
23
SMITH
19-09-1974
314
Relation (Table) Name : EMP
Relation Schema: EMP(empnum,name,date of birth,deptnum)
DEPTNUM
201
314
432
605
DEPTNAME
Production
Finance
Information Systems
Administration
Relation (Table) Name : DEPT
Relation Schema: DEPT(deptnum, deptname)
Referenced
Table
Special SQL 26 of
Relational Database
Data is represented in ROW and COLUMN form (matrix)
(attribute)
Collections of related data ---> TABLES (relations)
1 or more tables
----> DATA BASE
ATTRIBUTES are generally static
ROWS are DYNAMIC and Time-Varying
Special SQL 27 of
Some RDB Considerations
•
•
•
•
•
•
•
Data is held in tables
No order of data in tables - row or attribute
Concept of Foreign Key - Primary Key relationship
Data Typing - including nulls
Query Access - insert, update, delete, retrieval
Indexing on candidate (and Primary) keys
Integrity Constraints
Attribute value ranges
Referential Integrity (Foreign Key - Primary Key)
Entity Integrity
User Defined Integrity
Special SQL 28 of
Some RDB Considerations
• Domain constraints
• User defined ‘Rules’ e.g. quantities and values must not be
negative; pricing rate must not be zero
• Recovery procedures
• No explicit linkages between tables
• Linking or embedding database operations in a procedural
language (Cobol, C ..)
• Databases may be distributed across similar or different
DBMSs
• Security features
Special SQL 29 of
So, now that the scene has been set
let’s get on with the business of the day
which is
‘An Introduction to SQL’
Special SQL 30 of
What is ‘SQL’ ?
SQL is an internationally recognised programming language
for
– defining
– maintaining relational databases
It originated with IBM in 1977/78 as commercial products
were being created to use the relational database
management approach for Information Retrievals
It became a de facto standard, and became an official
standard in 1986 when ANSI released a document X3.1351986 titled ‘Database Language SQL’
ISO adopted this standard in 1987
Special SQL 31 of
SQL’s History
SQL-86 was updated and enhanced in 1989 (ANSI X3.1681989 ‘Database Language - Embedded SQL’ (April)
In October 1989, there was a further update ‘ANSI X3.135-1989
‘Database Language - SQL with Integrity Enhancement’ (this
was known as SQL-89)
In August 1992 these was a joint ANSI/ISO release. It was
ISO/IEC 9075:1992 ‘Database Language SQL’ (also known
as SQL-92)
This was adopted as a Federal Information Processing
Standard in the United States.
Special SQL 32 of
SQL’s History
There was a further refinement FIPS PUB 127-2 “database
Language SQL” specified US Government requirements for
the SQL-92 standard
Finally, to bring us up to date, ISO/IEC 9075:1999 is the
latest SQL standard, ‘Information Technology - Database
Languages - SQL’ (known as SQL3)
And there is current work on SQL-X This will provide the
linking of SQL with XML in Web based access to databases
Special SQL 33 of
Related ISO Documents
There are 5 inter-related documents :
1. SQL Framework (ISO/IEC 9065-1) - this defines the
framework on which SQL is based, and also specifies the
general requirements for SQL conformance.
All parts of the Standard are dependent on SQL Framework
2. SQL Foundation (ISO/IEC 9075-2) - this defines the
fundamental syntax and operations of SQL
All parts of the Standard (except SQL Frameworks) are
dependent on SQL Foundation
Special SQL 34 of
Related ISO Documents
3. SQL/Call-Level Interface (ISO/IEC 9075-3) - this defines the
an application programming interface to SQL. (no part of the
standard is dependent on SQL/CLI)
4. SQL Persistent Stored Modules (PSM) (ISO/IEC 9075-4) this defines the control structures which define SQL Routines
and the Modules which may contain SQL Routines. (no part
of the standard is dependent on SQL/PSM)
5. SQL/Host Language Bindings (ISO/IEC 9075-5) - this defines
the methods for embedding SQL statements in an application
written in a standard programming language. (no part of the
standard is dependent on SQL/Bindings)
Special SQL 35 of
Some Concepts
A database system is a computerised record keeping system
A database is a collection of structured data files and
associated indexes
A database user must be able to add, retrieve, insert, update
and delete data and files - subject to appropriate privileges
A set is any collection of definite distinguishable things.
Olympians for instance are a ‘set’ of people.
So are Students
Special SQL 36 of
A Relation
Relations exist between 2 or more ‘things’
There is a relation between Lleyton Hewitt and tennis
There is a relation between Steve Waugh and cricket
There is a relation between Tiger Woods and golf
We could present this as :
Name
Sport
Lleyton Hewitt
Tennis
Steve Waugh
Cricket
Tiger Woods
Golf
and we have a relation of degree 2. We can also have relations
of any required degree 3, 4, 5 ……….
Special SQL 37 of
Another Relation
We could have this
Name
Activity
Smith, J
Doctor
Ellis,T
Blacksmith
Werija,K
Lecturer
Brack,S
Premier
Residence
Clayton
Colac
Caulfield
Ballarat
Date of Death
22-09-1998
12-10-1976
???
???
This is a relation, or table, of degree 4
Notice that each row has only 1 entry in each ‘column’ or
attribute - this is called the ‘atomic value’
Special SQL 38 of
Operations on Sets of Data
SQL operates on ‘sets’ of data
There must be ‘set operations’
The SQL statements which are associated with operations are
Select
From
Where
Having
Group By
Order By
Special SQL 39 of
SQL Tables
A Table :
Is a named set of rows - an ordered row of one or more
column names, together with zero or more unordered rows of
data values
Tables store data about a specific entity - each row in a Table
describes a single occurrence of that entity.
The SQL Standard defines 3 types of tables - Base tables,
Views, and Derived Tables
Special SQL 40 of
Data Types
• Data types have a number of functions in database design
and data content
• They add to the Integrity features of a database by their ‘builtin’ features associated with
– value limitations of attribute sets triggered by inherent
constraint of the datatype
– limitation or restriction of the representation of content of
an attribute set
Special SQL 41 of
Data Types - Oracle
• Primary datatypes are:
• CHAR ,VARCHAR2, NCHAR, DATE, LONG, LONGRAW, NUMBER,
RAW and ROWID
• Compatibility with SQL databases allows for these additional
or expansion datatypes:
• CHAR(size) Fixed length. Max. size 255. Default 1
– Left justified and padded with blanks
• VARCHAR2(n) Variable length character data. Max size 4000
in Oracle8, 2000 in previous Oracle versions
Special SQL 42 of
Data Types - Oracle
• NCHAR Character datatype. Supports 16 bit (2byte) binary
character codes
• DATE
Valid dates from Jan 1, 4712 B.C. to December
31, 4712 A.D.
• NUMBER(l,d) Numeric data. l = length, d = number of
decimal digits
• LONG Stores variable-length character data up to 2Gb
Special SQL 43 of
Data Types - Oracle
• BLOB - Binary large Object. Up to 4Gb, Binary data
• CLOB - Character Large Object. Up to 4Gb
• BFILE - Binary File. Read only binary stored outside the
database. Length depends on the Operating
System
• NCLOB - A Clob column which supports a multibyte
character set
Special SQL 44 of
Microsoft Access SQL Datatypes
•
•
•
•
•
•
•
•
•
•
•
Binary 1 byte
Bit
1 byte (logical field)
Counter 4 bytes (Long in the Jet db engine)
Currency 8 bytes -922,337,203,658,477.5808 to
+922,337,203,658,477,5807
Datetime 8 bytes between the years 100 and 9999
Single
4 bytes -3.402823e38 to 3.402823e38
Double 8 bytes -1.7976931348623e38 to +1.79 ……..
Short
2 bytes -32,768 to + 32,767
Long
4 bytes -2,147,483,647 to + 2,147,483,647
Text
1 byte per character 0 to 255 characters
Longtext 0 to 1.2 Gb
Special SQL 45 of
We Are Going …..
1. To introduce the Data Definition and Data Manipulation
components of SQL (Structured Query Language) as
expressed in Oracle
2. To proceed through some of the SQL commands such as
Select, From, Where, Having, Group By, Order By
3. To introduce other components such as Logical Operators,
Arithmetic Operators, Sub-queries and Views
Special SQL 46 of
Why SQL ?
• SQL is the one industry standard language for querying
databases
• All of the database features can be accessed via SQL - which
doesn’t occur with a Graphics interface
• GUI tools frequently do not exploit the underlying language
functionality
• In client-server applications, an SQL query in any application
host language will return exactly the same results (ODBC)
Special SQL 47 of
SQL Statements
•
SELECT
Data retrieval
•
•
•
INSERT
UPDATE
DELETE
Data manipulation language
(DML)
•
•
•
•
•
CREATE
ALTER
DROP
RENAME
TRUNCATE
•
•
•
COMMIT
ROLLBACK
SAVEPOINT
Transaction control
•
•
GRANT
REVOKE
Data control language (DCL)
Data definition language
(DDL)
Special SQL 48 of
DDL - Data Definition
CREATE (1) Table - define table name, attributes, types
(2) View
- define user view of data
(3) Index - create index on nominated attributes
DROP
(1) Table - delete table, attributes and values
(2) View
- delete user view(s)
(3) Index - delete index, indexes
NOTE: Oracle supports the 'owner' concept.
Hence only 'owners' can DROP nnnn
Oracle DBMS has an ALTER command to vary attribute
characteristics.
Special SQL 49 of
DML - Data Manipulation Language
Group 1 - Data Modification
Insert - Add a single row (interactive)
- Perform successive INSERTS as a
'transaction ‘set’ - interactive
Copy - From an external file to a database table
- From a table to an external file
Update - Amend attribute values in rows
Delete - Delete rows of data from a table
Special SQL 50 of
Group 2
DML - Data Manipulation Language
DATA CONTROL - User control of transaction processing
Commit
- Commit or enable changes to the database
Rollback
- Rollback and reprocess (or some other
action) transaction which could not be
COMMITTed .
Group 3
DATA SECURITY - Authority over users - generally only
available to the DBA
Grant
- Allow access privileges to users (e.g.
read,write,update to nominated tables or attribute values in
tables)
Revoke
- Revoke or cancel access privileges
Special SQL 51 of
CREATE
The syntax is :
create table <tablename> ( columnname format
{,columnname format})
e.g. create table wages(name varchar2(10), I_D number(2,0),
Department varchar2(3),
date_comm date);
OR
create table wages(name varchar2(10) not null,
I_D number(2,0) not null,
Department varchar2(3) not null,
date_comm date) not null;
Special SQL 52 of
INSERT
This command allows data to be inserted, one row at a time,
into an existing table
Syntax: Insert into <tablename> (list of attributes)
values (list of values)
Note: The list of attributes can be ignored providing the order
of attribute values, and completeness of attribute instances,
is as per the table list.
example:
insert into employee(name, salary, birth_year)
values(‘Jones, Bill’, 45000,1967);
Special SQL 53 of
UPDATE
Replaces values of the specified columns with expression values for all
rows satisfying the search-condition.
Expressions in the set clause may be constants or column values from the
UPDATE tablename or FROM tablename
UPDATE PART
SET price = price * 1.1
WHERE price < 20;
Special SQL 54 of
DELETE
DELETE FROM tablename [corr-name]
[ WHERE search-condition ]
Delete one or many rows in a table.
Without the search condition, all rows will be deleted
DELETE FROM PART WHERE qoh < 4.00;
Special SQL 55 of
General Form of a Query
SELECT as a function applies algebra in developing a result
table from a base table, (or tables). The result table may
have 0 to n rows...
The Select Command is used to query data in the database..
Its syntax is : Select (select-list - attributes or derived data)
From (table name or names)
Where (sets up conditions)
Group By (attribute names)
Having (search-conditions)
Order By (attribute name or names)
Special SQL 56 of
General Form of a Query
SELECT and FROM are compulsory.
Other clauses are optional but occur in the order shown
HAVING is normally associated with GROUP BY
Special SQL 57 of
Select Example (Oracle)
PART
PARTNO
P1
P2
P3
PNAME
NUT
BOLT
CARAVAN
PRICE
0.20
1.00
5000.00
QOH
20
40
3
SELECT pname, price*qoh AS pvalue
FROM PART
WHERE price > 0.20 AND price * qoh > 30
ORDER BY pname desc;
pname
CARAVAN
BOLT
pvalue
15,000.00
40.00
Special SQL 58 of
Same Data - Oracle Datatypes
Oracle does not support a ‘money’ datatype as in Ingres
nor a ‘currency’ datatype as in Microsoft.
The Oracle datatype ‘numeric’ has many forms and some
of these are shown below using the value 7456123.89
number
results in 7456123.89 being stored
number(9)
results in 7456123 being stored
number(9,2) results in 7456123.89 being stored
number(9,1) results in 7456123.9 being stored
number(15,1) results in 7456123.9 being stored
To represent $ values in an output table :
column (attribute) format $99.999.00 heading (new name)
Special SQL 59 of
Expressions in Select
Arithmetic operators are + - ** * /
Comparison operators are = != <> ^= > < >= <=
Logical operators are AND OR NOT
Parentheses may be used to alter order of evaluation unary, **, * /, + Wildcard % = any string of zero or more character
_ = any one character
[ ] = any of the characters enclosed in
brackets
A range of numeric, string, date and other functions are
available.
Special SQL 60 of
SELECT Vocabulary
ALL
BY
GROUP
LIKE
ORDER
AND
DISTINCT
HAVING
NOT
SELECT
Arithmetic Operators
Relational Operators
Logical Operators
Parentheses
Special Operators
Existential Operator
ANY
EXISTS
IS
NULL
UNION
BETWEEN
FROM
IN
OR
WHERE
+ *
/
=
!=
< > <= >=
AND OR
NOT
(
)
BETWEEN IN LIKE NULL
EXISTS
Special SQL 61 of
Arithmetic Operators
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
?
?
Special SQL 62 of
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
Special SQL 63 of
Combining Logical Operators
Which prime ministers were born in NSW and then represented Victoria
or have simply not served less than two years?
SELECT
FROM
WHERE
AND
OR
PM_NAME, STATE_BORN, STATE_REP, YRS_SERVED
PRIME _MINISTER
STATE_REP = ‘VIC’
STATE_BORN = ‘NSW’
NOT 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
Special SQL 64 of
Select Examples - ‘PART’ table
SELECT PNAME FROM PART
WHERE QOH IS NULL;
Selects those rows where qoh has a null value
SELECT * FROM PART
WHERE PNAME LIKE '_ _T' or PNAME LIKE
'%LT';
Selects rows where pname has three letters the
last of which is a T or PNAME ends in LT
Special SQL 65 of
SET Funtions
• A SET Function is one which operates on an entire column of
values, not just a single value
• The SET functions supported are:
Name
count
sum
avg
max
min
Format(Result)
Description
integer
Count of Occurrences
integer,float,money
Summation
float,money
Average (sum/count)
same as the argument Maximum value
same as the argument Minimum value
Special SQL 66 of
Use of SET functions
PART
PartNo
P1
P2
P3
Pname
Price
NUT
1.00
BOLT
1.00
CARAVAN 5000.00
QOH
20
20
3
SELECT count(partno) Part_count, avg(price) Av_price,
count(distinct price) Price_count
FROM part;
Part_count Av_Price
3
1667.33
Price_count
2
Set functions supported = avg count max min sum
Set functions may not be used directly in a search condition
Special SQL 67 of
SubQueries
Provides the facility of a query supplying dynamic values to
another query for use in the search conditions of the main
query.
Example: Give the name and age at which death occurred for
each Prime Minister who died at an age less than
the average .
List in order of age at death.
SELECT PM_NAME, DEATH_AGE
FROM PRIME_MINISTER
WHERE DEATH_AGE < ( SELECT AVG(DEATH_AGE)
FROM PRIME_MINISTER);
The subquery computes the average age at death.
The main query then selects the appropriate names and
ages based on the values supplied by the sub-query.
(in this case where the age at death is less than the average)
Special SQL 68 of
SubQueries
Which prime minister died the oldest? Show the name and age.
SELECT
FROM
WHERE
PM_NAME, DEATH_AGE
PRIME_MINISTER
DEATH_AGE = (SELECT MAX(DEATH_AGE)
FROM PRIME_MINISTER);
PM_NAME
Forde F M
DEATH_AGE
93
Special SQL 69 of
Create View
· Provides logical data independence when base table
structure changes.
· Same data may be seen in different ways by different users.
· User’s perception may be simplified and views provide
automatic security.
Special SQL 70 of
Create View
Emp (empno, empname, salary_pa, deptno)
Dept (deptno, dname)
CREATE VIEW empdetails (empno, empname,
dname, salary_fn) AS
SELECT e.empno, e.empname, d.dname,
e.salary / 26
FROM emp e, dept d
WHERE e.deptno = d.deptno;
Special SQL 71 of
To Execute a View
To run the previous View the command structure would be:
Select * from empdetails;
Conditions (where) could be applied to further limit the output
(result table) scope.
Special SQL 72 of
The Purpose of SQL... and so ?
Oracle has a procedural language - PL/SQL
It also supports
packages
procedures
snapshots
triggers
which are developed to provide specific application logic
Used to include Integrity - ‘the database cannot be used on
Saturdays or Sundays’
Special SQL 73 of
SQL Language Elements
Normally, SQL statements are case insensitive.
The set of SQL Language characters contains
– the uppercase simple Latin characters A to Z
– The lowercase simple characters a to z
– The digits 0 to 9
– The set of special SQL characters
Special SQL 74 of
And here they are
(
)
“
‘
%
&
*
/
+
,
.
The space character
The left parenthesis
The right parenthesis
The double quote mark
The single quote mark
The percent sign
The ampersand
The asterisk or multiplication sign
The solidus or division sign
The plus sign
The minus sign or dash
The comma
The full stop
:
;
<
>
?
[
]
_
|
=
{
}
^
The colon
The semicolon
The less than operator
The greater than operator
The question mark
The left bracket
The right bracket
The underscore
The vertical bar
The equals operator
The left brace
The right brace
The circumflex
Special SQL 75 of