Counting null and non-null values in a single query
Here's the quick silver bullet to count NULL and non-NULL values in an SQL column:
This yields two counts: COUNT(column_name)
turns a blind eye to NULLs, while COUNT(*)
considers them. Subtraction gives us the ghostly count of NULLs.
Cross-platform variations
Though our fast answer is a tireless worker across platforms, remember that RDBMS-specific syntax can offer unique flavors:
- Oracle supports
MINUS
operator, which subtracts non null rows from all rows:
- For SQL Server, swap
MINUS
withEXCEPT
. However, our initial fast answer performs admirably across RDBMS including MySQL and PostgreSQL.
The SUM and CASE dynamic duo
Try a tag team of SUM
and CASE
for more complex conditions or simply for sheer querying joy:
This dynamic duo prevails where multiple nullity checks converge.
Tackling scalability and performance
Awareness of performance is like the spice in a well-cooked dish, especially with dishes of large data:
- Full table scans are SQL's equivalent of window shopping - time consuming and expensive. Peek into the execution plan to ensure you're leveraging indexes.
- Cleverly named aliases improve readability, like an unexpected plot twist that keeps audience glued to a thriller.
Whether you're stirring a small salad or cooking up a divine feast, stick to the recipe of efficient SQL tailored to your specific database schema and hardware capacities.
Employing UNION ALL for distinct counts
A fan of clear distinction? Use a UNION ALL
query for a visual breakout of counts for different conditions:
This approach untangles the counts and eases the task of report generation or data exporting.
Was this article helpful?