13

Alright, so what I'm trying to do is perform different COUNT()s on the same table based on different criteria without nested queries (efficiency) or subqueries (so it can be made into a view). Is this possible?

Example: a table has a date column - the query should be able to produce a count of the number of rows prior to & after a constant date.

1 Answer 1

34

You're using MySQL, so you can take advantage of its feature that a boolean expression evaluates to 0 for false and 1 for true. The SUM() of 1's is equal to a COUNT() where the expression is true.

SELECT SUM( date_column < '2009-08-21' ) AS prior_to_date,
       SUM( date_column > '2009-08-21' ) AS after_date
FROM MyTable;

PS: Don't try this on other brands of database that uphold the SQL standard behavior, i.e. a boolean expression yields a boolean, not a 0 or 1 integer.

Sign up to request clarification or add additional context in comments.

4 Comments

Nice - that works great. In other databases that use SQL syntax I suppose having an IF inside the SUM returning 1 or 0 given the condition should work as well.
Yes. But use CASE expressions if you want to be most portable. There's no IF() in standard SQL.
I tried with multiple and seperate. The problem i found if i put seperate select statement with necessary where clause, then mysql uses the index , but when combined, it does not use the index. Checked using explain.
@SenthilMuthiah, it's hard to guess what your conditions are, but I guess you have WHERE <term1> OR <term2>. This spoils the use of an index on either column, because if you have an index for term1, the query must do a table-scan to find all rows for term2, and vice-versa.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.