Table of Contents
- The Duplicate Data Headache
- Start with the grain
- Using GROUP BY to Spot Duplicates
- Choose the right columns
- Inspect the groups before the rows
- Why Joins Create Hidden Duplicates
- Test each relationship separately
- Aggregate before joining when possible
- Removing Duplicates with Window Functions
- Delete only after reviewing the rule
- Handling Tricky Duplicate Scenarios
- Treat composite keys as a single decision
- Separate detection from fuzzy matching
- Choosing Your Deduplication Strategy
- Fix the source, not just the symptom
Do not index
Do not index
You run a report that should be straightforward, but the totals look wrong. Customers appear more than once, revenue is inflated, and the row count no longer matches what the source table suggests. You add
DISTINCT, the output looks cleaner, and the query seems fixed. Then someone asks why the numbers changed.That situation is rarely just a nuisance in the data. Duplicate rows can come from repeated inserts, unclear business keys, incomplete joins, or a legitimate one-to-many relationship being treated like a one-to-one relationship. To analyze social media data, or any other activity data, you need to identify what “same” means before you remove anything.
The Duplicate Data Headache
A duplicate problem often announces itself through an innocent-looking report. A query joins customers to orders and then to contact records. The customer count seems plausible, but the order total is suspiciously high. Someone checks the source tables and finds no obvious repeated customer rows. The duplication appeared in the result, not necessarily in the stored data.

That distinction matters. A table can contain exact duplicates, such as two rows with the same supposed unique values. A query can also create repeated logical entities because a join matches several rows on each side. Those are different problems and need different fixes.
Start with the grain
The first question isn't “How do I delete duplicates?” It's what should one row represent? One customer, one order, one event, or one customer-order combination? Until the grain is explicit, a repeated value might be either an error or a valid relationship.
Write down the expected business key before running a cleanup query. For a users table, it might be an email address. For a product history table, it may be a product and effective date combination. For an event table, the identifier may include a user, event type, and timestamp.
A quick diagnostic is to compare the result at each stage of the query. Run the base table, then add one join, then the next. If the row count changes unexpectedly after a particular join, investigate that relationship before touching the underlying records.
The same discipline applies to dashboards and reporting pipelines. A clean-looking chart can still be built on a multiplied result set. Your insights dashboard examples may help organize metrics, but the SQL feeding those metrics still needs a clearly defined grain.
The familiar
GROUP BY ... HAVING COUNT(*) > 1 query is a useful starting point. It isn't a universal repair tool. First determine whether you're looking at stored duplicates, business-rule duplicates, or join-generated fan-out.Using GROUP BY to Spot Duplicates
The standard way to find duplicate rows in SQL is to group records by the columns that should be unique and keep only groups with more than one row. Educational and technical references continue to teach the pattern
GROUP BY ... HAVING COUNT(*) > 1, including the SQL duplicate-value guide from Atlassian.Suppose the
users table should contain one row per email address. The basic query is:SELECT email, COUNT(*) AS row_count FROM users GROUP BY email HAVING COUNT(*) > 1;This returns the duplicated email values and the number of rows associated with each value. It doesn't delete anything, which is exactly why it's a safe first move.
Choose the right columns
Grouping by the wrong column creates misleading results. A username may look unique until accounts are migrated between systems. An email address may be reused under a business rule that permits multiple profiles. A numeric ID may be unique by design and therefore useless for finding repeated entities.
For a composite business key, include every column that defines sameness:
SELECT username, email, COUNT(*) AS row_count FROM users GROUP BY username, email HAVING COUNT(*) > 1;This asks a narrower question than grouping by
email alone. It finds repeated username and email combinations, not every repeated email. The correct query depends on the table's intended uniqueness.Inspect the groups before the rows
The grouped result tells you which key combinations repeat, but not always which full records are involved. Use the output to inspect the source rows, compare timestamps and status fields, and identify whether one record should survive.
A useful variation adds ordering:
SELECT email, COUNT(*) AS row_count FROM users GROUP BY email HAVING COUNT(*) > 1 ORDER BY row_count DESC;COUNT(*) counts rows, including rows where other selected columns contain NULL. That makes it useful for measuring repeated groups, but it doesn't resolve whether NULL represents an unknown value, a missing identifier, or a valid shared state.Use
GROUP BY when you need a transparent inventory of repeated key combinations. It works well for staging checks, data-quality audits, and targeted investigations. It becomes insufficient when you need to keep a particular row, account for casing or nullability, or diagnose duplication that only appears after joins.Why Joins Create Hidden Duplicates
A join can multiply rows even when every source table looks reasonable by itself. Suppose a customer has several orders and several contact records. Joining both child tables directly to the customer creates a result containing each matching order combined with each matching contact. The query hasn't found duplicate customers. It has produced multiple customer representations through a many-to-many fan-out.

