J. Doe
J. Doe

Reputation: 1

MySQL date calculation in WHERE clause

I want to get a statistic of registered users per month for the past year, so I constructed this query

SELECT MONTH(created_at) as m, COUNT(*) as c
FROM users
WHERE created_at >= DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 12 MONTH), '%Y-%m')
GROUP BY m

Now what I understand MySQL will do is

If supposedly what I said above is correct, I am concerned about point 2. In a typical program the value in the if statement will be calculated every time if not put in a variable.

Do I need to put the statement DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 12 MONTH), '%Y-%m') in a variable and reference that in my WHERE clause to keep it from recalculating it on each row, and how?

Upvotes: 0

Views: 246

Answers (1)

Muhammad Usman
Muhammad Usman

Reputation: 10148

While executing your query the very first part that will be considered is the where clause. After that group by and then It will select all those resulting rows.

You don'y need to add any extra variables you just talked about at the end

Upvotes: 1

Related Questions