Skip to content
Advertisement

How to put Case in Where Statement for Oracle SQL

For the query below, I’m trying to pull a specific date range depending on the current day of the month. If it’s the 20th or less (e.g. “2/7/2020”) then I want the date range for January. Otherwise, I want the date range for February. Is it possible to be done with a case statement? Or there is a better way?

Advertisement

Answer

You can do this by avoiding the case statement and using truncate the date – 20 to the month, e.g.:

If you really had to use a CASE expression (you can’t use a CASE statement in SQL), you would need to do something like:

N.B. if you’re using a function, you don’t need to wrap it in a select .. from dual, you can use it directly in the SQL statement.

I’ve also assumed that you want a dynamic range, e.g. if the day of the month is 20 or less, the range is for the previous month, otherwise the current month.


ETA: You would use the above two queries if there is an index on the start_date column, otherwise you could simply do:

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement