0% found this document useful (0 votes)
104 views

Idbms Unit Iii

The document discusses the SQL language and its uses for defining and modifying database tables and relations. SQL allows users to define schemas, add and delete rows of data, and enforce integrity constraints. Key functions of SQL include the CREATE, ALTER, INSERT and DROP commands.

Uploaded by

shyamd4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
104 views

Idbms Unit Iii

The document discusses the SQL language and its uses for defining and modifying database tables and relations. SQL allows users to define schemas, add and delete rows of data, and enforce integrity constraints. Key functions of SQL include the CREATE, ALTER, INSERT and DROP commands.

Uploaded by

shyamd4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 86

UNIT III

Structured Query Language

Database System Concepts, 7th Ed.


©Silberschatz, Korth and Sudarshan
See www.db-book.com for conditions on re-use
Introduction to SQL
 SQL is a language that provides an interface to Relational database
systems.
 Developed by IBM in the 1970s for use in System R
 SQL is relatively easy to learn
 Nonprocedural language
 ANSI prescribes a standard SQL

Database System Concepts - 7th Edition 2.2 ©Silberschatz, Korth and Sudarshan
Introduction to SQL (continued)
 SQL functions fit into two broad categories:
 Data Definition Language
 includes commands to:
– Create database objects, such as tables, indexes, and
views
– Define access rights to those database objects
 Data Manipulation Language
 Includes commands to insert, update, delete, and retrieve data
within database tables

Database System Concepts - 7th Edition 2.3 ©Silberschatz, Korth and Sudarshan
Data Definition Language

Database System Concepts - 7th Edition 2.4 ©Silberschatz, Korth and Sudarshan
Domain Types in SQL
 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
 numeric(p,d). Fixed point number, with user-specified precision of p digits,
with d digits to the right of decimal point. (ex., numeric(3,1), allows 44.5 to be
stores exactly, but not 444.5 or 0.32)
 float(n). Floating point number, with user-specified precision of at least n digits.

Database System Concepts - 7th Edition 2.5 ©Silberschatz, Korth and Sudarshan
Create Table Construct
 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));

Database System Concepts - 7th Edition 2.6 ©Silberschatz, Korth and Sudarshan
Integrity Constraints in Create Table

 Types of integrity constraints


 primary key (A1, ..., An )
 foreign key (Am, ..., An ) references r
 not null
 SQL prevents any update to the database that violates an integrity constraint.
 Example:
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);
 Primary key attributes indicate both a NOT NULL and a UNIQUE specification

Database System Concepts - 7th Edition 2.7 ©Silberschatz, Korth and Sudarshan
And a Few More Relation Definitions
 create table student (
ID varchar(5),
name varchar(20) not null,
dept_name varchar(20),
tot_cred numeric(3,0),
primary key (ID),
foreign key (dept_name) references department);

 create table takes (


ID varchar(5),
course_id varchar(8),
sec_id varchar(8),
semester varchar(6),
year numeric(4,0),
grade varchar(2),
primary key (ID, course_id, sec_id, semester, year) ,
foreign key (ID) references student,
foreign key (course_id, sec_id, semester, year) references section);

Database System Concepts - 7th Edition 2.8 ©Silberschatz, Korth and Sudarshan
And more still
 create table course (
course_id varchar(8),
title varchar(50),
dept_name varchar(20),
credits numeric(2,0),
primary key (course_id),
foreign key (dept_name) references department);

Database System Concepts - 7th Edition 2.9 ©Silberschatz, Korth and Sudarshan
ALTER Command
 All changes in table structure are made by using ALTER command
 Followed by keyword that produces specific change
 Following four options are available:
 ADD
 MODIFY
 RENAME
 DROP
 Use ALTER to add column
 Syntax:
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 existing tuples in the relation are assigned null as the value
for the new attribute.
Example:
ALTER TABLE Student
ADD dateofbirth CHAR(20);
Database System Concepts - 7th Edition 2.10 ©Silberschatz, Korth and Sudarshan
ALTER Command contd.

 ALTER can be used to change data type


 Some RDBMSs (such as Oracle) do not permit changes to data types
unless column to be changed is empty
ALTER TABLE Student
MODIFY dateofbirth VARCHAR(20);

 Use ALTER to drop column


 Some RDBMSs impose restrictions on the deletion of an attribute
 Syntax:
alter table r drop column A
 where A is the name of an attribute of relation r
 Dropping of attributes not supported by many databases.
ALTER TABLE Student
DROP COLUMN dateofbirth;

Database System Concepts - 7th Edition 2.11 ©Silberschatz, Korth and Sudarshan
Deleting a Table from the Database
 DROP
 Deletes table from database
 Syntax:
 DROP TABLE tablename;

Database System Concepts - 7th Edition 2.12 ©Silberschatz, Korth and Sudarshan
Modification of the Database

 Insertion of new tuples into a given relation


 Deletion of tuples from a given relation.
 Updating of values in some tuples in a given relation

Database System Concepts - 7th Edition 2.13 ©Silberschatz, Korth and Sudarshan
Database System Concepts - 7th Edition 2.14 ©Silberschatz, Korth and Sudarshan
Adding Table Rows - Insertion
 INSERT
 Used to enter data into table
 Insert a row each time
 Use NULL for unknown values
 Syntax:
 INSERT INTO tablename
VALUES (value1, value2, … , valuen);

Database System Concepts - 7th Edition 2.15 ©Silberschatz, Korth and Sudarshan
Insertion (Cont.)
 Add a new tuple to course
insert into course
values (’CS-437’, ’Database Systems’, ’Comp. Sci.’, 4);

 or equivalently

insert into course (course_id, title, dept_name, credits)


values (’CS-437’, ’Database Systems’, ’Comp. Sci.’, 4);

 Add a new tuple to student with tot_creds set to null


insert into student
values (’3003’, ’Green’, ’Finance’, null);

Database System Concepts - 7th Edition 2.16 ©Silberschatz, Korth and Sudarshan
Inserting Table Rows with a
Select Subquery

 INSERT
 Inserts multiple rows from another table (source)
 Uses SELECT subquery
 Query that is embedded (or nested) inside another query
 Executed first
 Syntax:
 INSERT INTO tablename SELECT columnlist FROM
tablename;

Database System Concepts - 7th Edition 2.17 ©Silberschatz, Korth and Sudarshan
Inserting Table Rows with a
Select Subquery (Cont.)
Student(name, address, roll_num, total_credits)
Student1(addr, credits, rollno)

INSERT INTO Student1


SELECT address, total_credits, roll_num
FROM Student;

Database System Concepts - 7th Edition 2.18 ©Silberschatz, Korth and Sudarshan
Inserting Table Rows with a
Select Subquery (Cont.)
 INSERT INTO Student1
SELECT address, roll_num, total_credits
FROM Student;
(The order of attributes matter in the above)

 INSERT INTO Student1


SELECT * FROM Student;
(The number of attributes are not the same!)

Database System Concepts - 7th Edition 2.19 ©Silberschatz, Korth and Sudarshan
Updating Table Rows
 UPDATE
 Modify data in a table
 Syntax:
 UPDATE tablename
SET columnname = expression [, columnname = expression ]
[WHERE conditionlist];
 If more than one attribute is to be updated in row, separate corrections
with commas

Database System Concepts - 7th Edition 2.20 ©Silberschatz, Korth and Sudarshan
Updates (Cont.)

 Give a 5% salary raise to all instructors


update instructor
set salary = salary * 1.05
 Give a 5% salary raise to those instructors who Eran less than 70000
update instructor
set salary = salary * 1.05
where salary < 70000;
 Give a 5% salary raise to instructors whose salary is less than average
update instructor
set salary = salary * 1.05
where salary < (select avg (salary)
from instructor);

Database System Concepts - 7th Edition 2.21 ©Silberschatz, Korth and Sudarshan
Deleting Table Rows

 DELETE
 Deletes a table row
 Syntax:
 DELETE FROM tablename [WHERE conditionlist ];
 WHERE condition is optional
 If WHERE condition is not specified, all rows from specified table will be deleted

Database System Concepts - 7th Edition 2.22 ©Silberschatz, Korth and Sudarshan
Deletion (Cont.)

 Delete all instructors from the Finance department


delete from instructor
where dept_name= ’Finance’;

 Delete all instructors whose salary is less than the average salary of instructors
delete from instructor
where salary < (select avg (salary) from instructor);

 Delete all instructors


delete from instructor ;

Database System Concepts - 7th Edition 2.23 ©Silberschatz, Korth and Sudarshan
Restoring Table Contents

 ROLLBACK
 Used to restore database to its previous condition
 Only applicable if COMMIT command has not been
used to permanently store changes in database
 Syntax:
 ROLLBACK;
 COMMIT and ROLLBACK only work with data
manipulation commands that are used to add,
modify, or delete table rows

Database System Concepts - 7th Edition 2.24 ©Silberschatz, Korth and Sudarshan
Basic Structure of SQL Queries
 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.
 The select clause is used to list the attributes desired in the result of a query
(corresponds to the projection operation of the relational algebra).
 The from clause is a list of the relations to be accessed in the evaluation of
the query (Corresponds to the Cartesian product operation of the relational
algebra).
 The where clause specifies conditions that the result must satisfy
(Corresponds to the selection predicate of the relational algebra).

Database System Concepts - 7th Edition 2.25 ©Silberschatz, Korth and Sudarshan
Queries on a single relation
 Example: find the names of all instructors:
select name
from instructor;
 An asterisk in the select clause denotes “all attributes”
select *
from instructor;
 NOTE: SQL names are case insensitive (i.e., you may use upper- or lower-
case letters.)
 E.g., Name ≡ NAME ≡ name

Database System Concepts - 7th Edition 2.26 ©Silberschatz, Korth and Sudarshan
Queries on a single relation (Cont.)
 SQL allows duplicates in relations as well as in query results.
 Example: Find the department names of all instructors
select dept_name
from instructor;
 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 all dept_name


from instructor;

Database System Concepts - 7th Edition 2.27 ©Silberschatz, Korth and Sudarshan
Queries on a single relation (Cont.)
 The select clause can contain arithmetic expressions involving the operation, +,
–, , and /, and operating on constants or attributes of tuples.
 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.
 Can rename “salary/12” using the as clause:
select ID, name, salary/12 as monthly_salary from instructor;
 SQL includes a between comparison operator which is used to check whether
attribute value is within a range
 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;

Database System Concepts - 7th Edition 2.28 ©Silberschatz, Korth and Sudarshan
Queries on a single relation (Cont.)
 To find all instructors in Comp. Sci. dept
select name
from instructor
where dept_name = ‘Comp. Sci.‘;
 SQL allows the use of the logical connectives and, or, and not
 The operands of the logical connectives can be expressions involving the
comparison operators <, <=, >, >=, =, and <>.
 Comparisons can be applied to results of arithmetic expressions
 To find all instructors in Comp. Sci. dept with salary > 80000
select name
from instructor
where dept_name = ‘Comp. Sci.' and salary > 80000;

Database System Concepts - 7th Edition 2.29 ©Silberschatz, Korth and Sudarshan
Queries on a multiple relations
 Find the Cartesian product instructor X department
select 
from instructor, department;
 generates every possible instructor – department pair, with all attributes
from both relations.
 Cartesian product is not very useful directly, but useful combined with where-
clause condition (selection operation in relational algebra).

Database System Concepts - 7th Edition 2.30 ©Silberschatz, Korth and Sudarshan
Queries on a multiple relations (Contd.)
 Example: Retrieve the names of all instructors, along with their department
names and department building name
 Query:
select name, instructor.dept_name, building
from instructor, department
where instructor.dept_name= department.dept_name;

Database System Concepts - 7th Edition 2.31 ©Silberschatz, Korth and Sudarshan
Additional Basic Operations

String Operations:
 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.
 Find the names of all instructors whose name includes the substring “sa”.
select name
from instructor
where name like '%sa%'

Database System Concepts - 7th Edition 2.32 ©Silberschatz, Korth and Sudarshan
String Operations (Cont.)
 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.

 SQL supports a variety of string operations such as


 concatenation (using “||”)
 converting from upper to lower case (and vice versa)
 finding string length, extracting substrings, etc.

Database System Concepts - 7th Edition 2.33 ©Silberschatz, Korth and Sudarshan
String Operations (Cont.)

Examples:
 Find the names of all instructors whose name begins with
“K”.
 Find the names of all instructors whose name ends with
“n”.
 Find the names of all instructors whose second last letter is
“i”.
 Find the names of all instructors whose third letter from the
beginning is “i”

Database System Concepts - 7th Edition 2.34 ©Silberschatz, Korth and Sudarshan
String Operations (Cont.)
 ASCII(): Used to find the ASCII value of a character.
 Select ascii(‘a’) from dual;
 Concatenation:
 select 'vasavi' ||'college' from dual;
Or
 select concat('vasavi','college') from dual;
 select name,length(name) from instructor;
 select upper(name) from instructor;
 select lower(name) from instructor;
 select lower('VASAVI') from dual;
 select upper('vasavi') from dual;
 select length('vasavi college of engineering') from dual;

Database System Concepts - 7th Edition 2.35 ©Silberschatz, Korth and Sudarshan
Ordering the Display of Tuples
 List in alphabetic order the names of all instructors
select name
from instructor
order 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 attributes
 Example: order by dept_name, name

Database System Concepts - 7th Edition 2.36 ©Silberschatz, Korth and Sudarshan
Where Clause Predicates
 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

Database System Concepts - 7th Edition 2.37 ©Silberschatz, Korth and Sudarshan
Set Operations
RELATIONAL SET OPERATORS
- UNION
- INTERSECT
- MINUS (Except)
 Each of the above operations automatically eliminates duplicates
 To retain all duplicates use the
 union all
 intersect all
 except all.

Database System Concepts - 7th Edition 2.38 ©Silberschatz, Korth and Sudarshan
The UNION Operation
 The UNION statement combines rows from two or more queries
without including duplicate rows.
 Column names and their data types must be compatible
 Syntax: query UNION query

SELECT column-list FROM table1


UNION
SELECT column-list FROM table2;

Database System Concepts - 7th Edition 2.39 ©Silberschatz, Korth and Sudarshan
The UNION Operation (Contd.)
Consider two relations:
1. Student relation with three attributes- Rollno, Name, Deptname
2. Student1 relation with two attributes- Rollno, Name
Rollno and Name are common attributes. We can perform set operations
on these common attributes

Database System Concepts - 7th Edition 2.40 ©Silberschatz, Korth and Sudarshan
The UNION Operation (Contd.)
SELECT rollno,name FROM student
UNION
SELECT rollno,name FROM student1;

Result

Database System Concepts - 7th Edition 2.41 ©Silberschatz, Korth and Sudarshan
UNION ALL
 The UNION ALL query can be used to produce a relation that retains
the duplicate rows
 Column names and their data types must be compatible.
 Syntax: query UNION ALL query

SELECT column-list FROM table1


UNION ALL
SELECT column-list FROM table2;

Database System Concepts - 7th Edition 2.42 ©Silberschatz, Korth and Sudarshan
UNION ALL (Contd.)
SELECT rollno,name FROM student
UNION ALL
SELECT rollno,name FROM student1;

Result

Database System Concepts - 7th Edition 2.43 ©Silberschatz, Korth and Sudarshan
The INTERSECT Operation
 Find the rows that are in both tables

 Syntax: query INTERSECT query

SELECT column-list FROM table1


INTERSECT
SELECT column-list FROM table2;

 If we want to retain all duplicates, we must write intersect all in place of intersect.

Database System Concepts - 7th Edition 2.44 ©Silberschatz, Korth and Sudarshan
The INTERSECT Operation (Contd.)
SELECT rollno,name FROM student
INTERSECT
SELECT rollno,name FROM student1;

 Result:

