SQL - A Relational Database Language |
1970 - Codd Defines Relational Database Model
1974 - 1978 IBM System/R Project
1979 - Oracle Commercial RDBMS
1981 - INGRES & IBM SQL/DS
1982 - 1986 ANSI SQL Standard Developed/Ratified
1987 - ISO SQL Standard
Many versions exist from different manufacturers
ISO/ANSI Standard contains less than 30 statement types
Grouped into:
Used to specify a new relation by giving it a name and specifying each of its attributes
create table student
(stuid char (5) not null,
stln varchar(15) not null,
stfn varchar(15) not null,
major varchar(15) not null,
credits integer );
Used to delete a relation
drop table student;
Used to add an attribute to one of the existing relations in the database
alter table student add
birth_date char(9);
A query can consist of up to six clauses, the first two mandatory :
select <attribute list>
from <table list>
[where <condition>]
[group by <group attribute(s)>]
[having <group condition>]
[order by <attribute list>]
The select - clause lists the attributes or functions to be retrieved.
The from - clause specifies all relations needed in the query but not those needed in nested queries.
The where - clause specifies the conditions for selection of tuples from theses relations.
Group by specifies grouping attributes, whereas having specifies a condition on the groups being selected rather than on the individual tuples.
The built - in aggregate functions count, sum, min, max, and avg are used in conjunction with grouping.
Order by specifies an order for displaying the result of a query.
Simple Retrieval With Condition
Problem:Get names, ids and number of credits of all math majors from a university database
SQL Query:
select stfn, stln, stuid, credits
from student
where major = 'math;
p < stfn, stln, stuid, credits > (s major = mat(student))
Single relation name in from-clause is similar to select - project pair of relational algebra operations
Problem: Get the names of all math majors who have more than 30 credits.
SQL Query:
select stfn, stln
from student
where major = 'math and credits > 30;
Problem: Find ids and names of all students taking art103a.
SQL Query:
select enrolment.stuid, stfn, stln
from student, enrolment
where course# = 'art103a'
and enrolment.stuid = student.stuid;
select-project-join query: course# = 'art103a' selection condition;
enrolment.stuid = student.stuid - join condition.
Order by
Used to order the tuples in the result. the keyword asc can be used to specify ascending order explicitly, desc - descending order
Problem:Get names and ids of all faculty members, arranged in alphabetical order by name.
SQL Query:
select facid, facname
from faculty
order by facname;
Dealing With Ambiguous Attribute Names
Problem:Get a list of all courses that meet in the same room, with their schedules and room numbers
SQL Query:
select copy1.course#, copy1.sched, copy1.room, copy2.course#, copy2.sched
from class copy1, class copy2
wherecopy1.room = copy2.room
andcopy1.course# < copy2.course#;
Use of '*'
Which stands for all the attributes
Problem: Get all information about csc faculty.
SQL Query:
select *
fromfaculty
where dept = 'csc';
SQL does not treat a relation as a set.
Not automatically eliminates the duplicate tuples - expensive operation, elimination by the user wish, using aggregation functions
Key distinct, meaning that only distinct tuples should remain in the result
Problem:Find the number of credits
SQL Query:
select credits
from student;
SQL Query:
select distinct credits
from student;
Complete select query within the where-clause of another query
Problem:Get an alphabetical list of names and ids of all students in any class taught by faculty member f110.
SQL Query:
select stfn, stln, stuid
from student
where stuid in
(select stuid
from enrolment
where course# in
(select course#
from class
where facid = 'f110'))
order by stfn asc;
Problem:Find the number of departments that have faculty in them.
SQL Query:
select count (distinct dept)
from faculty;
Problem: Find the average number of credits students have.
SQL Query:
select avg (credits)
from student;
Problem: Find the student with the largest number of credits.
SQL Query:
select stuid, stfn, stln
from student
where credits =
(select max (credits)
from student);
Problem: Find the id of the student( s ) with the highest grade in any course.
SQL Query:
select stuid
fromenrolment
wheregrade =
(select min ( grade )
from enrolment);
Problem: Assuming that each course is three credits, list, for each student, the number of courses that he or she has completed.
SQL Query:
select stuid, 'number of courses =', credits/3
from student;
Group by - clause specifies the grouping attributes, which must also appear in the select-clause, so that the value of applying. Each function on the group of tuples appears along with the value of the grouping attribute(s).
Problem: Find each course, show the number of students enrolled.
SQL Query:
select course#, count(*)
from enrolment
group by course#;
Can appear only in conjunction with group by-clause. Having provides a condition on the group of tuples associated with each value of the grouping attributes, and only the groups that satisfy the condition are retrieved in the result of the query.
Problem: Find all courses in which fewer than three students are enrolled.
SQL Query:
select course#
from enrolment
group by course#
having count(*) < 3;
SQL allows queries that check if a value is null.
Problem: Find the stuid and course# of all students whose grades in that course are missing.
SQL Query:
select course#, stuid
from enrolment
where grade is null;
Practical Knowledge
Egs
sales
salesman | area | qtysold | value |
223 | 08 | 20 | 6000 |
277 | 01 | 25 | 8092 |
289 | 02 | 16 | 7131 |
301 | 02 | 31 | 5992 |
310 | 01 | 32 | 6109 |
319 | 08 | 25 | 7006 |
334 | 01 | 18 | 5817 |
1. select area, qtysold from sales;
area | qtysold |
08 | 20 |
01 | 25 |
02 | 16 |
02 | 31 |
01 | 32 |
08 | 25 |
01 | 18 |
2. select area, qtysold from sales where value > 7000;
area | qtysold |
01 | 25 |
02 | 16 |
08 | 25 |
3. select distinct area from sales;
area |
08 |
01 |
02 |
4. Group by creates sub-totals:-
select avg(qtysold) from sales;
avg(qtysold) |
23.857 |
select avg(qtysold) from sales group by area;
area | avg(qtysold) |
08 | 22.5 |
01 | 25 |
02 | 23.5 |
5. Having selects/rejects row groups
select avg(qtysold) from sales group by area
having avg(qtysold)<23;
area | avg(qtysold) |
01 | 25 |
02 | 23.5 |
Insert - adds new data
insert into table [(column-list)]
values {(insert-list) | query-spec}
Eg
insert into sales (salesman,area,qtysold,value)
values (351,08,3,675) ;
or
insert into sales values (351,08,3,675);
sales
salesman | area | qtysold | value |
351 | 08 | 3 | 675 |
223 | 08 | 20 | 6000 |
277 | 01 | 25 | 8092 |
289 | 02 | 16 | 7131 |
301 | 02 | 31 | 5992 |
310 | 01 | 32 | 6109 |
319 | 08 | 25 | 7006 |
334 | 01 | 18 | 5817 |
Note values can be taken from other tables, using select clause, instead of values!
Delete - removes data
delete from table [where search-condition]
Egs
1. All rows of a table:-
delete from sales;
2. Selected rows:-
delete from sales where salesman=351;
sales
salesman | area | qtysold | value |
223 | 08 | 20 | 6000 |
277 | 01 | 25 | 8092 |
289 | 02 | 16 | 7131 |
301 | 02 | 31 | 5992 |
310 | 01 | 32 | 6109 |
319 | 08 | 25 | 7006 |
334 | 01 | 18 | 5817 |
3. Using sub-queries to select items
costcentres
sarea | manager | costs |
08 | 21 | 5065 |
01 | 03 | 7231 |
02 | 07 | 6540 |
09 | 37 | 5345 |
delete from sales
where area =
( select sarea from costcentres
where costs > 7000 );
sales
salesman | area | qtysold | value |
223 | 08 | 20 | 6000 |
289 | 02 | 16 | 7131 |
301 | 02 | 31 | 5992 |
319 | 08 | 25 | 7006 |
Update - modifies data
update table set assignment-list [where search-condition]
Eg
update sales set qtysold = 23, value = 6975
where salesman = 223;
sales
salesman | area | qty sold | value |
223 | 08 | 23 | 6975 |
277 | 01 | 25 | 8092 |
289 | 02 | 16 | 7131 |
301 | 02 | 31 | 5992 |
310 | 01 | 32 | 6109 |
319 | 08 | 25 | 7006 |
334 | 01 | 18 | 5817 |
sales
salesman | area | qtysold | value |
223 | 08 | 20 | 6000 |
277 | 01 | 25 | 8092 |
289 | 02 | 16 | 7131 |
301 | 02 | 31 | 5992 |
310 | 01 | 32 | 6109 |
319 | 08 | 25 | 7006 |
334 | 01 | 18 | 5817 |
Foreign Key
costcentres
sarea | manager | costs |
08 | 21 | 5065 |
01 | 03 | 7231 |
02 | 07 | 6540 |
09 | 37 | 5345 |
Primary Key
select salesman, value, manager
from sales, costcentres
where area = sarea;
Notes
1. Both tables need to be specified
2. The 'where' clause specifies a test between
primary & foreign key
3. The keys do not have to be included in the output
result
salesman | value | manager |
223 | 6000 | 21 |
277 | 8092 | 03 |
289 | 7131 | 07 |
301 | 5992 | 07 |
310 | 6109 | 03 |
319 | 7006 | 21 |
334 | 5817 | 03 |
Row selection criteria may be used in conjunction:-
select salesman, value, manager
from sales, costcentres
where area = sarea
and costs > 6000;
salesman | value | manager |
277 | 8092 | 03 |
289 | 7131 | 07 |
301 | 5992 | 07 |
310 | 6109 | 03 |
334 | 5817 | 03 |
Other query possibilities are:-
- More than two tables
- Matching several columns in related tables
- Using non-key columns for matching
- 'Non-equi joins' eg
select salesman, value, manager
from sales, costcentres
where value > costs;
salesman | value | manager |
223 | 6000 | 21 |
277 | 8092 | 03 |
289 | 7131 | 07 |
319 | 7006 | 21 |
Qualified Column Names
- Where column names are the same in two/more tables
tablename.columnname
Aliases
- Provide a means of joining a table to itself:-
salesreps
salesman | value | manager |
223 | 6000 | 277 |
277 | 8092 | null |
289 | 7131 | 277 |
319 | 7006 | 277 |
Eg to list all salesreps, and their manager:-
select emps.salesman, mgrs.salesman
from salesreps emps, salesreps mgrs
where emps.manager = mgrs.salesman;
emps.salesman | mgrs.salesman |
223 | 277 |
289 | 277 |
319 | 277 |
Data Definition
- SQL Definition is based on three verbs:-
Create which creates a table,
Drop to delete tables
Alter to change structure
- create table table-name ( item-list )
where item-list is repetitions of:-
column data-type [ default { literal | user |null}]
| unique ( column-list )
| primary key ( column-name-list )
| foreign key key-list
Eg
create table offices
( office integer not null,
city varchar(15) not null,
region varchar(10) not null default "yorkshire",
mgr integer,
target money,
sales money not null,
primary key (office),
foreign key hasmgr (mgr)
references salesreps
on delete set null,
unique (city) )
The set of relations listed below is partial description of an auto service database. Create an relational database containing exactly this set of relations.
Relation Customer
customer id# | name | street
address |
city
|
postal
code |
home
tel # |
business
tel # |
5001 | Jones R. | 147 indian dr | toronto | m4s 1s3 | 897-9676 | 789-8657 |
2347 | Fraser D. | 34 pearson | hamilton | m4p 1j7 | 657-8754 | 980-9876 |
1238 | Wong A. | 102 york mills | toronto | m1p 2s1 | 488-3434 | 987-7576 |
6065 | Chen B. | 50 savonadr | london | m7j 2a8 | 343-4534 | 765-8754 |
1209 | Gerus H. | 68 edna | cambridge | m5n 1j4 | 765-5433 | 765-5433 |
7324 | Payne N. | 67 delmadr | waterloo | m9d 9i2 | 435-5656 | 586-8608 |
8526 | Philip J. | 72 clinton | mississauga | m6f 8f1 | 654-5676 | 254-9786 |
6357 | Tai K. | 245 dun | north york | m9i 9k2 | 564-6754 | 876-9087 |
1007 | Bruno M. | 21 dundas | toronto | m5i 3s7 | 544-5655 | 544-5655 |
9901 | Bryson S. | 6 mayfair | mississauga | m8s 1f2 | 907-9785 | 786-9767 |
Relation Service
car id # | date-scheduled | date-served | mechanic name | service charge |
548lop | 23/09/92 | 23/09/92 | Liu J. | 734.64 |
tre234 | 18/10/92 | 19/10/92 | Mcfadden M. | 509.87 |
789wrs | 29/10/92 | 29/10/92 | Liu J. | 173.00 |
234ery | 19/09/92 | 19/09/92 | Cohen S. | 509.87 |
548lop | 29/10/92 | 29/10/92 | Mcfadden M. | 734.63 |
olp789 | 08/09/92 | 09/09/92 | Dawe T. | 509.87 |
782iam | 28/10/92 | |||
tre234 | 04/09/92 | 04/09/92 | Cohen S. | 1089.87 |
Relation Vehicle
owner id# | make | model | year | licence plate # |
6065 | chevrolet | cavalier | 1989 | 234ery |
2347 | oldsmobile | cutlas | 1985 | gfd742 |
7324 | toyota | corola | 1989 | 980sss |
1209 | toyota | previa | 1991 | 782iam |
5001 | dodge | omni | 1988 | ctv111 |
7324 | ford | mustang | 1989 | 548lop |
1007 | buick | regal | 1989 | utt709 |
1238 | porche | 944 | 1985 | olp789 |
1209 | ford | mercury | 1990 | 342ges |
8526 | suzuki | sidekick | 1990 | tre234 |
5001 | toyota | tercel | 1985 | loo660 |
9901 | mazda | 626 | 1986 | 566kil |
6357 | chevrolet | astro | 1991 | 789wrs |
Formulate each of the queries below in the sql language and run them on the database created above.
Query 1: Find the names of all customers who live in Toronto.
Query 2: Find the make, model and year of all cars owned by Jones R.
Query 3: Find the names and addresses of all customers who own a Toyota.
Query 4 : Find the license plate number of all cars owned by Jones R.
Query 5: Find the customer name and make of car for every customer who has a 1989 car.
Query 6: Find the names of all customers who live in Toronto and own a Toyota.
Query 7: Find the names and addresses of all customers who own a Ford and who are scheduled for service on sep 23, 1992.
Query 8: Find the names of all customers who own a Chevrolet astro which was serviced on oct 29, 1992.
Query 9: Find the names of all customers whose home telephone number is the same as their business telephone number.
Query 10: Find the total service charges for Philip J.
Query 11: Find how many cars Jones R. owns.
Query 12: Find the largest service charge and the name of the customer who paid it.
Query 13: Find the lowest service charge and the name of the mechanic who did the service.
Query 14: Find the total number of cars and their licence plate numbers for cars which have not been scheduled for service.
Query 15: Find the names and telephone numbers of the owners of those cars which have been scheduled for service, but not yet serviced.
Query 16: For each customer who has a service charge, find the costumer's name and his total charge.
Query 17: For each mechanic who has repaired a car, find the mechanic's name and his total earnings.
Query 18: Find out when Gerus H. car is scheduled for service.
Query 19: Find how many cars where serviced on the same day that they were scheduled for service.
Query 20: For each city, find the total number of cars for that city in the database.
Query 21: Find which car has the highest service rate (i.e., has been serviced or scheduled for service the most times).
Query 22: For each make in the data base, find the average service rate for that make.
Query 23: Find the percentage served cars for each city in the database.