There are many ways to do this. Use an EXISTS
semi-join followed by DISTINCT
or GROUP BY
, should be among the fastest.
Postgres syntax:
SELECT DISTINCT customer_name
FROM order_dtls o
WHERE EXISTS (
SELEST 1 FROM order_dtls
WHERE customer_name = o.customer_name
AND order_date = o.order_date + 1 -- simple syntax for data type "date" in Postgres!
);
If the table is big, be sure to have an index on (customer_name, order_date)
to make it fast - index items in this order.
To clarify, since Oto happened to post almost the same solution a bit faster:
DISTINCT
is an SQL construct, a syntax element, not a function. Do not use parentheses like DISTINCT (customer_name)
. Would be short for DISTINCT ROW(customer_name)
- a row constructor unrelated to DISTINCT
- and just noise for the simple case with a single expression, because Postgres removes the pointless row wrapper for a single element automatically. But if you wrap more than one expression like that, you get an actual row type - an anonymous record actually, since no row type is given. Most certainly not what you want.
Also, don't confuse DISTINCT
with DISTINCT ON (expr, ...)
. See: