Unit-2 Ppt SQL and Pl SQL
Unit-2 Ppt SQL and Pl SQL
Example:
• create table instructor (
An SQL relation is defined using the create table command:
• create table r (A1 D1, A2 D2, ..., An Dn,
• (integrity-constraint1),
• ...,
• (integrity-constraintk))
r is the name of the relation
each Ai is an attribute name in the schema of relation r
Di is the data type of values in the domain of attribute Ai
Example:
create table instructor (
ID char(5),
Name varchar(20),
dept_name varchar(20),
salary numeric(8,2))
Integrity Constraints in Create Table
not null
primary key (A1, ..., An )
foreign key (Am, ..., An ) references r
•Example:
create table instructor
ID char(5),
Drop Table
drop table r
Alter
alter table r add A D
where A is the name of the attribute to be added to relation
Ai represents an attribute
Ri represents a relation
P is a predicate.
The result of an SQL query is a relation
The select Clause
The select clause lists 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 name
• from instructor
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.
The select Clause (Cont.)
SQL allows duplicates in relations as well as in query results.
To force the elimination of duplicates, insert the keyword
distinct
• after select.
Find the department names of all instructors, and remove
duplicates
• select distinct dept_name
• from instructor
The keyword all specifies that duplicates should not be
removed.
• (select course_id from section where sem = ‘Fall’ and year = 2009)
• union
• (select course_id from section where sem = ‘Spring’ and year = 2010)
Find courses that ran in Fall 2009 but not in Spring 2010
• (select course_id from section where sem = ‘Fall’ and year = 2009)
• except
• (select course_id from section where sem = ‘Spring’ and year = 2010)
Set Operations (Cont.)
Find the salaries of all instructors that are less than the largest salary.
select distinct T.salary
• from instructor as T, instructor as S
• where T.salary < S.salary