This is why duplicate detection in join-heavy workloads is often a fan-out diagnosis. If both sides contain multiple rows for the join key, the database returns every matching combination. Aggregates then count those combinations, not the business entities you had in mind.
Test each relationship separately
Start by checking the join key in each table:
SELECT customer_id, COUNT(*) AS row_count FROM orders GROUP BY customer_id HAVING COUNT(*) > 1;Run the equivalent check against contacts. Multiple rows in either table may be legitimate. The important question is whether the final query expects one-to-one, one-to-many, or many-to-many behavior.
Then add joins one at a time. Compare the number of rows before and after each join, and inspect the keys that expand. A join with an incomplete composite condition is a frequent culprit. For example, joining on
customer_id while omitting region_id can match records that belong to different regional contexts.The join type doesn't solve the underlying issue. A
LEFT JOIN preserves unmatched rows, but it can still multiply matched rows. A missing ON condition can create an accidental Cartesian product. A non-unique natural key can match unrelated records that happen to share the same visible value.Aggregate before joining when possible
If the report needs order totals per customer, aggregate orders to the customer grain before joining them to another child table. That keeps the order calculation at the level where it makes sense. If the query only needs to confirm that a related record exists, use
EXISTS instead of joining the full child table. EXISTS usually avoids producing unnecessary duplicate rows because it tests presence rather than returning every match.This pattern is especially important in analytics pipelines. A social reporting query that joins posts, reactions, and audience records can inflate engagement totals if each table has multiple rows per profile. The social media analytics API may provide useful data inputs, but SQL still has to preserve the intended grain at every transformation step.
Removing Duplicates with Window Functions
Finding repeated keys is only half the job. Cleanup requires a retention rule. Should you keep the newest record, the oldest record, the row with a completed status, or the record with the most reliable source? A window function lets you express that decision instead of deleting arbitrary rows.

