0% found this document useful (0 votes)
5 views16 pages

Dbms Unit III SQL Quiries MM

The document provides an overview of SQL queries using a schema consisting of Sailors, Boats, and Reserves tables. It includes various SQL query examples for retrieving data, such as finding sailors' names, ages, and reservations based on specific conditions. Additionally, it discusses aggregate functions, subqueries, and the differences between nested and correlated queries, as well as the use of JOIN operations.

Uploaded by

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

Dbms Unit III SQL Quiries MM

The document provides an overview of SQL queries using a schema consisting of Sailors, Boats, and Reserves tables. It includes various SQL query examples for retrieving data, such as finding sailors' names, ages, and reservations based on specific conditions. Additionally, it discusses aggregate functions, subqueries, and the differences between nested and correlated queries, as well as the use of JOIN operations.

Uploaded by

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

Number of sample queries using the following schema:

Sailors(sid: integer, sname: string, rating: integer, age: real)


Boats(bid: integer, bname: string, color: string)
Reserves(sid: integer, bid: integer, day: date)

The key fields are underlined, and the domain of each field is listed after the field name.
Fields in an instance of one of these relations will be referred to by name, or positionally, using the
order in which they are listed above.

sid sname rating age sid sname rating age sid bid day
22 Dustin 7 45.0 28 Yuppy 9 35.0 22 101 10/10/96
31 Lubber 8 55.5 31 Lubber 8 55.5
58 103 11/12/96
58 Rusty 10 35.0 44 Guppy 5 35.0
Fig 4.3 Instance R1 of Reserves
58 Rusty 10 35.0
Fig 4.1 Instance S1 of Sailors
Fig 4.2 Instance S2 of Sailors

Boats

Bid Bname Color

101 Interlake Blue

102 Interlake Red

103 Clipper Green

104 Marine Red


The basic form of an SQL query is as follows:
SELECT [DISTINCT] select-list
FROM from-list
WHERE qualification

Sailors table data

An Instance S3 of Sailors
An Instance R2 of Reserves

Reserves table data

An Instance B1 of Boats

Boats table data


15) Find the names and ages of all sailors.
SELECT DISTINCT S.sname, S.age FROM Sailors S

With distinct
Without Distinct

11) Find all sailors with a rating above 7.


SELECT S.sid, S.sname, S.rating, S.age FROM Sailors AS S WHERE S.rating > 7

15) Find the sids of sailors who have reserved a red boat.
SELECT R.sid
FROM Boats B, Reserves R
WHERE B.bid = R.bid AND B.color = 'red';

SELECT R.sid FROM Boats B, Reserves R WHERE B.bid = R.bid AND B.color = 'red';

1) Find the names of sailors who have reserved boat number 103.

SELECT S.sname
FROM Sailors S, Reserves R
WHERE S.sid = R.sid AND R.bid=103

SELECT S.sname FROM Sailors S, Reserves R WHERE S.sid = R.sid AND R.bid=103;

Query1
SELECT sname
FROM Sailors S, Reserves R
WHERE S.sid = R.sid AND bid=103

Query1 m

SELECT sname
FROM Sailors , Reserves
WHERE Sailors.sid = Reserves.sid AND bid=103

Instance of Reserves R3

Instance of sailors s4
S4x R3

2) Find the names of sailors who have reserved a red boat.

SELECT S.sname FROM


Sailors S, Reserves R, Boats B
where S.sid = R.sid AND R.bid = B.bid AND B.color = 'red';

SELECT s.sname FROM Sailors S, Reserves R, Boats B where S.sid = R.sid AND R.bid = B.bid AND B.color =
'red';

3)Find the colors of boats reserved by Lubber.


SELECT B.color
FROM Sailors S, Reserves R, Boats B
WHERE S.sid = R.sid AND R.bid = B.bid AND S.sname = 'Lubber'

SELECT B.color FROM Sailors S, Reserves R, Boats B WHERE S.sid = R.sid AND R.bid = B.bid AND S.sname =
'Lubber'

4)Find the names of sailors who have reserved at least one boat.
SELECT S.sname
FROM Sailors S, Reserves R
WHERE S.sid = R.sid
SELECT S.sname FROM Sailors S, Reserves R WHERE S.sid = R.sid

UNION, INTERSECT, AND EXCEPT

(Q5) Find the names of sailors who have reserved a red or a green boat.
SELECT S.sname
FROM Sailors S, Reserves R, Boats B
WHERE S.sid = R.sid AND R.bid = B.bid
AND (B.color = 'red' OR B.color = 'green')

SELECT S.sname FROM Sailors S, Reserves R, Boats B


WHERE S.sid = R.sid AND R.bid = B.bid AND (B.color = 'red' OR B.color = 'green')

(Q6) Find the names of sailors who have reserved both a red and a green boat.

SELECT S.sname
FROM Sailors S, Reserves R1, Boats B1, Reserves R2, Boats B2
WHERE S.sid = R1.sid AND R1.bid = B1.bid
AND S.sid = R2.sid AND R2.bid = B2.bid
AND B1.color='red' AND B2.color = 'green';

