Keywords with Nested Queries

tags: #sql/complex_queries

EXISTS Keyword

EXISTS is a boolean operator that returns either True or False.

SELECT column1, column2, ...
FROM table_name
WHERE EXISTS (subquery); // checking if any rows exists in subquery

Example:

SELECT E.Emp_Name, E.Dept_No
FROM Employee AS E
WHERE EXISTS (SELECT P.Pno
              FROM Project AS P
              WHERE P.Emp_SSN = E.Emp_SSN);
Use Case

Does not compare values directly. Therefore, is only suitable for scenarios where you want to check for the existence of any row that satisfies certain conditions.

This can be used with

IN Clause

The IN clause retrieves all records which match with the given set of values.

SELECT column1, column2, ...
	FROM table_name
	WHERE (condition) in (
		--subqeury
		SELECT cols 
			from table_name
			.... 
			);
What is the equivalent logic for multiple AND conditions?

Consider the following scenario where you want to check that values of an instance of an entity in more than one column (e.g., column1 and column2) from the main query exist in a subquery, you can use the following SQL approaches:

SELECT column1, column2
FROM main_table
WHERE column1 IN (SELECT colx FROM subquery_table)
  AND column2 IN (SELECT coly FROM subquery_table);

This ensures that both conditions are satisfied: the value in column1 must exist in the result of the subquery for colx, and the value in column2 must exist in the result of the subquery for coly.

Use Case

For when you want to compare a column against a list of values. Only use EXISTS when you want to check for the existence of rows that meet specific conditions in a subquery.

NOT EXISTS Negation

We can use NOT EXISTS is to return all the rows from the main query where a correlated subquery has no matching rows (also used to express the "for all" condition).

Example:

Want to find all employees who have not been assigned to any project.

SELECT E.name
FROM EMPLOYEE AS E
WHERE NOT EXISTS (
	SELECT E.name
	FROM WORKS_ON AS W
	WHERE W.ESSN = E.ESSN
)

UNIQUE Keyword

The UNIQUE keyword is not used in the same way as EXISTS and IN in SQL. Instead, it is typically associated with constraints and indexes to enforce the uniqueness of values in a column or combination of columns.

Example:

SELECT Dname
FROM DEPARTMENT D
WHERE UNIQUE(SELECT Salary -- retrieving UNIQUE result set of salary from E
            FROM EMPLOYEE E
            WHERE E.Dno = D.Dnumber)
Use Case

We can use the UNIQUE keyword with nested queries to ensure that the result set contains only unique values; used to specify that the result set should contain only unique values based on the condition/criteria.

Powered by Forestry.md