4

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.

Paolo Stefan
  • 10,112
  • 5
  • 45
  • 64
Manish Kumar
  • 595
  • 2
  • 5
  • 20

3 Answers3

5

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.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
4

The expression IFNULL(CL.EmploymentType, 3) basically means: if CL.EmploymentType IS NULL then use 3 instead. The original value of CL.EmploymentType is used if it is not NULL.

If I understand correctly your question, you need to select the rows having NULL or 3 in the column CL.EmploymentType.
The query is:

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

Update:

If only one row must be returned (the one having 3 being preferred over those having NULL) then the rows must be sorted using a criteria that puts the NOT NULL value in front and a LIMIT 1 clause must be added.

MySQL documentation about NULL says:

When doing an ORDER BY, NULL values are presented first if you do ORDER BY ... ASC and last if you do ORDER BY ... DESC.

The updated query is:

SELECT (@v:=2) AS Row, CL.LeaveTypeId, CL.NumberOfLeave
FROM `CompanyLeave` CL
WHERE IFNULL(CL.EmploymentType, 3) = 3;
ORDER BY CL.EmploymentType DESC
LIMIT 1
axiac
  • 68,258
  • 9
  • 99
  • 134
1

You can use IF statement instead of IFNULL()

IF(condition, expres1, expres2) 

It means that if condition is satisfied then return expres1 else expres2

SELECT (@v:=2) AS Row, CL.LeaveTypeId, CL.NumberOfLeave
FROM `CompanyLeave` CL
WHERE IF(CL.EmploymentType IS NULL, 0, CL.EmploymentType) = 3;
Saharsh Shah
  • 28,687
  • 8
  • 48
  • 83