Use
ROW_NUMBER() to rank rows inside each duplicate group:SELECT id, email, created_at, ROW_NUMBER() OVER (PARTITION BY email ORDER BY created_at DESC, id DESC) AS rn FROM users;PARTITION BY email defines the duplicate group. The ORDER BY clause defines which record ranks first. Adding a stable tie-breaker such as id makes the choice deterministic when timestamps match.ROW_NUMBER() doesn't remove anything by itself. It only labels rows. To identify the rows that would be removed, place the ranking query in a common table expression:WITH ranked AS ( SELECT id, email, ROW_NUMBER() OVER (PARTITION BY email ORDER BY created_at DESC, id DESC) AS rn FROM users ) SELECT * FROM ranked WHERE rn > 1;The records with
rn = 1 are the candidates to retain. The records with rn > 1 are candidates for review or deletion.Delete only after reviewing the rule
A database-specific delete syntax may look like this:
WITH ranked AS ( SELECT id, ROW_NUMBER() OVER (PARTITION BY email ORDER BY created_at DESC, id DESC) AS rn FROM users ) DELETE FROM users WHERE id IN (SELECT id FROM ranked WHERE rn > 1);Test the inner query first. Save the candidate IDs, verify the retention rule, and run the deletion in a transaction where your database supports it. You should also consider foreign keys, audit requirements, and whether downstream systems still reference the rows.
The Metabase explanation of duplicated SQL data emphasizes the same core discipline: define the result grain, group by the exact business key, and don't treat
DISTINCT as a repair. DISTINCT can conceal a faulty join or modeling mistake while forcing the database to perform duplicate elimination over the result.A grouped query may be safer when you only need one aggregate-safe value per group. A window function is better when the surviving row matters. Neither approach should be applied until the ranking or grouping columns reflect the actual business definition of sameness.
Here is a practical walkthrough of the ranking technique:
Handling Tricky Duplicate Scenarios
Exact equality is the easiest duplicate definition. Production data usually gives you something messier: different capitalization, whitespace, missing values, regional identifiers, or several valid historical versions of the same entity.
Consider email addresses such as
john@email.com and John@Email.com. Whether they represent the same account depends on the application's identity rules and the database collation. If the business treats them as equivalent, normalize the comparison deliberately rather than hoping the database makes the intended choice.SELECT LOWER(TRIM(email)) AS normalized_email, COUNT(*) AS row_count FROM users GROUP BY LOWER(TRIM(email)) HAVING COUNT(*) > 1;That query detects a business-rule duplicate based on a normalized expression. It doesn't mean you should overwrite the stored values immediately. Preserve the original data, inspect the affected rows, and decide whether normalization belongs in ingestion, a generated column, a canonical identity table, or a one-time cleanup.
Treat composite keys as a single decision
A customer may be represented by a regional ID in one source and a global ID in another. Neither identifier alone necessarily defines uniqueness. The matching rule might require a combination of source system, regional ID, and customer type.
The same issue appears with history tables. “Latest row per entity” isn't an exact duplicate problem at all. It is a selection problem. Use
ROW_NUMBER() with an explicit ordering column, then retain the ranked row that matches the rule.ROW_NUMBER() also exposes a difficult question about NULL. SQL's comparison behavior around NULL doesn't mean “equal to every other missing value.” If a missing email should not identify an account, exclude or separately classify those rows. If missing values should form one review group, normalize them intentionally in the grouping expression and document the choice.Separate detection from fuzzy matching
Fuzzy identifiers require more caution than
LOWER() or TRIM(). Similar names can belong to different people, and a shared phone number can represent a household or organization. Don't turn approximate similarity into an automatic delete rule without a review path.Real-time Twitter analytics can involve usernames, profile IDs, and changing display names. A display name is a poor identity key if it can change or be shared. Prefer stable identifiers where the source provides them, and use human review for ambiguous matches.
The Oracle SQL guidance on finding and deleting duplicate rows reflects this broader shift from simple exact-match detection toward controlled retention workflows. The safest process is to define the business key, normalize only where the rule requires it, rank candidates deterministically, and quarantine uncertain matches instead of deleting them.
Choosing Your Deduplication Strategy
The right method depends on where the repetition originates and what the query needs to return. A grouped query is excellent for discovery. A window function is stronger when you must choose a specific surviving row. Pre-aggregation is often the correct answer when a join is multiplying valid child records.

Use this decision guide:
Situation | Preferred approach | Main trade-off |
You need to discover repeated key combinations | GROUP BY with HAVING COUNT(*) > 1 | Shows groups, not automatically the row to keep |
You need a specific record per group | ROW_NUMBER() with a deterministic ORDER BY | Requires a clear retention rule |
You need totals at a parent grain | Pre-aggregate before joining | Adds a transformation step, but protects aggregates |
You only need to test whether a match exists | EXISTS | Doesn't return the matching child rows |
You need a quick projection with exact repeated output values | DISTINCT | Can hide faulty joins and may add duplicate-elimination work |
Fix the source, not just the symptom
A cleanup query is temporary if the same duplicate can be inserted again. Enforce the intended uniqueness with a suitable database constraint or ingestion check when the business rule is stable. If the rule is conditional, such as one active record per entity, use the database features and application logic appropriate for your SQL system.
Performance also matters. Grouping, sorting, and window functions can require substantial work on large result sets, especially after an accidental fan-out. Reduce the data early, normalize join keys consistently, and pre-aggregate child records before joining them to other one-to-many tables.
Don't add
DISTINCT merely because the output has too many rows. First identify the join or key that created them. The cleanest deduplication strategy is the one that prevents invalid multiplicity from entering the result in the first place.For broader reporting workflows, social media data analysis follows the same principle: define the entity and event grain, validate each transformation, and distinguish repeated activity from repeated entities. That discipline keeps a legitimate stream of events from being mistaken for corrupt source data.
Start with a read-only duplicate report, inspect the keys, and test joins one at a time. Then choose
GROUP BY, ROW_NUMBER(), EXISTS, or pre-aggregation based on the actual failure mode, not on whichever query happens to make the output look tidy.SuperX helps X users, creators, and marketers analyze profile activity, tweet performance, audience signals, and content trends without guessing from raw timelines. If duplicate-looking activity is making your social reporting harder to trust, visit SuperX to explore a clearer way to inspect and understand your data.
