Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL optimization: Four statements into one

Tags:

sql

mysql

I have a table with some columns, one holds a timestamp that I use to run currently four single selects to compute a SELECT count() and return information like "n-rows older than 1 week", "n-rows older than 2 weeks", ...

How to transform the four queries into one SQL-Statement that is hopefully running faster?

The statements look like this:

SELECT count(foo_pk) AS oneweek FROM foo WHERE foo_timstamp < DATE_SUB(now(), INTERVAL 1 week)
like image 203
initall Avatar asked Jun 14 '26 07:06

initall


2 Answers

I'm not a MySql guy, but in SQL Server I would use the CASE statement like so:

SELECT
    SUM(CASE WHEN foo_timstamp < DATE_SUB(now(), INTERVAL 1 week) THEN 1 ELSE 0 END) as oneweek,
    SUM(CASE WHEN foo_timstamp < DATE_SUB(now(), INTERVAL 2 week) THEN 1 ELSE 0 END) as twoweek,
    SUM(CASE WHEN foo_timstamp < DATE_SUB(now(), INTERVAL 3 week) THEN 1 ELSE 0 END) as threeweek,
    SUM(CASE WHEN foo_timstamp < DATE_SUB(now(), INTERVAL 4 week) THEN 1 ELSE 0 END) as fourweek
FROM foo
WHERE 
    foo_timstamp < DATE_SUB(now(), INTERVAL 1 week)

It seems that this statement is available in MySql as well, so while my syntax might be a bit off I think something like the SQL above should work.

like image 117
rsbarro Avatar answered Jun 16 '26 10:06

rsbarro


SELECT 
      COUNT(1) AS olderthanoneweek, 
      COUNT(CASE WHEN foo_timstamp < DATE_SUB(now(), INTERVAL 2 week) THEN 1 END) AS olderthantwoweek,
      COUNT(CASE WHEN foo_timstamp < DATE_SUB(now(), INTERVAL 3 week) THEN 1 END) AS olderthanthreeweek, 
      COUNT(CASE WHEN foo_timstamp < DATE_SUB(now(), INTERVAL 4 week) THEN 1 END) AS olderthanfourweek 
FROM foo 
WHERE foo_timstamp < DATE_SUB(now(), INTERVAL 1 week)
like image 34
Martin Smith Avatar answered Jun 16 '26 10:06

Martin Smith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!