0% found this document useful (0 votes)
6 views7 pages

Complex Queries

The document explains nested queries in SQL, detailing how inner queries provide values for outer queries, and includes examples of using tuples, comparison operators, and handling ambiguity with aliases. It also covers the EXISTS and NOT EXISTS functions, the UNIQUE function, explicit sets, renaming attributes, and various types of joins, including natural and outer joins. Additionally, it illustrates multiway joins and alternative syntax for outer joins, emphasizing the importance of clarity and structure in SQL queries.

Uploaded by

gowdaroshan49
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)
6 views7 pages

Complex Queries

The document explains nested queries in SQL, detailing how inner queries provide values for outer queries, and includes examples of using tuples, comparison operators, and handling ambiguity with aliases. It also covers the EXISTS and NOT EXISTS functions, the UNIQUE function, explicit sets, renaming attributes, and various types of joins, including natural and outer joins. Additionally, it illustrates multiway joins and alternative syntax for outer joins, emphasizing the importance of clarity and structure in SQL queries.

Uploaded by

gowdaroshan49
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/ 7

Nested Queries

A nested query is a complete SQL query that is embedded within another SQL query. The
outer query is the main query, while the inner query (or subquery) provides a set of values
that the outer query can use.

SELECT DISTINCT Pnumber


FROM PROJECT
WHERE Pnumber IN
( SELECT Pnumber
FROM PROJECT, DEPARTMENT, EMPLOYEE
WHERE Dnum = Dnumber AND
Mgr_ssn = Ssn AND Lname = 'Smith' )
OR
Pnumber IN
( SELECT Pno
FROM WORKS_ON, EMPLOYEE
WHERE Essn = Ssn AND Lname = 'Smith' );

First Nested Query:

This part retrieves project numbers (Pnumber) for projects managed by employees with the
last name 'Smith'.
It joins the PROJECT, DEPARTMENT, and EMPLOYEE tables to find the relevant project
numbers.
Second Nested Query:

This part retrieves project numbers (Pno) for projects where employees with the last name
'Smith' are working.
It joins the WORKS_ON and EMPLOYEE tables.
Outer Query:

The outer query selects distinct project numbers from the PROJECT table where the project
number is found in
either of the results from the nested queries.

Using Tuples in Comparisons


SQL also allows you to compare tuples (sets of values) using parentheses. For example:
SELECT DISTINCT Essn
FROM WORKS_ON
WHERE (Pno, Hours) IN ( SELECT Pno, Hours
FROM WORKS_ON
WHERE Essn = '123456789' );
It selects the employee social security numbers (Essn) of all employees who work on the
same project and for the
same number of hours as the employee with Essn = '123456789'.
Comparison Operators with Sets
SQL provides several comparison operators that can be used with sets or multisets:

IN: Checks if a value exists in a set.


= ANY or = SOME: Checks if a value is equal to any value in a set.
ALL: Checks if a value meets a condition against all values in a set.
Example Using ALL
SELECT Lname, Fname
FROM EMPLOYEE
WHERE Salary > ALL ( SELECT Salary
FROM EMPLOYEE
WHERE Dno = 5 );
Handling Ambiguity in Nested Queries
When using nested queries, you may encounter ambiguity if the same attribute name exists in
both the outer
and inner queries. To avoid this, you can use aliases (tuple variables) to
clarify which table's attribute you are referring to.
SELECT E.Fname, E.Lname
FROM EMPLOYEE AS E
WHERE E.Ssn IN ( SELECT D.Essn
FROM DEPENDENT AS D
WHERE E.Fname = D.Dependent_name
AND E.Sex = D.Sex );

SELECT E.Fname, E.Lname


FROM EMPLOYEE AS E
WHERE E.Ssn IN ( SELECT D.Essn
FROM DEPENDENT AS D
WHERE E.Fname = D.Dependent_name
AND E.Sex = D.Sex );
Explanation of Q16
Outer Query:

