Lecture 21 - More on SQL

Transcription

Lecture 21 - More on SQL
Lecture 21
30/3/15
Indexes (Manual (10-31)
• Indexes are special lookup
tables that the database search
engine can use to speed up data
retrieval.
• An index can be created in a
table to find data more quickly
and efficiently.
• An index is a pointer to data in a
table.
• An index in a database is very
similar to an index in the back of
a book.
• The users cannot see the
indexes, they are just used to
speed up searches/queries.
• SQL CREATE INDEX Syntax
• Creates an index on a table.
Duplicate values are allowed:
CREATE INDEX index_name
ON table_name (column_name)
• Note: Updating a table with
indexes takes more time than
updating a table without
(because the indexes also
need an update). So you
should only create indexes on
columns (and tables) that will
be frequently searched
against.
CREATE INDEX emp_index
ON EMPLOYEE (EMP_NO, EMP_NAME);
CREATE INDEX empindex2
ON EMPLOYEE (EMP_NO, EMP_NAME, JOB,SAL);
When should indexes be
avoided?
• Although indexes are intended to enhance a database's
performance, there are times when they should be avoided.
The following guidelines indicate when the use of an index
should be reconsidered:
• Indexes should not be used on small tables.
• Tables that have frequent, large batch update or insert
operations.
• Indexes should not be used on columns that contain a high
number of NULL values.
• Columns that are frequently manipulated should not be indexed.
Other SQL Statements
DROP INDEX
index_name
• The ALTER TABLE statement is
used to add, delete, or modify
columns in an existing table.
• ALTER TABLE table_name
ADD column_name datatype
• ALTER TABLE table_name
DROP COLUMN column_name
• ALTER TABLE table_name
MODIFY column_name datatype
VIEW (Manual 10-4)
• Use the CREATE VIEW statement to define a view, which is a
logical table based on one or more tables or views.
• A view contains no data itself.
• The tables upon which a view is based are called base tables.
• Views are virtual tables formed by a query.
• A view is a dictionary object that you can use until you drop it.
Views are not updatable.
More on Views
Advantages
• To restrict data access
• To provide data
independence
• To make complex queries
easy
• To present different
views of the same data
Example -
CREATE VIEW empview1
AS SELECT emp_no,
emp_name, sal
FROM EMPLOYEE
WHERE DEPT_NO =3;
Correlated Sub queries
• As opposed to a regular subquery, where the outer query depends
on values provided by the inner query
• A correlated subquery is one where the inner query depends on
values provided by the outer query
• This means that in a correlated subquery, the inner query is
executed repeatedly, once for each row that might be selected by
the outer query
• Correlated subqueries can produce result tables that answer
complex management questions.
Some notes –
http://www.zentut.com/sql-tutorial/understanding-correlatedsubquery/
The Process
The sequence that is followed is:
• Get the first row from the outer query
• Run the inner query using the value from the row from step A
• Determine whether to return a result based on the outer
where clause
• Repeat process until all outer rows have been selected
9
EMP_NO EMP_NAME
JOB
DEPT_NO SAL
COMM
HIREDATE MANAGER_NO
---------- -------------------- -------------------- ---------- -------------------- -------------------- --------- ---------3 HEARNE
ANALYST
4
800
100
07-JAN-11
4 BYRNE
CLERK
3
100
20-FEB-09
6 WALSH
MANAGER
4
3500
11-OCT-07
8 HARTE
ACCOUNTANT
3
700
300
20-JAN-12
11 CASEY
MANAGER
1
1000
150
17-OCT-08
12 MURRAY
CLERK
2
360
80
27-JAN-12
9 DOHERTY
CLERK
3
150
28-JUN-11
10 MARTIN
MANAGER
2
900
190
07-SEP-13
Continued…
FULL DATASET -
No other analyst in my dataset no matching inner
record
EMP_NAME
JOB
SAL
-------------------- -------------------- -------------------HEARNE
ANALYST
800
BYRNE
CLERK
100
WALSH
MANAGER
3500
HARTE
ACCOUNTANT
700
CASEY
MANAGER
1000
MURRAY
CLERK
360
DOHERTY
CLERK
150
MARTIN
MANAGER
900
select emp_name, job, sal
from employee e
where sal <
(
select avg(sal) from
employee where job=e.job
);
No other accountant in my dataset no matching
inner record
OUTPUT -
EMP_NAME
JOB
SAL
-------------------- -------------------- -------------------BYRNE
CLERK
100
CASEY
MANAGER
1000
DOHERTY
CLERK
150
MARTIN
MANAGER
900
Example of the process
• Lets look at this process for the query above.
 Get first row from employee table (outer query)
 Run the inner query.
 The where clause ensures that the job type matches between
the two rows.
 Get the average salary for the job type from the outer row
 The outer where clause determines whether or not to return a
row.
 In this case, is the salary less than the average salary for that
employees job type.
 Get the next row and repeat.
12
Which is it?
If you are unsure whether a sub-query is a correlated sub-query,
there is a simple check.
• If the inner query compares to a row from the outer query,
then it is a correlated sub-query.
http://www.tutorialspoint.com/sql_certificate/subqueries_to_sol
ve_queries.htm
13
Creating Constraints
Constraints are basically rules to stop a user doing something
with a table that you don’t want to happen.
• Constraints are used by Oracle to enforce rules whenever a
row is added, changed, or removed.
• There are two types of constraints : Table constraints; and
Column Constraints.
15
Constraints continued..
• The following are the different constraints.
•
•
•
•
•
•
NOT NULL
DEFAULT
UNIQUE
PRIMARY KEY
FOREIGN KEY
CHECK
16
Not Null
Columns, by default, allow NULL values. By specify NOT NULL we
are saying that NULLs are not allowing in a particular column.
Create table addresses ( name varchar2(30) not null, address
varchar2(50) not null, phone number(10) );
• Note that the constraint can also be given a name.
Create table phones (name varchar2(30) constraint namenull
not null,
phone number(9));
17
Default
If a value isn’t supplied for a column, then a default can be
supplied. If we don’t use the default constraint, a NULL value
would be entered.
Create table addresses (name varchar2(30) not null, address
varchar2(50) default 'None Given', phone number(10) );
• In this example, if no value is specified for address, “None
Given” is inserted in the column.
• The default constraint cannot be given a name
18
Unique
• Unique constraints ensure that the contents of a column (or
columns) are unique.
•
There can be no duplicate entries in a column.
• Unique constraints can be applied at the column level or at the table
level.
At the column level we simply add the constraint after the column
definition.
For table level, we are putting a constraint on two or more columns, so
we add the constraint after all the column definitions.
19
Unique (cont)
• The following is an example of a column level unique constraint.
create table phone
(name char(20) constraint onename unique, phonenum number(10));
• Nulls are allowed in a column with a unique constraint.
• The following is an example of a table level constraint
create table phone
(firstname char(10),
secondname char(20),
course char(15),
startdate date,
constraint onename unique(firstname,secondname));
20
Primary Key
There can only be one primary key per table and it is used to
ensure that each row is distinctive. Each row is identified
uniquely by its primary key.
• A primary key, like a unique constraint, can be made up of one
or more columns. The difference is that NULLs are allowed in
single column unique constraints, there can be no nulls in a
primary key.
21
Primary Key (cont)
To create a column level constraint, we run (for example)
create table phone
(name char(20) constraint keyone primary key,
address char(50),
phone number(10));
• An example of a table level constraint is
create table phone
(name char(20),
address char(50), phone number(10),
constraint keyone primary key(name));
22
Foreign Key
• A foreign key is used to link the information in two tables
23
Foreign Key (cont)
The command to create the phone table is
create table phone
(name char(8) primary key,
areaname char(8),
phone number(8),
constraint fkeyarea foreign key (areaname) references
area(areaname));
• This is a table level constraint, the equivalent command for a
column level constraint is
create table phone
(name char(8) primary key,
areaname char(8) constraint forkey references area(areaname),phone
number(8));
24
Composite Foreign Keys
• The idea of composite foreign keys is simply referencing more
than one column.
• To create composite foreign key constraints (which can only
be table level) for the example above, we run
Create table( …
…
, constraint fkeyarea foreign key (division,section) references
departments(division,section)
);
We can combine up to 16 columns in a composite foreign key
constraint.
25
Referential Integrity
• This means that the foreign key ensure that references
between tables (links) can not “get lost”
26
Referential Integrity (cont.)
The original constraint we used in creating the phone table was
Create table( …
…
, constraint fkeyarea foreign key (areaname) references area(areaname)
);
To allow “cascading deletions” (deleting in one table cascades into tables
referencing it) we change this command to
Create table( …
…
, constraint fkeyarea foreign key (areaname) references area(areaname)
on delete cascade
);
27
Check Constraints
• Check constraints offer the most flexibility. Rather than Oracle
defining how a constraint works, we can impose our own rules.
For example
create table money
(name char(10),
sal number(7,2) constraint mycheckcon check (sal > 4.8)
);
28
Overview SQL
• Select * from table
name;
• Order by
• Where
• Group by (aggregate
functions)
• Having
• Distinct
• Comparison Operators
• Wildcard like ‘%’
•
•
•
•
•
•
•
•
•
•
•
Create table
Insert
Insert all
Update
Delete
Alter
Dual
Sysdate
Table alias
Column alias
Constraints
29
Overview SQL
• Group functions e.g.
• Upper/Lower/Initcap/Concat/ avg, max, min, count,
sum
lpad/rpad/instr/ltrim/
• rtrim/soundex/length/
• Joins - equijoins, inner
joins, outer joins
• replace
• All, Any, some, Exists
• Number functions
• Round/trunc/sign/ceil/floor/p • Sub-queries (query
ower
within a query)
• Date functions
• Correlated sub query
• Months_between/add_mont (where the outer query
hs/next_day/last_day/round
provides a value to the
inner query)
• Index
• Character Functions
30