Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i use IFNULL in Where clause

Tags:

sql

mysql

ifnull

I want to use IFNULL() in such a way that I can select the record containing NULL or, if a value is present, then select the record matchinga particular value.

My query is:

SELECT (@v:=2) AS Row, CL.LeaveTypeId, CL.NumberOfLeave
FROM `CompanyLeave` CL
WHERE(IFNULL(CL.EmploymentType,0)=3);

column EmploymentType can contain either an Integer or NULL.

I want to select the record matching the specified value, or, if none matches, then the record containing NULL.

like image 885
Manish Kumar Avatar asked Jan 09 '23 02:01

Manish Kumar


1 Answers

I am interpreting the question as a prioritization. If a record with 3 exists, choose that. Otherwise, choose the one that is NULL, if it exists.

If so, this might do what you want:

SELECT (@v:=2) AS Row, CL.LeaveTypeId, CL.NumberOfLeave
FROM `CompanyLeave` CL
WHERE CL.EmployementType = 3 or CL.EmployementType IS NULL
ORDER BY (CL.EmployementType = 3) DESC
LIMIT 1;

This will return the row with 3, if present. Otherwise, it will return a row with NULL, if one exists.

like image 184
Gordon Linoff Avatar answered Jan 11 '23 22:01

Gordon Linoff