The outer query selects the first name (Fname) and last name (Lname) of employees from the
EMPLOYEE table.
For each employee, it checks if their Ssn is in the result of the nested query.
Nested Query:

The nested query retrieves the Essn (employee social security number) from the
DEPENDENT table.
It filters dependents based on the condition that the dependent's name matches
the employee's first name and the sex matches the employee's sex.
Execution:

For each employee in the EMPLOYEE table, the nested query is


executed to find matching dependents. If a match is found, that employee is included in the
result.
Equivalent Single Block Query
The same logic can be expressed without a nested query, as shown in Q16A:
SELECT E.Fname, E.Lname
FROM EMPLOYEE AS E, DEPENDENT AS D
WHERE E.Ssn = D.Essn AND E.Sex = D.Sex
AND E.Fname = D.Dependent_name;

EXISTS Function
The EXISTS function checks whether a nested query returns any rows.
It returns TRUE if the nested query returns at least one tuple and FALSE if it returns no
tuples.
This function is often used in correlated nested queries.

Example of EXISTS
Consider the following query (Q16B):
SELECT E.Fname, E.Lname
FROM EMPLOYEE AS E
WHERE EXISTS ( SELECT *
FROM DEPENDENT AS D
WHERE E.Ssn = D.Essn AND E.Sex = D.Sex
AND E.Fname = D.Dependent_name);
Explanation:

For each employee in the EMPLOYEE table, the nested query checks if there are any
dependents in the
DEPENDENT table that match the employee's social security number, sex, and first name.
NOT EXISTS Function
The NOT EXISTS function is the opposite of EXISTS. It returns TRUE if the nested query
returns no tuples and FALSE if it returns at least one tuple.

Example of NOT EXISTS


Consider the following query (Q6):
SELECT Fname, Lname
FROM EMPLOYEE
WHERE NOT EXISTS ( SELECT *
FROM DEPENDENT
WHERE Ssn = Essn );
This query retrieves the names of employees who have no dependents.
For each employee, the nested query checks for any dependents related to that
employee. If none exist, the employee's name is included in the result.
Using EXISTS with Multiple Conditions
You can also use EXISTS with multiple conditions in nested queries. For example,
SELECT Fname, Lname
FROM EMPLOYEE
WHERE EXISTS ( SELECT *
FROM DEPENDENT
WHERE Ssn = Essn )
AND EXISTS ( SELECT *
FROM DEPARTMENT
WHERE Ssn = Mgr_ssn );

SELECT Fname, Lname


FROM EMPLOYEE
WHERE NOT EXISTS ( ( SELECT Pnumber
FROM PROJECT
WHERE Dnum = 5)
EXCEPT ( SELECT Pno
FROM WORKS_ON
WHERE Ssn = Essn) );
The first subquery selects all projects controlled by department 5.
The second subquery selects all projects that the employee works on.
If the set difference is empty, it means the employee works on all projects controlled by
department 5.
Projects in Dept 5 = Project 1, Project 2

Employee A works on Project 1 and Project 2 → ✅ include

Employee B only works on Project 1 → ❌ skip

UNIQUE Function
The UNIQUE function checks if the result of a query contains duplicate tuples. It returns
TRUE if there are no duplicates and FALSE if duplicates exist.

Example of UNIQUE
sql
Run
Copy code
SELECT UNIQUE(column_name)
FROM table_name;
Explanation:

This query retrieves unique values from a specified column in a table.


It can be useful for ensuring that the results of a nested query are treated as a set rather than a
multiset.

Explicit Sets in SQL


An explicit set is a list of values that you can use in a query's WHERE clause. This allows
you to filter results based on specific values without needing a nested query.

Example of Explicit Sets


Consider the following query (Q17):

SELECT DISTINCT Essn


FROM WORKS_ON
WHERE Pno IN (1, 2, 3);
Explanation:

This query retrieves the distinct social security numbers (Essn) of employees who work on
projects with numbers 1, 2, or 3.
The IN operator is used to specify the explicit set of project numbers (1, 2, 3) that we are
interested in.
Renaming Attributes in SQL
You can rename attributes in the result set of a query using the AS keyword.
This is useful for making the output more readable or for avoiding naming conflicts.

