Data Engineering

SQL UNION vs UNION ALL: When Removing Duplicates Changes the Meaning

SoftwareJobs.io editorial29 November 20262 min read

Combining two query results does not always mean removing repeated rows. UNION and UNION ALL make different choices. Before selecting one, decide whether identical result rows represent duplicates or separate real events.

Start with two short results

Imagine result A contains Ada and Ben. Result B contains Ben and Cara. UNION returns Ada, Ben and Cara: three distinct rows. UNION ALL keeps all four rows, including Ben twice. PostgreSQL documents that UNION removes duplicate result rows unless ALL is used. The results need the same number of columns with compatible types.

Ask what a row means

If each row represents a distinct person, removing the repeated name might appear useful, although a name alone is usually a weak identifier. If each row represents an activity, two entries for Ben could be two real activities. Removing one would lose information.

SELECT person FROM morning_activity
UNION ALL
SELECT person FROM afternoon_activity;

This sketch keeps the repeated person values. It does not guarantee row order. Add an explicit ordering requirement if the report needs a particular display sequence.

Try a useful exercise

  • Predict the output count before running each operator.
  • Add an activity reference column and compare again.
  • Explain whether two identical displayed rows are necessarily the same event.

Avoid a hidden cleanup rule

Do not use UNION simply to make a count smaller. Agree the identity of a record and how duplicates should be defined. In a Malta data interview, explaining the intended meaning is more valuable than choosing an operator without checking the business question.

Sources and further reading

Explore current technology jobs in Malta →

PUT YOUR IDEAS INTO ACTION

What’s your next move?

Explore software, cloud and data roles that fit your skills and ambitions.

Explore opportunities
KEEP EXPLORING

More ideas for your next chapter