SELECT S.sname FROM Sailors S, Reserves R1, Boats B1, Reserves R2, Boats B2
WHERE S.sid = R1.sid AND R1.bid = B1.bid AND S.sid = R2.sid AND R2.bid = B2.bid
AND B1.color='red' AND B2.color = 'green';

A better solution for these two queries is to use UNION and INTERSECT.
The OR query (Query Q5) can be rewritten as follows:(Correct)

SELECT S.sname FROM Sailors S, Reserves R, Boats B


WHERE S.sid=R.sid AND R.bid = B.bid AND B.color = 'red'
UNION
SELECT S2.sname FROM Sailors S2, Boats B2, Reserves H2
WHERE S2.sid = H2.sid AND H2.bid = B2.bid AND B2.color = 'green';

In complete symmetry, the AND query (Query Q6) can be rewritten as follows:

SELECT S.sname
FROM Sailors S, Reserves R, Boats B
WHERE S.sid = R.sid AND R.bid = B.bid AND B.color = 'red'
INTERSECT
SELECT S2.sname
FROM Sailors S2, Boats B2, Reserves R2
WHERE S2.sid=R2.sid AND R2.bid=B2.bid AND B2.color ='green';

(Q 19) Find the sids of all sailor's who have reserved red boats but not green boats.
SELECT S.sid
FROM Sailors S, Reserves R, Boats B
WHERE S.sid = R.sid AND R.bid = B.bid AND B.color = 'red'
EXCEPT
SELECT S2.sid
FROM Sailors S2, Reserves R2, Boats B2
WHERE S2.sid = R2.sid AND R2.bid = B2.bid AND B2.color = 'green';

Sailors 22, 64, and 31 have reserved red boats. Sailors 22, 74, and 31 have
reserved green boats.

Hence, the answer contains just the sid 64

Reserves relation contains sid information, there is no need to look at the Sailors relation
simpler query
SELECT H.sid
FROM Boats B, Reserves R
WHERE R.bid = B.bid AND B.color = 'red'
EXCEPT
SELECT R2.sid
FROM Boats B2, Reserves R2
WHERE R2.bicl = B2.bid AND B2.color ='green'

(Q20) Find all sids of sailors who have a rating of 10 or reserved boat 104.
SELECT S.sid
FROM Sailors S
WHERE S.rating = 10
UNION
SELECT R.sid
FROM Reserves R
WHERE R.bid = 104

The first part of the union returns the sids 58 and 71.

The second part returns 22 and 31.

The answer - set of sids 22, 31, 58, and 71.

A final point to note about UNION, INTERSECT, and EXCEPT follows.

In contrast to the default that duplicates are not eliminated unless DISTINCT is specified
in the basic query form, the default for UNION queries is that duplicates are
eliminated!

To retain duplicates, UNION ALL must be used;

Aggregate functions (count,min,max,sum,avg)

1. Find the average age of all sailors.


SELECT AVG (S.age)
FROM Sailors S;

On instance 53, the average age is 37.4.

Of course, the WHERE clause can be used to restrict the sailors considered in computing the average age.

2. Find the average age of sailors with a rating of 10.


SELECT AVG (S.age)
FROM Sailors S
WHERE S.rating = 10
3. Find the name and age of the oldest sailor.

SELECT S.sname, MAX (S.age) FROM Sailors S;

4. Count the number of sailors.

SELECT COUNT (*) FROM Sailors S

5. Count the number of different sailor names.


SELECT COUNT ( DISTINCT S.sname ) FROM Sailors S

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;

select dept_name, avg (salary) as avg_salary from instructor group by dept_name


having avg (salary) > 69000;
(QS2) Find the age of the youngest sailor who is eligible to vote (i.e., is at least
18 years old) for each rating level with at least h.uo such sailors.
SELECT S.rating, MIN (S.age) AS minage
FROM Sailors S
WHERE S.age >= 18
GROUP BY s.rating
HAVING COUNT (*) > 1

34)Find the average age of sailors of each rating level that has at least two sailors.
SELECT S.rating, AVG (S.age) AS average
FROM Sailor S
GROUP BY S.rating
HAVING COUNT (*) > 1;

SELECT S.rating, AVG (S.age) AS average FROM Sailors S GROUP BY S.rating HAVING COUNT (*) > 1;

Q36) Find the average age of sailors who are of voting age (i.e., at least 18
years old) each rating level that has at least two such sailors.

SELECT S.rating, avg ( S.age ) AS average


FROM Sailors S
WHERE s.age>18
GROUP BY s.rating

SELECT S.rating , avg(S.age ) as average FROM Sailors S WHERE s.age>18 GROUP BY s.rating;(Working)

33)For each red boat,find the number of reservations for this boat
SELECT B.bid, COUNT (*) AS reservationcount
FROM Boats B, Reserves R
WHERE R.bid = B.bid AND B.color = 'red'
GROUP BY B.bid;

