Junior
Is it possible to rewrite queries with EXISTS/NOT EXISTS without using these operators? What types of JOINs do you know?
sobes.tech AI
Answer from AI
Yes, queries with EXISTS/NOT EXISTS can be rewritten without these operators by using JOINs and aggregate functions.
For example, a query with EXISTS:
SELECT * FROM A WHERE EXISTS (SELECT 1 FROM B WHERE B.a_id = A.id);
Can be rewritten using INNER JOIN:
SELECT DISTINCT A.* FROM A INNER JOIN B ON B.a_id = A.id;
For NOT EXISTS, you can use LEFT JOIN with a NULL check:
SELECT A.* FROM A LEFT JOIN B ON B.a_id = A.id WHERE B.a_id IS NULL;
Main types of JOINs:
- INNER JOIN — returns rows that match in both tables.
- LEFT JOIN (LEFT OUTER JOIN) — returns all rows from the left table and matching rows from the right, or NULL if there are no matches.
- RIGHT JOIN (RIGHT OUTER JOIN) — the opposite, all from the right and matching from the left.
- FULL JOIN (FULL OUTER JOIN) — combines LEFT and RIGHT JOIN, returning all rows from both tables.
Understanding these JOINs helps in rewriting and optimizing queries.