Database System Concepts - 7th Edition 2.45 ©Silberschatz, Korth and Sudarshan
The Except (Minus) Operation
 Combines rows from two queries and returns only those rows that appear in the
first table but not in the second
 Syntax: query except query

SELECT column-list FROM table1


EXCEPT
SELECT column-list FROM table2;

 If we want to retain duplicates, we must write except all in place of


except

Database System Concepts - 7th Edition 2.46 ©Silberschatz, Korth and Sudarshan
The Except (Minus) Operation (Contd.)
SELECT rollno,name FROM student
MINUS
SELECT rollno,name FROM student1;

Result:

Database System Concepts - 7th Edition 2.47 ©Silberschatz, Korth and Sudarshan
Null Values
 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 null
 Example: 5 + null returns null
 The predicate is null can be used to check for null values.
 Example: Find all instructors whose salary is null.
select name
from instructor
where salary is null;
 The predicate is not null succeeds if the value on which it is applied is not
null.

Database System Concepts - 7th Edition 2.48 ©Silberschatz, Korth and Sudarshan
Null Values (Cont.)
 SQL treats as unknown the result of any comparison involving a null value
(other than predicates is null and is not null). This creates a third logical value
in addition to true and false.
 Example: 5 < null or null <> null or null = null
 The predicate in a where clause can involve Boolean operations (and, or, not);
thus the definitions of the Boolean operations need to be extended to deal with
the value unknown.
 and : (true and unknown) = unknown,
(false and unknown) = false,
(unknown and unknown) = unknown
 or: (unknown or true) = true,
(unknown or false) = unknown
(unknown or unknown) = unknown
 not: The result of not unknown is unknown.
 Result of where clause predicate is treated as false if it evaluates to unknown

Database System Concepts - 7th Edition 2.49 ©Silberschatz, Korth and Sudarshan
Aggregate Functions
 Aggregate functions are functions that take a collection (a set or multiset) of values as
input and return a single value. SQL offers five built-in aggregate functions:

Database System Concepts - 7th Edition 2.50 ©Silberschatz, Korth and Sudarshan
Aggregate Functions Examples
 Find the average salary of instructors in the Computer Science
department
 select avg (salary)
from instructor
where dept_name= ’Comp. Sci.’;
 we can give a meaningful name to the attribute by using the as
clause as follows
 select avg (salary) as avg_salary
from instructor
where dept_name= ’Comp. Sci.’;
 Find the number of tuples in the instructor relation
 select count (*)
from instructor;

Database System Concepts - 7th Edition 2.51 ©Silberschatz, Korth and Sudarshan
Aggregate Functions Examples
 Finding maximum salary:
 select max (salary)
from instructor;
 we can give a meaningful name to the attribute by using the as
clause as follows
 select max (salary) as maximum_salary
from instructor;

 Finding minimum salary:


 select min (salary)
from instructor;
 we can give a meaningful name to the attribute by using the as
clause as follows
 select min (salary) as minimum_salary
from instructor;

Database System Concepts - 7th Edition 2.52 ©Silberschatz, Korth and Sudarshan
Aggregate Functions Examples
 Finding sum of salaries of all the instructors:
 select sum (salary)
from instructor;
 we can give a meaningful name to the attribute by using the as
clause as follows
 select sum (salary) as total_salary
from instructor;

Database System Concepts - 7th Edition 2.53 ©Silberschatz, Korth and Sudarshan
Grouping Data
 The GROUP BY clause is generally used when you have attribute columns
combined with aggregate functions in the SELECT statement

 Syntax:
 SELECT columnlist
FROM tablelist
[ WHERE conditionlist ]
[ GROUP BY columnlist ];

Database System Concepts - 7th Edition 2.54 ©Silberschatz, Korth and Sudarshan
Aggregate Functions – Group By
 Find the average salary of instructors in each department
 select dept_name, avg (salary) as avg_salary
from instructor
group by dept_name;

Database System Concepts - 7th Edition 2.55 ©Silberschatz, Korth and Sudarshan
Aggregate Functions – Having Clause

 Find the names and average salaries of all departments whose


average salary is greater than 42000

select dept_name, avg (salary) as avg_salary


from instructor
group by dept_name
having avg (salary) > 42000;

Note: predicates in the having clause are applied after the formation
of groups whereas predicates in the where clause are applied before
forming groups.

Database System Concepts - 7th Edition 2.56 ©Silberschatz, Korth and Sudarshan
Null Values and Aggregates
 Total all salaries
select sum (salary )
from instructor;
 Above statement ignores null amounts
 Result is null if there is no non-null amount
 All aggregate operations except count(*) ignore tuples with null values
on the aggregated attributes
 What if collection has only null values?
 count returns 0
 all other aggregates return null

Database System Concepts - 7th Edition 2.57 ©Silberschatz, Korth and Sudarshan
Nested Subqueries
 SQL provides a mechanism for the nesting of subqueries.
 A subquery is a query (select-from-where expression) inside a
query
 Normally expressed inside parenthesis
 The first query in the SQL statement is known as the outer query
 The query inside the SQL statement is known as the inner query
 The inner query is executed first.
 The output of an inner query is used as the input for the outer
query.

Database System Concepts - 7th Edition 2.58 ©Silberschatz, Korth and Sudarshan
Nested Subqueries (Contd.)
 The nesting can be done in the following SQL query

select A1, A2, ..., An


from r1, r2, ..., rm
where P

as follows:
 From clause: ri can be replaced by any valid subquery
 Where clause: P can be replaced with an expression of the form:
B <operation> (subquery)
Where B is an attribute and <operation> to be defined later.
 Select clause:
Ai can be replaced be a subquery that generates a single value.

Database System Concepts - 7th Edition 2.59 ©Silberschatz, Korth and Sudarshan
Subqueries in the Where cluase
 The most common type of subquery uses an inner SELECT subquery on the
right side of a WHERE comparison expression
 Select the names of instructors whose salary is less than average salary.
select name from instructor
where salary < (select avg (salary)
from instructor);
 select all tuples in the instructor relation for those instructors associated with
a department located in the Watson building.
select * from instructor
where dept_name in (select dept_name
from department
where building = ’Watson’);
 IN
 Used to check whether attribute value matches any value within a value
list

Database System Concepts - 7th Edition 2.60 ©Silberschatz, Korth and Sudarshan
Subqueries in the Where clause (Contd.)
 select all tuples in the instructor relation for those instructors not associated
with a department located in the Watson building.
select * from instructor
where dept_name not in (select dept_name
from department
where building = ’Watson’);

 Finding second highest salary of an instructor.


select max(salary) from instructor
where salary<(select max(salary) from instructor);

Database System Concepts - 7th Edition 2.61 ©Silberschatz, Korth and Sudarshan
Subqueries in the Where clause (Contd.)
 Update the name of an instructor who is having minimum salary.
update instructor set name='Ramu'
where salary=(select min(salary) from instructor);

 Delete instructors whose salary is less than the average salary.


delete from instructor
where salary<(select avg(salary) from instructor);

Database System Concepts - 7th Edition 2.62 ©Silberschatz, Korth and Sudarshan
Subqueries in the Where clause (Contd.)
 Multi row Subquery Operators: SOME and ALL
 SOME and ALL are logical operators in SQL.

Definition of “some” Clause


 SOME or ANY: The ANY operator returns TRUE if any of the
subquery values meet the condition.
0
(5 < some 5 ) = true
(read: 5 < some tuple in the relation)
6
0
(5 < some 5 ) = false

0
(5 = some 5 ) = true

0
(5  some 5 ) = true (since 0  5)
Database System Concepts - 7th Edition 2.63 ©Silberschatz, Korth and Sudarshan
Subqueries in the Where clause (Contd.)
Definition of “all” Clause
 ALL: The ALL operator returns TRUE if all of the subquery
values meet the condition.

0
(5 < all 5 ) = false
6
6
(5 < all 10 ) = true

4
(5 = all 5 ) = false