SELECT [ DISTINCT] select-list


FROM from-list
WHERE 'qualification
GROUP BY grouping-list
HAVING group-qualification

MySQL GROUP BY Clause


The MYSQL GROUP BY Clause is used to collect data from multiple records and group the result by one or
more column. It is generally used in a SELECT statement.

You can also use some aggregate functions like COUNT, SUM, MIN, MAX, AVG etc. on the
grouped column.

Syntax:

SELECT expression1, expression2, ... expression_n,


aggregate_function (expression)
FROM tables
[WHERE conditions]
GROUP BY expression1, expression2, ... expression_n;

Parameters

expression1, expression2, ... expression_n: It specifies the expressions that are not encapsulated
within an aggregate function and must be included in the GROUP BY clause.

aggregate_function: It specifies a function such as SUM, COUNT, MIN, MAX, or AVG etc. tables: It specifies
the tables, from where you want to retrieve the records. There must be at least one table listed in the
FROM clause.

WHERE conditions: It is optional. It specifies the conditions that must be fulfilled for the records to be
selected.

MySQL GROUP BY Clause with COUNT function

Table named "officers" table.

1)Count repetitive number of cities in the column address.

SELECT address, COUNT(*)


FROM officers
GROUP BY address;
MySQL GROUP BY Clause with SUM function

SELECT emp_name, SUM(working_hours) AS "Total working hours"


FROM employees
GROUP BY emp_name;

MySQL GROUP BY Clause with MIN function

Specifies the minimum working hours of the employees form the table "employees".

Execute the following query:

SELECT emp_name, MIN(working_hours) AS "Minimum working hour"


FROM employees
GROUP BY emp_name;

MySQL GROUP BY Clause with MAX function


The following example specifies the maximum working hours of the employees form the table
"employees".

SELECT emp_name, MAX (working_hours) AS "Minimum working hour"


FROM employees
GROUP BY emp_name;

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

MySQL GROUP BY Clause with AVG function


Specifies the average working hours of the employees from the table "employees".

SELECT emp_name, AVG(working_hours) AS "Average working hour"


FROM employees
GROUP BY emp_name;
SubQuery/Inner Query /Nested query

A Subquery or Inner query or a Nested query is a query within another SQL query and embedded within
the WHERE clause.

A subquery is used to return data that will be used in the main query as a condition to further restrict the
data to be retrieved.

Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with the
operators like =, <, >, >=, <=, IN, BETWEEN, etc.

There are a few rules that subqueries must follow −

Subqueries must be enclosed within parentheses.

A subquery can have only one column in the SELECT clause, unless multiple columns are in the
main query for the subquery to compare its selected columns.

An ORDER BY command cannot be used in a subquery, although the main query can use an
ORDER BY. The GROUP BY command can be used to perform the same function as the ORDER
BY in a subquery.

Subqueries that return more than one row can only be used with multiple value operators such as
the IN operator.
A correlated subquery is evaluated once for each row processed by the parent statement. The parent
statement can be a SELECT, UPDATE, or DELETE statement.

A correlated subquery is one way of reading every row in a table and comparing values in each row against
related data.

It is used whenever a subquery must return a different result or set of results for each candidate row
considered by the main query

Find the details of all employees who works any department.

(Write the nested subquery and correlated query)

Example:

Emp table

Empid Ename
1 P
2 Q
3 R
4 S
5 T

Dept Table

Deptid Dname Empid


D1 CSE 1
D2 EEE 2
D3 CIVIL 3

Nested subquery

Select * from emp where empid in (select empid from dept) ;

Correlated query (Exists,Not exists etc.)

Select * from emp where empid exists (select empid from dept where emp.empid=dept.empid) ;
Join

Select * from emp,dept where emp.empid=dept.empid;

Output

1 P
2 Q
3 R

Parameters Nested Query Correlated Query Join Operation

In Nested query, a Join operation is used to


query is written combine data or rows
inside another from two or more tables
query and the In Correlated query, a based on a common field
result of inner query is nested inside between them.INNER
query is used in another query and inner JOIN, LEFT JOIN, RIGHT
execution of outer query uses values from JOIN, FULL JOIN are
Definition query. outer query. different types of Joins.

Bottom up
approach i.e. Inner
query runs first,
and only once. Top to Down Approach
Outer query is i.e. Outer query
executed with executes first and for It is basically cross
result from Inner every Outer query row product satisfying a
Approach query. Inner query is executed. condition.

Inner query
execution is not Inner query is There is no Inner Query or
dependent on dependent on Outer Outer Query. Hence, no
Dependency Outer query. query. dependency is there.

Performs better Performs slower than By using joins we


than Correlated both Nested Query and maximize the calculation
Performance Query but is Join operations as for burden on the database
slower than Join every outer query inner but joins are better
Difference
Operation. query is executed. optimized by the server so between
the retrieval time of the Nested Query,
query using joins will Correlated on :
almost always be faster
than that of a subquery.

You might also like