-
Notifications
You must be signed in to change notification settings - Fork 6
Recursive SQL
-_- edited this page Aug 20, 2025
·
3 revisions
-- Look at all messages sent to one person after a certain day.
-- We want to find all the messages, but not the very first one.
SELECT DISTINCT sn.uuid
FROM public.soon sn
WHERE sn.uuid = 'cabd80ab-8e0d-4883-9fe0-9670ffe97d2c'
AND sn.date_created > '1996-06-17'
-- Now take away the very first message.
-- This part finds the first one and removes it from the list.
EXCEPT
(
SELECT sn.uuid
FROM public.soon sn
WHERE sn.uuid = 'cabd80ab-8e0d-4883-9fe0-9670ffe97d2c'
AND sn.date_created > '1996-06-17'
-- This checks if there are no messages before this one.
-- If there aren’t, then this is the first message.
AND NOT EXISTS (
SELECT 1
FROM public.soon sub
WHERE sub.uuid = sn.uuid
AND sub.date_created > '1996-06-17'
AND sub.date_created < sn.date_created
)
);
https://youtu.be/RtlV1lowdzE?feature=shared
http://www.codedependant.net/2017/04/30/build-json-api-responses-postregres-with-cte/
https://dba.stackexchange.com/questions/230516/slow-left-join-lateral-in-subquery
https://wiki.postgresql.org/images/4/4f/SNisenbaum_Yello_Becoming_A_SQL_Guru.pdf
https://stackoverflow.com/questions/61160156/get-paginated-rows-and-total-count-in-single-query
https://jaxenter.com/10-sql-tricks-that-you-didnt-think-were-possible-125934.html