Data Engineering

COUNT(*) vs COUNT(column): Why Missing Values Change a SQL Result

SoftwareJobs.io editorial24 November 20262 min read

Two count queries can give different results on the same table without either query being broken. The difference is what you asked them to count. This is a useful detail for data analysts and engineers in Malta.

Start with three records

Imagine three support tickets. Ticket 1 has an owner called Ada, ticket 2 has a null owner and ticket 3 has an owner called Ben. In this teaching example, null means that the owner value is missing.

SELECT COUNT(*) AS tickets,
       COUNT(owner) AS tickets_with_owner
FROM tickets;

The expected result is 3 tickets and 2 tickets_with_owner. COUNT(*) counts rows. COUNT(owner) counts rows where owner is not null. PostgreSQL documents this difference in its aggregate function reference. An empty string is a value, so it is not treated as null by this rule.

Connect the query to the question

If the report asks “How many tickets exist?”, counting owners answers a different question. If it asks “How many tickets have an owner recorded?”, the second count may be useful. Agree what a missing or blank field means in your source before choosing the measure.

Try two changes

  • Set the second ticket’s owner to an empty string. Predict both counts.
  • Remove one ticket completely. Predict the row count again.

Keep the dataset tiny so that you can check the answer by hand. When reviewing a real report, write the measure definition alongside the SQL. A correct query still needs to answer the question the reader thinks it answers.

Sources and further reading

Browse 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