Example of Renaming Attributes


Consider the following query (Q8A):

SELECT E.Lname AS Employee_name, S.Lname AS Supervisor_name


FROM EMPLOYEE AS E, EMPLOYEE AS S
WHERE E.Super_ssn = S.Ssn;
Explanation:

This query retrieves the last names of employees and their supervisors from the EMPLOYEE
table.
The AS keyword is used to rename the columns in the result set:
E.Lname is renamed to Employee_name.
S.Lname is renamed to Supervisor_name.
The result will have clearer column headers, making it easier to understand the output.

If at least one matching dependent exists, the employee's name is included in the result.

Joined Tables in SQL


A joined table is created when you combine two or more tables based on a related column.
This can be done using various types of joins, such as inner joins and outer joins.

Example of a Joined Table


Consider the following query (Q1A) that retrieves the names and addresses of
employees who work for the 'Research' department:
SELECT Fname, Lname, Address
FROM (EMPLOYEE JOIN DEPARTMENT ON Dno = Dnumber)
WHERE Dname = 'Research';
The FROM clause specifies a joined table created by joining the EMPLOYEE and
DEPARTMENT tables on the
condition that the department number (Dno) in the EMPLOYEE table matches the
department number (Dnumber)
in the DEPARTMENT table.
The WHERE clause filters the results to include only those employees who work in the
'Research' department.
NATURAL JOIN
A NATURAL JOIN automatically joins tables based on columns with the same name. If the
join attributes have
different names, you can rename them using the AS keyword.
SELECT Fname, Lname, Address
FROM (EMPLOYEE NATURAL JOIN (DEPARTMENT AS DEPT (Dname, Dno, Mssn,
Msdate)))
WHERE Dname = 'Research';
Explanation:

In this example, the DEPARTMENT table is renamed to DEPT, and its attributes are adjusted
to match the EMPLOYEE table's join attribute.
The NATURAL JOIN automatically uses the renamed attributes for the join condition.
Outer Joins
Outer joins include all records from one table and the matched records from the other table. If
there is no match, NULL values are returned for the columns of the table that does not have a
match.

Types of Outer Joins


LEFT OUTER JOIN: Includes all records from the left table and matched records from the
right table.
RIGHT OUTER JOIN: Includes all records from the right table and matched records from the
left table.
FULL OUTER JOIN: Includes all records when there is a match in either left or right table
records.
Example of LEFT OUTER JOIN
SELECT E.Lname AS Employee_name, S.Lname AS Supervisor_name
FROM (EMPLOYEE AS E LEFT OUTER JOIN EMPLOYEE AS S ON E.Super_ssn =
S.Ssn);
Explanation:

This query retrieves the last names of employees and their supervisors.
If an employee does not have a supervisor (i.e., Super_ssn is NULL), the employee will still
be
included in the result, with NULL values for the supervisor's name.
Multiway Joins
You can also join multiple tables in a single query, known as a multiway join.

Example of a Multiway Join


SELECT Pnumber, Dnum, Lname, Address, Bdate
FROM ((PROJECT JOIN DEPARTMENT ON Dnum = Dnumber)
JOIN EMPLOYEE ON Mgr_ssn = Ssn)
WHERE Plocation = 'Stafford';
This query joins the PROJECT, DEPARTMENT, and EMPLOYEE tables to retrieve project
details along with the manager's name and address for projects located in 'Stafford'.
Alternative Syntax for Outer Joins
Some SQL implementations, like Oracle, use a different syntax for outer joins, using special
operators.
SELECT E.Lname, S.Lname
FROM EMPLOYEE E, EMPLOYEE S
WHERE E.Super_ssn + = S.Ssn;

In this syntax, the + operator indicates that the join is a left outer join,
meaning all records from the left table (E) will be included, along with matching records
from the right table (S).

Example of NATURAL JOIN with Renaming

You might also like