4
(5  all 6 ) = true (since 5  4 and 5  6)

Database System Concepts - 7th Edition 2.64 ©Silberschatz, Korth and Sudarshan
Subqueries in the Where clause (Contd.)
 Find the tuples of instructors with salary greater than that of some
(at least one) instructor in the Computer Science department.
select *
from instructor
where salary > some (select salary
from instructor
where dept_name = ’Comp. Sci.’);

 Find the tuples of all instructors whose salary is greater than the
salary of all instructors in the Computer Science department.
select *
from instructor
where salary > all (select salary
from instructor
where dept_name = ’Comp. Sci.’);

Database System Concepts - 7th Edition 2.65 ©Silberschatz, Korth and Sudarshan
Subqueries in the From Clause
 SQL allows a subquery expression to be used in the from clause
 Find the average instructors’ salaries of those departments where the
average salary is greater than $42,000.”
select dept_name, avg_salary
from ( select dept_name, avg (salary) as avg_salary
from instructor
group by dept_name)
where avg_salary > 42000;
 Find the maximum across all departments of the total salary at each
department.
select max(tot_salary)
from(select deptname, sum(salary) as tot_salary
from instructor group by deptname);

Database System Concepts - 7th Edition 2.66 ©Silberschatz, Korth and Sudarshan
Scalar Subquery
 Scalar subquery is one which is used where a single value is
expected
 List all departments along with the number of instructors in each
department
select dept_name,
( select count(*)
from instructor
where department.dept_name = instructor.dept_name)
as num_instructors
from department;
 Runtime error if subquery returns more than one result tuple

Database System Concepts - 7th Edition 2.67 ©Silberschatz, Korth and Sudarshan
Join Expressions
 Join operations take two relations and return as a result another
relation.
 A join operation is a Cartesian product which requires that tuples in the
two relations match (under some condition). It also specifies the
attributes that are present in the result of the join
 The join operations are typically used as subquery expressions in the
from clause

Database System Concepts - 7th Edition 2.68 ©Silberschatz, Korth and Sudarshan
SQL Join Operators

Database System Concepts - 7th Edition 2.69 ©Silberschatz, Korth and Sudarshan
Join operations – Example
 Relation course

 Relation prereq

 Observe that
prereq information is missing for CS-315 and
course information is missing for CS-347
Database System Concepts - 7th Edition 2.70 ©Silberschatz, Korth and Sudarshan
Outer Join

 An extension of the join operation that avoids loss of information.


 Computes the join and then adds tuples form one relation that does not
match tuples in the other relation to the result of the join.
 Uses null values.

Database System Concepts - 7th Edition 2.71 ©Silberschatz, Korth and Sudarshan
Left Outer Join

 course natural left outer join prereq

Database System Concepts - 7th Edition 2.72 ©Silberschatz, Korth and Sudarshan
Right Outer Join

 course natural right outer join prereq

Database System Concepts - 7th Edition 2.73 ©Silberschatz, Korth and Sudarshan
Joined Relations
 Join operations take two relations and return as a result another relation.
 These additional operations are typically used as subquery expressions in
the from clause
 Join condition – defines which tuples in the two relations match, and
what attributes are present in the result of the join.
 Join type – defines how tuples in each relation that do not match any
tuple in the other relation (based on the join condition) are treated.

Database System Concepts - 7th Edition 2.74 ©Silberschatz, Korth and Sudarshan
Full Outer Join

 course natural full outer join prereq

Database System Concepts - 7th Edition 2.75 ©Silberschatz, Korth and Sudarshan
Joined Relations – Examples

 course inner join prereq on


course.course_id = prereq.course_id

 What is the difference between the above, and a natural join?


 course left outer join prereq on
course.course_id = prereq.course_id

Database System Concepts - 7th Edition 2.76 ©Silberschatz, Korth and Sudarshan
Joined Relations – Examples
 course natural right outer join prereq

 course full outer join prereq using (course_id)

Database System Concepts - 7th Edition 2.77 ©Silberschatz, Korth and Sudarshan
Views
 In some cases, it is not desirable for all users to see the entire logical
