Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using an alias in a where clause in MySql

I’ve this table structure:

HDN_Client HDN_Type HDN_EndDate
Client #1 Hosting 2022-02-01
Client #2 Hosting 2022-03-01
Client #3 Hosting 2022-07-30

I want to display the list of datas when the HDN_EndDate has 60 or less days between the today date and the HDN_EndDate date.

My query is the following one:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SELECT *, 
DATEDIFF(HDN_EndDate, '2022-01-17') 
    AS HDN_DateDiff 
FROM ___table 
WHERE HDN_Type='Hosting' 
   AND HDN_DateDiff<60 
ORDER BY HDN_DateDiff ASC

But it says that the HDN_DateDiff can’t be used in the WHERE clause.

How can I make it work?

>Solution :

You can’t refer to an alias in a WHERE clause defined in the same SELECT. MySQL overloads its HAVING clause to allow it to use aliases. The following version should work:

SELECT *, DATEDIFF(HDN_EndDate, '2022-01-17') AS HDN_DateDiff
FROM ___table
WHERE HDN_Type = 'Hosting'
HAVING HDN_DateDiff < 60
ORDER BY HDN_DateDiff;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading