sql correlated subqueries - advanced sql _ bipp analytics
sql correlated subqueries - advanced sql _ bipp analytics
There are some data questions where the SQL to solve the question must include a
correlated subquery. This is particularly true in queries where you are looking for what
might be called negatives or negative data questions.
Table employee
Table payment_history
Here is an SQL query to answer a negative data question: List the employees who
have never received a bonus.
Copy
The result:
first_name last_name
first_name last_name
Marcos Bisset
Carlos Casco
The negative part of the data question is often solved in the correlated subquery by
using a NOT EXISTS operator in the WHERE clause. EXISTS is an operator always
followed by a subquery. If the subquery returns at least one record, then the EXISTS
evaluates to TRUE. If the subquery returns empty, then the EXISTS evaluates to
FALSE. Note we use NOT EXISTS, which is the opposite to EXISTS.
Here is an SQL query to answer a positive data question: List the employees who have
received a bonus.
Copy
The query uses an implicit JOIN by putting both tables in the FROM clause. The implicit
JOIN is equivalent to the query:
Copy
first_name last_name
Kate Perez
It is a best practice to solve data question with JOIN instead of a correlated subquery
whenever possible. You should only use correlated subqueries for negative data
questions or other data questions where a correlated subquery is the only way to
answer it.
Copy
SELECT first_name, last_name
FROM employee e1, payment_history ph
WHERE e1.employee_id = ph.employee_id
AND amount_paid > = (
SELECT avg(amount_pa
id)
FROM payment_histo
ty ph2
WHERE ph2.employee_
id = e1.employee_id
AND ph2.payme
nt_date < ‘2018-03-01’
)
AND month(ph.payment_date) = 3
AND year(ph.payment_date) = 2018
AND ph.payment_type = ‘salary’
You can identify the reference to the outer subquery table marked in red, so you know
this is a correlated subquery. The subquery executes once per record instead of just a
single time like a simple query.
Closing Words
In this lesson you learned how to identify and use correlated subqueries, a special kind
of subquery, which is used under specific circumstances. The next lesson covers SQL
Window Functions: very powerful functions that add new possibilities to the SQL
language. Keep going, learn SQL and increase your skills!
account!
Sign up for free
Business Intelligence bipp Data Modeling Layer Blog Documentation About Request Demo
Embedded Analytics Visual SQL Data Explorer Reports bipp Tutorial Meet The Team Support
Professional Services Data Visualization Release Notes Why bipp? Careers Contact Us