model (that is, all the actual relations stored in the database.)
 Consider a person who needs to know an instructors name and
department, but not the salary. This person should see a relation
described, in SQL, by

select ID, name, dept_name


from instructor

 A view provides a mechanism to hide certain data from the view of


certain users.
 Any relation that is not of the conceptual model but is made visible to a
user as a “virtual relation” is called a view.

Database System Concepts - 7th Edition 2.78 ©Silberschatz, Korth and Sudarshan
Virtual Tables: Creating a View
 View is virtual table based on SELECT query

Can contain columns, computed columns, aliases, and aggregate
functions from one or more tables
 Base tables are tables on which view is based
 Create view by using CREATE VIEW command
 CREATE VIEW viewname AS SELECT query

Database System Concepts - 7th Edition 2.79 ©Silberschatz, Korth and Sudarshan
View Definition
 A view is defined using the create view statement which has
the form
create view v as < query expression >

where <query expression> is any legal SQL expression. The


view name is represented by v.
 Once a view is defined, the view name can be used to refer to
the virtual relation that the view generates.
 View definition is not the same as creating a new relation by
evaluating the query expression
 Rather, a view definition causes the saving of an expression;
the expression is substituted into queries using the view.

Database System Concepts - 7th Edition 2.80 ©Silberschatz, Korth and Sudarshan
Example Views
 A view of instructors without their salary
create view faculty as
select ID, name, dept_name
from instructor
 Find all instructors in the Biology department
select name
from faculty
where dept_name = ‘Biology’
 Create a view of department salary totals
create view departments_total_salary(dept_name, total_salary) as
select dept_name, sum (salary)
from instructor
group by dept_name;

Database System Concepts - 7th Edition 2.81 ©Silberschatz, Korth and Sudarshan
Views Defined Using Other Views
 One view may be used in the expression defining another view
 A view relation v1 is said to depend directly on a view relation
v2 if v2 is used in the expression defining v1
 A view relation v1 is said to depend on view relation v2 if either
v1 depends directly to v2 or there is a path of dependencies
from v1 to v2
 A view relation v is said to be recursive if it depends on itself.

Database System Concepts - 7th Edition 2.82 ©Silberschatz, Korth and Sudarshan
View Expansion
 A way to define the meaning of views defined in terms of other
views.
 Let view v1 be defined by an expression e1 that may itself
contain uses of view relations.
 View expansion of an expression repeats the following
replacement step:
repeat
Find any view relation vi in e1
Replace the view relation vi by the expression defining vi
until no more view relations are present in e1
 As long as the view definitions are not recursive, this loop will
terminate

Database System Concepts - 7th Edition 2.83 ©Silberschatz, Korth and Sudarshan
Update of a View
 Add a new tuple to faculty view which we defined earlier
insert into faculty values (’30765’, ’Green’, ’Music’);
This insertion must be represented by the insertion of the tuple
(’30765’, ’Green’, ’Music’, null)
into the instructor relation

Database System Concepts - 7th Edition 2.84 ©Silberschatz, Korth and Sudarshan
Some Updates cannot be Translated Uniquely
 create view instructor_info as
select ID, name, building
from instructor, department
where instructor.dept_name= department.dept_name;
 insert into instructor_info values (’69987’, ’White’, ’Taylor’);
 which department, if multiple departments in Taylor?
 what if no department is in Taylor?
 Most SQL implementations allow updates only on simple views
 The from clause has only one database relation.
 The select clause contains only attribute names of the
relation, and does not have any expressions, aggregates, or
distinct specification.
 Any attribute not listed in the select clause can be set to null
 The query does not have a group by or having clause.

Database System Concepts - 7th Edition 2.85 ©Silberschatz, Korth and Sudarshan
And Some Not at All
 create view history_instructors as
select *
from instructor
where dept_name= ’History’;
 What happens if we insert (’25566’, ’Brown’, ’Biology’, 100000)
into history_instructors?

Database System Concepts - 7th Edition 2.86 ©Silberschatz, Korth and Sudarshan

You might also like