Is it possible to specify condition in Count()?
Yes, you can apply conditions within the COUNT() function by using SUM() with a conditional expression:
Replace condition with your boolean criteria and your_table with the respective table name. condition::int converts the boolean result to an integer (1 for true, 0 for false) ensuring SUM() counts only the true results.
Advanced conditional counting with CASE
In SQL, the COUNT() function can be leveraged within a CASE statement for applying conditions without a WHERE clause. This can keep your dataset intact during aggregation:
This way the COUNT() only includes rows that meet the given condition.
Counting categories with CASE
Categories nested in the same column can be counted separetely using CASE within COUNT():
Fair warning — this might start a category rivalry!
The CLEAN approach with FILTER and COUNTIF
FILTER clause and the COUNTIF function, which are widely used in PostgreSQL and SQLite, dispense conditioned aggregations with aplomb:
Why use a sieve, when you have a FILTER!
In Google BigQuery, COUNTIF plays dexterously with complex conditions:
COUNTIF — The Swiss Army knife for conditional counts.
For more on the FILTER clause's compatibility across various platforms, visit modern-sql.com/feature/filter.
Binary logic Simplified
Binary logic (1 for true, 0 for false) simplifies conditional counts:
This method punches above its weight when dealing with multiple conditions in one execution.
Robust counting with IIF
In SQL Server, the IIF function brings a more concise alternative to the CASE:
Like a friendly conditional sorting hat, IIF excludes NULLs automatically, ensuring accurate counts.
Was this article helpful?