0

One variant of question asked SQL: IF clause within WHERE clause

Let's say :DeptID is a parameter passed to the SQL query and if @DeptID is null, then show all rows, else filter the result by DeptID.

Some pseudo code like

SELECT * 
FROM EMPLOYEE 
   IF :DeptID not = null 
     WHERE DeptID = :DeptID
   ELSE (no filter)

Looking for correct syntax suitable for PostgreSQL & MySQL

The expected result is: when the parameter DeptID passed in is NULL, then show all employees.

And when the parameter DeptID is passed as 10, show employees for the department with an ID of 10.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
user2458922
  • 1,691
  • 1
  • 17
  • 37

1 Answers1

1
SELECT * 
FROM EMPLOYEE 
WHERE :DeptID is null 
   OR :DeptID = DeptID
juergen d
  • 201,996
  • 37
  • 293
  • 362
  • The Expected result is , when the parameter DeptID passed is Null then show all employees. And When the Parameter DeptID is passed as 10, show employees for that deptarment ID which is 10. – user2458922 Dec 05 '19 at 14:39
  • Yes, that is what the code does. Didn't you test it? – juergen d Dec 05 '19 at 14:40