Introduction To SQL
Introduction To SQL
Introduction To SQL
Language
What is SQL ?
SQL is a standard that specifies how
a relational schema is created
data is inserted/updated in the relations
data is queried
transactions re started and stopped
program access data in the relations
and a host of other things to do.
SQL provides a small and concise set of commands which can be combined with dBase
commands to define and access data from a database. Every relational database management
system (RDBMS) is required to support/implement the SQL standard.
Conventional Programming
Languages
Disadvantages :
1. Difficulty in Interfacing
Interfacing an SQL database is more complex than adding a few lines of code.
2. Scalability
Users have to scale relational database on powerful servers that are expensive
and difficult to handle. To scale relational database, it has to be distributed onto
multiple servers. Handling tables on different servers is a chaos.
SQL statements are not case sensitive. It can be typed in lower case
or upper case or mix of both.
The statements can be typed in a single line or multiple lines.
A semicolon is placed to terminate th SQL statements
The Keywords cant be distributed across the line but statements may
be.
A comma(,) is used to separate parameter without a clause.
Characters and Date Constants or literals must be enclosed in single
quotes(A).
A command can be type either full or first 4 characters generally.
Syntax
CREATE TABLE <table_name>
(
<Column1_specification>,
<Column2 specification>,
<Column3 specification>,
..........
);
column name
data type
[size or length of column] //[] means optional
[constraints] // [] means optional
The table_name gives the name of the table you created, Column name gives the name
of the column,
Data Type specifies what type of data the column can hold and the size is optional,
Constraints is a condition or check applicable that is apply on a field or set of fields.
Example
This will create Employee table with five columns namely, Emp_ID, Emp_First_Name,
Emp_Last_Name, Address, Salary.
Syntax :
o To Add a Column
o
ADD <Column_specification>
For Example,
ALTER TABLE Employee
ADD Basic_Pay real;
The above query will add a column Basic_Pay to the Employee table whose data
type is real.
o Syntax To DROP a Column
o
Example :
ALTER TABLE Employee
Example :
ALTER TABLE Employee
MODIFY Salary float;
3. Rename Command
Rename Command is used to change the name of the table or the database object.
Syntax :
RENAME old_table_name
TO new_table_name;
Example :
RENAME Employee TO
WIPRO_Employees;
Syntax :
DROP TABLE table_name;
Example :
The
The
The
The
Syntax :
There are two ways to write the INSERT INTO Commands
Form 1 : (Mainly used if we want to insert data in all columns)
INSERT INTO table_name
VALUES (value1, value2, value3,....);
Example :
Let the Initial table will be :
Emp_ID
Emp_First_Name
Emp_Last_Name
Address
Salary
1000
Renu
Garg
Bhiwani
31000.00
1001
Pooja
Garg
Bhiwani
32000.00
1002
Komal
Mittal
Rohtak
35000.00
(Table 1)
INSERT INTO Employee
VALUES (1003,'Surender','Mittal','BHIWANI',50000.00);
Example of Form 2 :
INSERT INTO Employee VALUES (Emp_ID,Emp_First_Name,Emp_Last_Name)
VALUES (1004,'Renu','Mittal');
Emp_ID
Emp_First_Name
Emp_Last_Name
Address
Salary
1000
Renu
Garg
Bhiwani
31000.00
1001
Pooja
Garg
Bhiwani
32000.00
1002
Komal
Mittal
Rohtak
35000.00
1003
Surender
Mittal
Bhiwani
50000.00
1004
Renu
Mittal
NULL
NULL
(Table 2)
Syntax :
UPDATE table_name
SET <column_name1> = <value expression1>
[<column_name2> = <value expression2>
......
]
[ WHERE <condition>];
The columns whose values have to be updated and the expressions to derive these values are
included in the SET clause.
The WHERE Clause The WHERE Clause is used to extract only those records that fulfill a
specified criteria.
The command will modify the salary of the employee with 60000.00 whose ID is 1004.
SQL UPDATE Warning :
Be careful after removing WHERE Clause during updating records Because it will update all
records. For Example :
UPDATE Employee
SET ADDRESS = 'ROHTAK', Emp_Last_Name = 'Garg'
Emp_First_Name
Emp_Last_Name
Address
Salary
1000
Renu
Garg
Rohtak
31000.00
1001
Pooja
Garg
Rohtak
32000.00
1002
Komal
Garg
Rohtak
35000.00
1003
Surender
Garg
Rohtak
60000.00
1004
Renu
Garg
Rohtak
NULL
(Table 3)
Example :
SELECT Emp_ID, Emp_First_Name, Salary
FROM Employee;
Emp_First_Name
Salary
1000
Renu
31000.00
1001
Pooja
32000.00
1002
Komal
35000.00
1003
Surender
50000.00
1004
Renu
NULL
(Table 4)
Syntax for selecting all the rows without specifying column names :
SELECT *
FROM table_name;
Example :
SELECT *
FROM Employee;
Example :
SELECT Emp_ID, Emp_First_Name, Salary
FROM Employee
WHERE Emp_ID = 1002;
Emp_First_Name
Emp_Last_Name
Address
Salary
1002
Komal
Garg
Rohtak
35000.00
(Table 5)
Syntax :
DELETE FROM table_name
[WHERE <condition(s)>]
Example :
DELETE FROM Employee
where Emp_ID = 1003;
Emp_First_Name
Emp_Last_Name
Address
Salary
1000
Renu
Garg
Rohtak
31000.00
1001
Pooja
Garg
Rohtak
32000.00
1002
Komal
Garg
Rohtak
35000.00
1004
Renu
Garg
Rohtak
NULL
(Table 6)
Syntax
COMMIT [WORK];
where COMMIT is the keyword and the WORK is optional keyword and it is used to make the
commend more user friendly.
Example :
DELETE FROM Employee WHERE SALARY > 40000.00;
COMMIT;
The first statement deletes the records of the Employee whose salary>40000.00, a COMMIT
command is issued to save the changes to the database, completing the transaction.
Syntax :
ROLLBACK [WORK];
Example :
DELETE FROM Employee WHERE Salary>40000.00;
ROLLBACK;
First statement delete the records of all the employees whose salary is greater than 40000.00. But
the second statement remove the effect of first one and rollback/undo the changes made by it.
Hence, there will be no effect on Employee table.
Syntax :
GRANT <privileges> ON <table/view_name>
TO <user_name_list>/PUBLIC
FROM
<table list>
[WHERE
[GROUP BY
[HAVING
[ORDER BY
<Condition (s)>]
<grouping attributes (s)>]
<group condition>]
<attribute list>[DESC/ASC]
Select (Projection)
Where (Condition)
Example
Eno
Fname
Lname
Address
City
1000
Ankit
Mittal
MC Colony
Bhiwani
1001
Pooja
Garg
JainChowk
Bhiwani
1002
Komal
Gupta
Babra town
Rohtak
1003
Surender
Jain
Model Town
Rohtak
Distinct keyword:
In a table, some of the columns may contain duplicate values. This is not a problem, however,
sometimes you may want to listen on a different (distinct) values in a table.
The DISTINCT keyword can be used to return only distinct different values.
Description
Equal
!=
Not Equal
>
Greater Than
<
Less Than
>=
<=
BETWEEN
LIKE
IN
AND Operators
OR Operator
ORDER BY Name;
where Age>10
GROUP BY Rollno
Query 3: Find the total number of students in a branch order by their Roll
Numbers?
GROUP BY BranchID
ORDER BY COUNT(Rollno)
GROUP BY BranchID
ORDER BY a;
Query 4 : Find total strength of each branch and display the details of branches
where the total number of students is more than 45 and display them in ascending
order.
Wrong Query :
GROUP BY BranchID
HAVING a>45
ORDER BY a;
Correct Query :
GROUP BY BranchID
HAVING COUNT(Rollno)>45
ORDER BY a;
Result : The main motive of this query is to tell you that we cannot
use aliases in HAVING Clause.
Orders
OID
OrderDate
OrderPrice
Customer
2015/08/24
1000
Ankit
2015/07/25
1600
Pooja
2015/06/24
700
Ankit
2015/05/24
300
Ankit
2015/12/24
2000
Surender
2015/7/24
100
Pooja
Customer
OrderPrice
Ankit
2000
Pooja
1700
Surender
2000
Query 1 : Find the student details who got second maximum or third maximum
or in general nth maximum marks ?
Query 2 :Find all the total number of students in each and every branch?
GROUP BY BranchID;
The HAVING clause was added to SQL because the where keyword could not be
used with aggregate functions.
Query
Example 2: Retrieve students whose branch average marks is greater than equal
to 65.
Query
: SELECT *
FROM Student
GROUP BY (Branch)
HAVING AVG(Marks)>65;
Solution : It calculates average of the groups and then prints all the attributes of
the table for the group whose AVG(Marks) 65.
For example :
GROUP BY COUNT(Rollno);
GROUP BY a;
GROUP BY BranchID;
Example : Find out the branch detail whose total strength is more
than 50 students?
Query :
GROUP BY BranchID
HAVING COUNT(Rollno)>50.
Example :
Query
GROUP BY Rollno
HAVING SUM(Fine)>20;
FROM Student
WHERE marks>50
GROUP BY(BRANCH);
HAVING Clause
Employee
Eno
Name
Age
Salary
1000
Ankit
24
30000
1001
Pooja
24
20000
1002
Komal
19
10000
1003
Surender
49
40000
Work_IN
Eno
Dno
1000
10
1001
10
1002
11
1003
10
Department
Dno
Dname
City
10
Landline
Bhiwani
11
Phone
Rohtak
Query 4 : Get the employee number and name of the employees whose Salary is greater than
25000.
Solution : SELECT Eno, Name FROM Employee WHERE Salary>25000;
range
operations.
(Using
BETWEEN &
NOT
Examples of SubQueries :
Subquery 1: Find names of employees who work in Department number 11.
Solution : SELECT Name FROM Employee WHERE
Employee.Eno = (SELECT Work_IN.Eno FROM Work_IN
WHERE Dno =11);
Subquery 2: Find name of employee whose basic pay is Greater then all basic pay of the
employees working in Department number 10.
Solution : SELECT Name FROM Employee WHERE
Salary > ALL(SELECT Salary FROM Employee WHERE Employee.Eno =
(SELECT Work_IN.Eno FROM Work_IN WHERE Dno = 10))
Subquery 3 : Find the names of employees whose basic pay is greater than the average basic
pay.
Solution : SELECT Name From Employee WHERE Salary > (SELECT AVG(Salary)
FROM Employee);
Characteristics of subquery:
The inquiry will run first and substitute its results in outer query.
The variable from outer query can be used in the inner query but
reverse is not true.
Corelated Subquery : Inner query will run some time as many times
as the number of rows are available in `the outer query. If it is refer a
variable in outer query then it is called correlated subquery. For
Example :
The following operators are normally used between query and subquery:
IN predicate : IN or NOT IN
- (DIFFERENCE)
* (MULTIPLY)
/ (DIVISION)
Relational Operators :
= (EQUAL TO)
Conjunction Operators : Conjunction Operators are used to combine the conditions. Operators
are :
AND Operator
OR Operator
Operat
ors
Meaning
Unique
All
Any
Is Null
Betwee
n
Used to search for values that are within a set of value, given the
minimum value and maximum value.
In
Like
Exist
Used to search for the presence of a row in a specified table that meets
certain criteria.
[NOT] IN
]NOT] EXIST
IS [NOT] NULL
[NOT] BETWEEN
[NOT] LIKE
Function
Meaning
Count ([DISTINCT]
attribute)
Count (*)
Sum ([DISTINCT]
attribute)
AVG ([DISTINCT]
attribute)
Max (attribute)
Min (attribute)
UNION
INTERSECT
MINUS
UNION ALL
INTERSECT ALL
MINUS ALL
Example :
Consider the two relation R(A) and S(A) such that
CONTAIN Operator
The CONTAIN Operator is similar to Division Operator in Relational Algebra.
NULL values :
NULL is the set of some randomly generated ASCII value, generated by DBMS engine.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name
BETWEEN value1 AND value2;
The NOT BETWEEN operator select the data outside the range of data between two values. The
values can be text, numbers or date.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name
NOT BETWEEN value1 AND value2;
Example :
SELECT * FROM Student
WHERE Age=19
AND (Name = 'Ankit' OR Marks = 458)
Example 1 :
Example 2:
Consider the relation Employee(Eno,Ename,Sal,Dno)
Eno
Ename
Sal
Dno
E1
E2
10
E3
15
E4
20
E5
25
Query
Solution : >ANY(15,25) E4
If the inner query is prefixed with NOT EXIST, then the condition is
treated as true, if inner query returns empty rows.
Points :
Find the student details whose name starts with S and from branch
CSE.
Find all the student details who opted network protocol as a subject.
Find the details of student whose 1st letter is A and 4th letter is C
and last letter is D.
Find the details of students who are in CSE branch and coming from
Hyderabad and whose 3rd letter is A.
WHERE Name LIKE '_ _ A%' AND City = 'Hyderabad' AND Branch =
'CSE';
For Example :
Find the details of the order, whose ordername starts with P and ends with S and contains a
% symbol?
SELECT * FROM Orderdetails
WHERE Ordername LIKE 'P% /% %S';
Result 1: MAX and MIN marks can be used on both numeric and non
numeric columns. For Example,
Result 2: SUM and AVG must be applied only on numeric queries. For
Example,
Result 3: DISTINCT has no effect with MIN and MAX but will have a
impact on SOME and AVG. For Example,
The
Query
(d)
is
wrong.
Reason : Aggregate functions operate on a single column of a table or on expressions
and returns a single value, but it cannot work on multiple columns simultaneously.
// Produces
Incorrect Result
Query 1: Find the details of students whose marks lies between 500
and 600.
Query 2: Find the details of student whose marks does not lie
between 350 and 400.
If any name consists only a single letter K, then that will be included in the
BETWEEN case.
SQL will give you a syntax error because lower bound must be mentioned first in
between query.
Query 2 : Find the details of all the students who are having e-mail addresses.
SELECT * FROM Students
WHERE email IS NOT NULL;
Question 3 : In SQL, relations can contain NULL values, and comparisons with
null values are treated as unknown. Suppose all comparisons with a null value
are treated as false. Which of the following pairs is not equivalent? a) x=5
not(not(x=5)) b) x=5 x>4 and x<6 where x is an integer c) x5 not(x=5) d) None
of the Above [GATE 2000]
Solution :
Query : Retrieve all customers Name, where customer places an order through Agent A5 ?
Solution :
1. SELECT Cname FROM Customers
WHERE Cno
IN(SELECT Cno FROM Order
WHERE Ano = 'A5');
OR
2. SELECT Cname FROM Customers
WHERE Cno
ANY (SELECT Cno FROM Order
WHERE Ano = 'A5');
OR
3. SELECT C.Cname FROM Customer C
WHERE EXIST(SELECT * FROM Order O
WHERE C.Cno = O.Cno AND O.Ano = 'A5');
OR
4. SELECT C.Cname FROM Customer C, ORDER O
WHERE C.Cno = O.Cno AND O.Ano = 'A5' ;
Joins in SQL
A Join
is
a
query
that
combines
rows from
two
or
more
tables.
In a join query, more than one table are listed in FROM clause. The function of combining data
from
multiple
tables
is
called
joining.
SQL can obtain data from several related tables by performing either a physical or virtual join on
the
tables.
The WHERE Clause is most often used to perform the JOIN function with two or more tables
have columns.
Equi join
o
Inner Join
Outer Join
Self join
Natural join
Joins are used when we have to select data from two or more tables. Joints are used to extract
data from two (or more) tables, when we need a relationship between certain columns in these
tables.
The SQL join condition is always used in the WHERE clause of SELECT, UPDATE and
DELETE statements.
Equi join :
Equi join is a simple SQL join condition that uses equals sign as a comparison operator.
Syntax :
SELECT col1,col2,col3
FROM table1,table2
WHERE table1.col1 = table2.col2;
Cartesian product :
The Cartesian product is also referred as cross-join. It is a binary operation and is denoted by X.
The degree of the new relation is the sum of the degrees of two relations on which Cartesian
product is operated. The number of the tuples of the new relation is equal to the product of the
number of tuples, of the two relations on which Cartesian product is performed.
Example 1:
Let
A
=
{1,2}
and
B={a,b,c},
Then,
AB
=
{(1,a),(1,b),(1,c),(2,a),(2,b),(2,c)}
Elements of A(3) * Elements of B(2) = Elements of [AB] (6)
Example 2:
Consider two relations Person and Order such that
ORDERS
PERSON
P_ID
Last_Nam
e
First_Nam
e
Sharma
Abhay
Mumbai
Gupta
Mohan
Delhi
Verma
Akhil
City
Mumbai
Solution :
O_id
Order_No
P_id
10050
25000
5687
45000
35000
15
Last_Name
First_Name
Order_No
Sharma
Abhay
5687
Sharma
Abhay
45000
Verma
Akhil
10050
Verma
Akhil
25000
Points
All rows in the first table are joined to all rows in the second table.
Types of Equi-Joins
SQL Equi-Joins are further classified into two categories
Inner join
Outer join
Inner join
The Inner joins returns us the rows which are common in both the tables. i.e. gives the
intersection of two tables.
Syntax :
SELECT col1,col2
FROM table1 INNER JOIN table2
ON table1.column_name = table2.column_name;
Outer join
The outer join include rows in a joint result even when they have no match in the joint table.
And Outer join Returns all rows that must satisfy the join condition and also returns those rows
from one table for which no rows from the other satisfy the join condition.
Solution :
Last_Name
First_Name
Order_No
Sharma
Abhay
5687
Sharma
Abhay
45000
Verma
Akhil
10050
Verma
Akhil
25000
Gupta
Mohan
NULL
The right outer join return all rows from the right table, even if there are no matches in the left
table.
Syntax :
SELECT col1,col2
FROM table1
RIGHT JOIN table2
ON table1.col_name=table2.col_name;
Example :
SELECT P.Lname, P.Fname, O.Orderno
FROM Person P
RIGHT JOIN Order O
ON P.PID = O.PID
ORDER BY P.Lname;
Result :
Last_Name
First_Name
Order_No
Sharma
Abhay
5687
Sharma
Abhay
45000
Verma
Akhil
10050
Verma
Akhil
25000
NULL
NULL
35000
Self join
A self join is a join in which the table is joined with itself to get the appropriate results. In this
case, it is necessary to ensure that the join statement defines an ALIAS name for both the of
copies of the tables to avoid column ambiguity.
Example :
Consider the relation Course as :
TABLE COURSE
Course_id
Course_Name
Pre_Course
NULL
C++
Java
C#
VB.NET
Solution :
Course
Prerequisite_Course
C++
Java
C++
C#
Java
VB.NET
Java
Syntax :
SELECT * FROM table1,table2
WHERE table1.column > table2.column;
Example :
SELECT E.Empno, E.Ename, E.Salary, S.Grade
FROM Emp E, SalaryGrade S
WHERE E.Salary BETWEEN S.LowSalary AND S.HighSalary;
Natural join
The natural join is a type of Equi Join and is structured in such a way that, columns with same
name of associated tables will appear once only.
Syntax :
SELECT * FROM table1
NATURAL JOIN table2;
Example :
SELECT * FROM Person
NATULAR JOIN Orders;
Solution :
P_ID
Last_Name
Sharma
Sharma
Verma
Verma
First_Name
City
O_ID
Order_No
Abhay
Mumbai
5687
Abhay
Mumbai
45000
Akhil
Mumbai
10050
Akhil
Mumbai
25000
Union
The union is used to return all the distinct rows selected by either query.
Example :
(SELECT Sname FROM Student
WHERE Stream = 'Science') UNION
(SELECT Sname FROM Student
WHERE Stream = 'Arts');
Syntax :
CREATE VIEW <view_name>
[<view column names>]
AS <query specification>;
The view column names are optional. The <query specification> is the SELECT for selecting the
rows and columns which will constitute the view. Views are typically used in queries, and are
required to provide restricted access, or more relevant window to the user wanting to see the
data.
Example :
CREATE VIEW DPT100
(E_Code,Ename,Basic)
AS SELECT E_Code,Ename,Basic
FROM Employee
WHERE Basic>5000;
The view DPT100 will include only the employee having basic greater than 5000 in employee
table.
Table ALIASES
Alias means another name. The table alias means to rename a table in a particular SQL
statement. The renaming is a temporary change and the actual table name does not change in
the database.
Query : Get the employees name who have some basic pay.
Renaming Using AS :
We can rename attribute and also the table using AS operator. Consider the same example,
SELECT Ename AS Employee_Name FROM emp AS First, Emp AS Second
WHERE First.Basic = Second.Basic
AND First.Eno <> Second.Eno;
SQL Comments
A Comment is the text which appear within the SQL statement such that they do not affect to the
SQL statement in execution.
A comment can be written in two ways :
Begins with (2 hyphens) and proceed with the text of the comment.
DESCRIBE Command
Describe an Oracle table, view, synonym, package or function.
Syntax :
DESCRIBE table_name
DESC table_name;
CLEAR SCREEN
Clear screen is used to clear the screen at SQL* PLUS prompt.
Syntax:
CLEAR SCREEN;
Questions on SQL
Question 1 : Consider the following schema:
Suppliers(sid: integer, sname: string, address: string)
Parts(pid: integer, pname: string, color: string)
Catalog(sid: integer, pid: integer, cost: real)
The Catalog relation lists the prices charged for parts by
Suppliers. Write the following queries in SQL:
EXCEPT
( SELECT C.pid FROM Catalog C
WHERE C.sid = S.sid ))
4. Find the pnames of parts supplied by Acme Widget Suppliers and no one else.
Solution : SELECT p.pname FROM Parts AS p
WHERE p.pid IN (
(SELECT c1.pid AS pid FROM Catalog AS c1, Suppliers s1
WHERE c1.pid = s1.sid
AND s1.sname = Acme Widget Suppliers)
EXCEPT
(SELECT DISTINCT c2.pid AS pid
FROM Catalog AS c2, Suppliers s2
WHERE c2.pid = s2.sid
AND s2.sname != Acme Widget Suppliers))
5. Find the sids of suppliers who charge more for some part than the average
cost of that part (averaged over all the suppliers who supply that part.
Solution : SELECT DISTINCT c.sid FROM Catalog AS c,
(SELECT c1.pid AS avg pid, AVG(c1.cost) AS avg cost
FROM Catalog AS c1 GROUP BY c1.pid) AS TEMP
WHERE c.pid = TEMP.avg pid AND c.cost > TEMP.avg cost
6. Find the sids of suppliers who supply a red part and a green part.
Solution : (SELECT DISTINCT c1.sid AS SID
FROM Parts AS p1, Catalog AS c1
WHERE p1.pid = c1.pid AND p1.color = green)
INTERSECT (
SELECT DISTINCT c2.sid AS SID
FROM Parts AS p2, Catalog AS c2
WHERE p2.pid = c2.pid AND p2.color = red)
or
SELECT DISTINCT c.sid
FROM Catalog c, Parts p
WHERE c.pid = p.pid and p.color = 'red'
INTERSECT
SELECT DISTINCT c.sid
FROM Catalog c, Parts p
WHERE c.pid = p.pid and p.color = 'green'
7. For every supplier who supplies at least 1 red part, print the name of the
supplier and the total number of red parts that he or she supplies.
Solution : SELECT S.sname, COUNT(*) as PartCount
FROM Suppliers S, Catalog C, Parts P
WHERE C.sid = S.sid and P.pid = C.pid and P.color = 'Red'
GROUP BY S.sname, S.sid
8. For each part, find the sname of the supplier who charges the most for that
part.
Solution : SELECT P.pid, S.sname
FROM Parts P, Suppliers S, Catalog C
WHERE C.pid = P.pid
AND C.sid = S.sid
(a) Find the names of grandparents of all the people who were born in San
Francisco.
Solution : SELECT p2.PersonID, p2.Name
FROM Parent AS p1, Person AS p2, Parent AS p3,
Person AS p4
WHERE p1.ParentID = p2.PersonID
AND p1.ChildID = p3.ParentID
AND p3.ChildID = p4.PersonID
AND p4.CityOfBirth = San Francisco
(b) Find the names of all people who were born in the same city as their
father.
Solution : SELECT p1.Name
FROM Parent AS p1, Person AS p2, Person AS p3
WHERE p1.ChildId = p2.PersonID
AND p1.ParentID = p3.PersonID
AND p3.CityOfBirth = p2.CityOfBirth
AND p3.Sex = Male
(a)
Solution : SELECT p.Z AS Z FROM P AS p, Q AS q
WHERE p.Y != Q.Y
(b)
Solution : SELECT X
FROM ( (SELECT p1.X AS X, q1.U as U FROM P AS p1, Q AS q1
WHERE p1.X = q1.X AND p1.Y = q1.Y AND p1.X = 20)
UNION
(SELECT p2.X AS X, q1.U AS U FROM P AS p2, Q AS q2
WHERE p2.X = q2.X AND p2.Y = q2.Y AND p2.X = 15))
(c)
Solution : SELECT DISTINCT p1.Z FROM P AS p1
WHERE NOT EXISTS
((SELECT q1.X, q1.Y FROM Q AS q1)
EXCEPT
(SELECT p2.X, p2.Y FROM P AS p2
WHERE p2.Z = p1.Z))
OR
a) Find the names of aircraft such that all pilots certified to operate them
have salaries more than $80,000.
Solution : SELECT DISTINCT A.aname
FROM Aircraft A
WHERE A.Aid IN (SELECT C.aid
FROM Certified C, Employees E
WHERE C.eid = E.eid AND
NOT EXISTS ( SELECT *
FROM Employees E1
WHERE E1.eid = E.eid AND E1.salary < 80000 ))
b) For each pilot who is certified for more than three aircraft, find the eid
and the maximum cruisingrange of the aircraft for which she or he is
certified.
Solution : SELECT C.eid, MAX (A.cruisingrange)
FROM Certified C, Aircraft A
WHERE C.aid = A.aid
GROUP BY C.eid
HAVING COUNT (*) > 3
c) Find the names of pilots whose salary is less than the price of the
cheapest route from Los Angeles to Honolulu.
SOlution : SELECT DISTINCT E.ename
FROM Employees E
WHERE E.salary < ( SELECT MIN (F.price)
FROM Flights F
WHERE F.from = Los Angeles AND F.to = Honolulu )
d) For all aircraft with cruisingrange over 1000 miles, find the name of the
aircraft and the average salary of all pilots certified for this aircraft.
Solution : SELECT Temp.name, Temp.AvgSalary
FROM ( SELECT A.aid, A.aname AS name,
AVG (E.salary) AS AvgSalary
FROM Aircraft A, Certified C, Employees E
WHERE A.aid = C.aid AND
C.eid = E.eid AND A.cruisingrange > 1000
GROUP BY A.aid, A.aname ) AS Temp
e) Find the names of pilots certified for some Boeing aircraft.
Solution : SELECT DISTINCT E.ename
FROM Employees E, Certified C, Aircraft A
( SELECT F0.flno
FROM Flights F0, Flights F1
WHERE F0.from = Madison AND F0.to <> New York
AND F0.to = F1.from AND F1.to = New York
AND F1.departs > F0.arrives
AND F1.arrives < 18:00 )
UNION
( SELECT F0.flno
FROM Flights F0, Flights F1, Flights F2
WHERE F0.from = Madison
AND F0.to = F1.from
AND F1.to = F2.from
AND F2.to = New York
AND F0.to <> New York
AND F1.to <> New York
AND F1.departs > F0.arrives
AND F2.departs > F1.arrives
AND F2.arrives < 18:00 ))
j) Compute the difference between the average salary of a pilot and the
average salary of all employees (including pilots).
Solution : SELECT Temp1.avg - Temp2.avg
FROM (SELECT AVG (E.salary) AS avg
FROM Employees E
1. Print the names and ages of each employee who works in both the Hardware
department and the Software department.
Solution : SELECT E.ename, E.age
FROM Emp E, Works W1, Works W2, Dept D1, Dept D2
WHERE E.eid = W1.eid
AND W1.did = D1.did AND D1.dname = Hardware
AND E.eid = W2.eid AND W2.did = D2.did
AND D2.dname = Software
2. For each department with more than 20 full-time-equivalent employees (i.e.,
where the part-time and full-time employees add up to at least that many fulltime employees), print the did together with the number of employees that work
in that department.
Solution : SELECT W.did, COUNT (W.eid)
FROM Works W
GROUP BY W.did
6. If a manager manages more than one department, he or she controls the sum
of all the budgets for those departments. Find the managerids of managers who
control more than $5 million.
Solution : SELECT D.managerid
FROM Dept D
WHERE 5000000 < (SELECT SUM (D2.budget)
FROM Dept D2
WHERE D2.managerid = D.managerid )
7. Find the managerids of managers who control the largest amounts.
Solution : SELECT DISTINCT tempD.managerid
FROM (SELECT DISTINCT D.managerid,
SUM (D.budget) AS tempBudget
FROM Dept D
GROUP BY D.managerid ) AS tempD
WHERE tempD.tempBudget = (SELECT MAX (tempD.tempBudget)
FROM tempD)
8. Find the enames of managers who manage only departments with budgets larger
than $1 million, but at least one department with budget less than $5 million.
Solution : SELECT E.ename
FROM Emp E, Dept D
WHERE E.eid = D.managerid GROUP BY E.Eid, E.ename
HAVING EVERY (D.budget > 1000000)
AND ANY (D.budget < 5000000)
Sid
Sname
rating
Age
18
Jones
30.0
41
Jonah
56.0
22
Ahab
44.0
63
Moby
Null
15.0
Table 5.1
1. Write SQL queries to compute the average rating, using AVG; the sum of the
ratings, using SUM; and the number of ratings, using COUNT.
Solution : SELECT AVG (S.rating) AS AVERAGE
FROM Sailors S
SELECT SUM (S.rating)
FROM Sailors S
SELECT COUNT (S.rating)
FROM Sailors S
2. If you divide the sum just computed by the count, would the result be the
same as the average? How would your answer change if these steps were carried
out with respect to the age field instead of rating?
Solution : The result using SUM and COUNT would be smaller than the
result using AVERAGE if there are tuples with
rating = NULL.
This is because all the aggregate operators, except for
COUNT, ignore NULL values. So the first approach would
compute the average over all tuples while the second
approach would compute the average over all tuples with
non-NULL rating values. However,if the aggregation is done
on the age field, the answers using both approaches would
be the same since the age field does not take NULL values.
3. Consider the following query: Find the names of sailors with a higher
rating than all sailors with age < 21. The following two SQL queries attempt
to obtain the answer to this question. Do they both compute the result? If
not, explain why. Under what conditions would they compute the same result?
SELECT S.sname FROM Sailors S WHERE NOT EXISTS ( SELECT * FROM Sailors S2
WHERE S2.age < 21 AND S.rating <= S2.rating ) SELECT * FROM Sailors S WHERE
S.rating > ANY ( SELECT S2.rating FROM Sailors S2 WHERE S2.age < 21 )
Solution : Only the first query is correct. The second query returns
the names of sailors with a higher rating than at least
one sailor with age < 21. Note that the answer to the
second query does not necessarily contain the answer to
the first query. In particular, if all the sailors are at
least 21 years old, the second query will return an empty
set while the first query will return all the sailors.
This is because the NOT EXISTS predicate in the first
query will evaluate to true if its subquery evaluates to
an empty set, while the ANY predicate in the second query
will evaluate to false if its subquery evaluates to an
empty set. The two queries give the same results if and
only if one of the following two conditions hold :
1. The Sailors relation is empty, or
2. There is at least one sailor with age > 21 in the Sailors
relation, and for every sailor s, either s has a higher
rating than all sailors under 21 or s has a rating no
higher than all sailors under 21.
(a) Show the left outer join of S with itself, with the join condition being
sid=sid. (b) Show the right outer join of S with itself, with the join
condition being sid=sid. (c) Show the full outer join of S with itself, with
the join condition being sid=sid.
Solution :
(d) Show the left outer join of S1 with S2, with the join condition being
sid=sid. (e) Show the right outer join of S1 with S2, with the join condition
being sid=sid. (f) Show the full outer join of S1 with S2, with the join
condition being sid=sid.
Solution :
1. Find the names of all Juniors (level = JR) who are enrolled in a class
taught by I. Teach.
Solution : SELECT DISTINCT S.Sname
FROM Student S, Class C, Enrolled E, Faculty F
WHERE S.snum = E.snum
AND E.cname = C.name
AND C.fid = F.fid AND
F.fname = I.Teach AND S.level = JR
2. Find the age of the oldest student who is either a History major or
enrolled in a course taught by I. Teach.
Solution : SELECT MAX(S.age)
FROM Student S
12. For each age value that appears in Students, find the level value that
appears most often. For example, if there are more FR level students aged 18
than SR, JR, or SO students aged 18, you should print the pair (18, FR).
Solution : SELECT S.age, S.level
FROM Student S
GROUP BY S.age, S.level,
HAVING S.level IN (SELECT S1.level
FROM Student S1
WHERE S1.age = S.age
GROUP BY S1.level, S1.age
HAVING COUNT (*) >= ALL (SELECT COUNT (*)
FROM Student S2
WHERE s1.age = S2.age
GROUP BY S2.level, S2.age))