Date post: | 31-Dec-2015 |
Category: |
Documents |
Upload: | isabel-wilkerson |
View: | 216 times |
Download: | 0 times |
STRUCTURED QUERY LANGUAGE
Module Coordinator
Tan Szu TakSchool of Information and Communication Technology, Politeknik Brunei
Semester 3 2014
Contents
2
History Data Definition Language Domain Types in SQL Create Table Construct Integrity Constraints in Create Table Creating Table Exercise Drop Table Constructs
*Words with underline can be clicked on
Contents
3
Alter Table Constructs Data Manipulating Language The select Clause The where Clause The from Clause Cartesian Product The join Clause
*Words with underline can be clicked on
Contents
4
Natural Join The Rename Operation String Operations Ordering the Display of Tuples Where Clause Predicates Null Values Null Values and Three Valued Logic
*Words with underline can be clicked on
What are the fours types of Data Model covered in Lecture 2? Hierarchical Network Relational Object Oriented (OO)
In which data model introduced a powerful and flexible query language?
Recap
5
In lecture 3 – Relational Data Model, we covered EIGHT relational algebra operators.
What are they? SELECT PROJECT UNION INTERSECT
Cont. Recap
6
DIFFERENCE PRODUCT JOIN DIVIDE
SELECT Yields values for all rows found in a table that satisfy a
given condition.
PROJECT Yields values for all columns for selected attributes.
UNION Combines all rows from two tables, excluding duplicate
rows.
Cont. Recap
7
JOIN (Natural Join) Links tables by selecting rows with common values in
common attributes.
DIVIDE Uses one single-column tables as the divisor and one
2-column table as the divident.
Cont. Recap
8
IBM Sequel language was developed as part of the System R project at the IBM San Jose Research Laboratory.
Later renamed as Structured Query Language (SQL).
ANSI and ISO standard SQL (version):SQL-86, SQL-89, SQL-92, SQL:1999, SQL:2003, SQL:2008
Commercial systems offer most of SQL-92 features plus varying features sets from later standards.
History
9
The SQL data-definition language (DDL) allows the specification of information about relations, including:
The schema for each relation.
The domain of values associated with each attribute.
Integrity constraints The set of indices to be maintained for each relations.
Security and authorization information for each relations.
The physical storage structure of each relation on disk.
Data Definition Language
10
char(n) – Fixed length character string, with user-specified length n.
varchar(n) – Variable length character strings, with user-specified maximum length n.
int – integer (a finite subset of the integers that is machine-dependent).
smallint – small integer (a machine-dependent subset of the integer domain type).
Domain Types in SQL
11
numeric(p,d) – Fixed point number, with user-specified precision of p digits, with d digits to the right of decimal point.
real, double precision – Floating point and double-precision floating point numbers, with machine-dependent precision.
float(n) – Floating point number, with user-specified precision of at least n digits.
Cont. Domain Types in SQL
12
A SQL relation is defined using the create table command:
create table r (A1 D1, A2 D2, ..., An Dn ,(integrity-constraint1),...,(integrity-constraintk) );
Where: r is the name of the relation each A1 is an attribute name in the schema of relation r. D1 is the data type of values in the domain of attribute A1.
Create Table Construct
13
Example:create table instructor (
ID char(5),name varchar(20) not null,dept_name varchar(20),salary numeric(8, 2));
insert into instructor values (‘10211’, ’Smith’, ’Biology’, 66000);insert into instructor values (‘10211’, null, ’Biology’, 66000);
Cont. Create Table Construct
14
not null ◦attribute cannot be unknown/empty
primary key (A1, ..., An )◦primary key declaration on an attribute
automatically ensures not null
foreign key (Am, ..., An ) references r
Integrity Constraints in Create Table
15
Example: Declare ID as the primary key for instructor.
create table instructor (ID char(5),name varchar(20) not null,dept_name varchar(20),salary numeric(8, 2),primary key (ID),foreign key (dept_name) references department);
Cont. Integrity Constraints in Create Table
16
How to create a table in SQL with the following criteria?
dept_name refers to dept_name in department table.
Creating Table Exercise
17
coursecourse_id (primary key) varchar - 8title varchar - 50dept_name (foreign key) varchar - 20credits numeric – 2 significant, 0
decimal point
create table course ( course_id varchar(8) primary key, title varchar(50), dept_name varchar(20), credits numeric(2,0), foreign key (dept_name) references department );
Primary key declaration can be combined with attribute declaration as shown above
Cont. Creating Table Exercise
18
drop table student◦Deletes the table and its contents. (rollback
disable)
delete from student◦Deletes all contents of table, but retains table
(rollback enable)
truncate table student◦Deletes all contents of table, but retains table
(rollback disable)
Drop Table Constructs
19
alter table◦alter table r add A D where A is the name of the attribute to be
added to relation r and D is the domain of A. All tuples in the relation are assigned null as the
value for the new attribute.
◦alter table r drop A where A is the name of an attribute of relation r Dropping of attributes not supported by many
databases
Alter Table Constructs
20
The SQL data-manipulation language (DML) provide the ability to: Query information Insert tuples Delete tuples Update tuples.
Data Manipulation Language
21
A typical SQL query has the form:
select A1, A2, ..., An
from r1, r2, ..., rm
where P
◦Ai represents an attribute◦Ri represents a relation◦P is a predicate.
The result of an SQL query is a relation.
Cont. Data Definition Language
22
The select clause list the attributes desired in the result of a query
◦corresponds to the projection operation of the relational algebra
Example: find the names of all instructors:select namefrom instructor
The select Clause
23
NOTE: SQL names are case insensitive (i.e., you may use upper- or lower-case letters.)
◦E.g. Name ≡ NAME ≡ name◦Some people use upper case wherever we use bold
font.
SQL allows duplicates in relations as well as in query results.
To force the elimination of duplicates, insert the keyword distinct after select.
Cont. The select Clause
24
E.g. Find the names of all departments with instructor, and remove duplicates
select distinct dept_namefrom instructor
The keyword all specifies that duplicates not be removed.
select all dept_namefrom instructor
Cont. The select Clause
25
An asterisk in the select clause denotes “all attributes”
select *from instructor
The select clause can contain arithmetic expressions involving the operation, +, –, *, and /, and operating on constants or attributes of tuples.
Cont. The select Clause
26
The query: select ID, name, salary/12 from instructor
would return a relation that is the same as the instructor relation, except that the value of the attribute salary is divided by 12.
Cont. The select Clause
27
The where clause specifies conditions that the result must satisfy
◦Corresponds to the selection predicate of the relational algebra.
E.g. To find all instructors in Comp. Sci. dept with salary > 80000
select namefrom instructorwhere dept_name = ‘Comp. Sci.' and salary > 80000
The where Clause
28
Comparison results can be combined using the logical connectives and, or, and not.
where dept_name = ‘Comp. Sci.' or salary > 80000
Comparisons can be applied to results of arithmetic expressions.
where salary/12 > 500
Cont. The where Clause
29Visit this link for more operators
The from clause lists the relations involved in the query◦Corresponds to the Cartesian product operation of
the relational algebra.
Find the Cartesian product instructor X teaches
select * from instructor, teaches◦generates every possible instructor – teaches pair,
with all attributes from both relations
Cartesian product not very useful directly, but useful combined with where-clause condition
The from Clause
30
Cartesian Product: instructor X teaches
31
instructor teaches
Join clause is used to combine rows from two or more tables, based on a common field between them.
Example: For all instructors who have taught some course, find their names and the course ID of the courses they taught.
select name, course_id from instructor, teaches where instructor.ID = teaches.ID
The join Clause
32
Example: Find the course ID, semester, year and title of each course offered by the Comp. Sci. department
select section.course_id, semester, year, title from section, course where section.course_id = course.course_id and dept_name = ‘Comp. Sci.'
Cont. The join Clause
33
Natural join matches tuples with the same values for all common attributes, and retains only one copy of each common column
select * from instructor natural join teaches;
Natural Join
34
List the names of instructors along with the course ID of the courses that they taught.
select name, course_idfrom instructor, teacheswhere instructor.ID = teaches.ID;
select name, course_idfrom instructor natural join teaches;
Cont. Natural Join
35
Tables below will be used as an example to describe natural join.
Cont. Natural Join
36
1. PRODUCT
Cont. Natural Join
37
2. SELECT
3. PROJECT
Cont. Natural Join
38
Danger in natural join: beware of unrelated attributes with same name which get equated incorrectly.
List the names of instructors along with the titles of courses that they teach
Incorrect version (makes course.dept_name = instructor.dept_name)
select name, titlefrom instructor natural join teaches natural join course;
Cont. Natural Join
39
Correct versionselect name, titlefrom instructor natural join teaches,
coursewhere teaches.course_id =
course.course_id;
Another correct versionselect name, titlefrom (instructor natural join teaches)
join course using(course_id);
Cont. Natural Join
40
The SQL allows renaming relations and attributes using the as clause:
old-name as new-name
E.g. select ID, name, salary/12 as monthly_salaryfrom instructor
The Rename Operation
41
Find the names of all instructors who have a higher salary than some instructor in ‘Comp. Sci’.
select distinct T. name from instructor as T, employee as S where T.salary > S.salary and S.dept_name = ‘Comp. Sci.’
Keyword as is optional and may be omitted instructor as T ≡ instructor TKeyword as must be omitted in Oracle
Cont. The Rename Operation
42
SQL includes a string-matching operator for comparisons on character strings. The operator “like” uses patterns that are described using two special characters:
◦percent (%) - The % character matches any substring.
◦underscore (_) - The _ character matches any character.
String Operations
43
Example: Find the names of all instructors whose name includes the substring “dar”.
select namefrom instructorwhere name like '%dar%'
Match the string “100 %”like ‘100 \%' escape '\‘
\ is used the escape character.
Cont. String Operations
44
Patterns are case sensitive.
Pattern matching examples: ‘Intro%’ matches any string beginning with “Intro”.
‘%Comp%’ matches any string containing “Comp” as a substring.
‘_ _ _’ matches any string of exactly three characters.
‘_ _ _ %’ matches any string of at least three characters.
Cont. String Operations
45
SQL supports a variety of string operations such as converting from upper to lower case (and vice
versa)
E.g. SELECT UCASE(CustomerName) AS Customer, City FROM Customers;
finding string length, extracting substrings, etc.
Cont. String Operations
46
List in alphabetic order the names of all instructors select distinct name
from instructororder by name
We may specify desc for descending order or asc for ascending order, for each attribute; ascending order is the default. Example: order by name desc
Can sort on multiple attributesExample: order by dept_name, name
Ordering the Display of Tuples
47
SQL includes a between comparison operator
Example: Find the names of all instructors with salary between $90,000 and $100,000 (that is, > $90,000 and < $100,000)
select name from instructor where salary between 90000 and 100000
Where Clause Predicates
48
It is possible for tuples to have a null value, denoted by null, for some of their attributes
null signifies an unknown value or that a value does not exist.
The result of any arithmetic expression involving null is nullExample: 5 + null returns null
Null Values
49
The predicate is null can be used to check for null values.
Example: Find all instructors whose salary is null.select namefrom instructorwhere salary is null
Any comparison with null returns unknownExample: 5 < null or null <> null or null = null
Cont. Null Values
50
Three-valued logic using the truth value unknown:
OR: (unknown or true) = true, (unknown or false) = unknown (unknown or unknown) = unknown
AND: (true and unknown) = unknown, (false and unknown) = false, (unknown and unknown) = unknown
Null Values and Three Valued Logic
51
NOT: (not unknown) = unknown◦“P is unknown” evaluates to true if predicate P
evaluates to unknown
Result of where clause predicate is treated as false if it evaluates to unknown
Cont. Null Values and Three Valued Logic
52
Find out what is the difference between char VS varchar and varchar VS varchar2.
Find out does double precision mean.
Will cover: Structured Query Language IIAggregate Functions such as: Avg, Min, Max, Sum, Count
Group by, Having, Not Exists
Insert, Delete, Update tuples
Next Lecture
53
Reference: Database System Concepts – 6th EditionLecture Slides by Tan Szu Tak, SICT, Politeknik Brunei