Write a SQL query to identify users who have logged in more than once in the last 24 hours.
Instruction: In PostgreSQL logins(user_id integer NOT NULL, login_time timestamptz NOT NULL), find users with more than one login in the 24 elapsed hours ending at statement start. Use an inclusive lower bound and exclusive upper bound, and explain event duplication and daylight-saving considerations.
Updated
Official answer
For PostgreSQL logins(user_id integer NOT NULL, login_time timestamptz NOT NULL), use a half-open interval ending at this statement's start:
WITH bounds AS (SELECT statement_timestamp() AS as_of)
SELECT l.user_id, COUNT(*) AS login_count
FROM logins AS l CROSS JOIN bounds AS b
WHERE l.login_time >= b.as_of - INTERVAL '24 hours'
AND l.login_time < b.as_of
GROUP BY l.user_id
HAVING COUNT(*) > 1
ORDER BY l.user_id;
The lower boundary is included and the upper boundary excluded, so future events do not qualify. INTERVAL '24 hours' means elapsed hours; a calendar day can have a different duration across a daylight-saving transition. statement_timestamp is anchored to statement start, while CURRENT_TIMESTAMP is anchored to transaction start in PostgreSQL.
COUNT(*) counts login records, not necessarily distinct login events. If ingestion can duplicate events, establish an event ID and deduplicate under that rule before counting. For reproducible reports, bind an explicit as-of timestamp and use the same bounds. This is a rolling 24-hour measure, not yesterday's local calendar day.