A data quality alert fires saying your trips table has more rows than unique trip_id values — commuters have reported the app double-logging trips whenever a spotty GPS signal triggers a sync retry. How do you quickly find which trip_ids are duplicated and how many times each appears?
Click or press Enter to reveal the answerGroup by trip_id, count the rows in each group, and filter with HAVING count(*) > 1 — GROUP BY collapses rows into one per trip_id, and HAVING filters on that aggregated count, which a WHERE clause can't do since WHERE runs before aggregation happens.
The query
select
trip_id,
count(*) as row_count
from trips
group by trip_id
having count(*) > 1
order by row_count desc
Why HAVING and not WHERE
SQL evaluates clauses roughly in this order: FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY. WHERE filters individual rows before grouping happens, so at that point count(*) doesn’t exist yet — there’s nothing to filter on. HAVING filters after aggregation, once count(*) per group is known, which is exactly what you need to say “keep only the groups with more than one row.”
-- This does NOT work: count(*) isn't available at the WHERE stage
select trip_id
from trips
where count(*) > 1 -- error
group by trip_id
A quick sanity check without the full breakdown
If you just want a yes/no answer to “are there any duplicates at all” before digging into which ones:
select count(*) as total_rows, count(distinct trip_id) as unique_ids
from trips
If total_rows doesn’t equal unique_ids, duplicates exist — then run the GROUP BY ... HAVING query above to identify exactly which trip_ids are affected and by how much, which is the first step toward root-causing the upstream issue (in this case, the mobile app resending a trip after a failed GPS sync instead of recognizing it had already uploaded).