I’m wondering if the two queries below are equivalent to each other:
SELECT
messages1.id, messages1.channel
FROM
(SELECT *
FROM messages
WHERE channel IN ('U560')) messages1
LEFT JOIN
read_messages ON messages1.id = read_messages.message_id
WHERE
read_messages.id IS NULL;
SELECT
"messages"."id", "messages"."channel"
FROM
"messages"
LEFT OUTER JOIN
"read_messages" ON ("messages"."id" = "read_messages"."message_id")
WHERE
("messages"."channel" IN ('U560')
AND "read_messages"."id" IS NULL)
How can I test that?
2
Answers
You can check the execution plan using the
EXPLAIN
keyword.https://www.postgresql.org/docs/current/sql-explain.html
If the execution plans are the same, the queries are the same.
You can take the suggestion by @MikeOrganek a step further. UNION those queries. See documentation for Combining Queries. If the result is empty set (no rows) then your original queries produce the same result and are therefore equivalent. If any rows are returned use the individual except queries to determine differences. HINT: Make [query 1] and [query 2] CTEs.