Oracle SQL Where Clause against a date column
-
28-09-2019 - |
Question
I have a DATE column with a date in it but I need to query it to find records less than 30 days old.
START_DATE
----------
01-AUG-2010
09-AUG-2010
22-AUG-2010
09-SEP-2010
Query:
SELECT START_DATE
WHERE START_DATE < 30;
I know it is simple Query in ORACLE SQL but i am doing something wrong.
Solution
WHERE START_DATE > SYSDATE - 1
or perhaps
WHERE TRIM(STARTDATE) > TRIM(SYSDATE) - 1
OTHER TIPS
Use:
SELECT t.start_date
FROM YOUR_TABLE t
WHERE t.start_date > SYSDATE - 30
SYSDATE
is Oracle's syntax to get the current date and time- In Oracle, you can do date arithmetic in the context of days, so SYSDATE - 30 means "current date, subtract thirty days" to get a date that is thirty days in the past
If you want to evaluate the date based on thirty days as of midnight, use the TRUNC function:
SELECT t.start_date
FROM YOUR_TABLE t
WHERE t.start_date > TRUNC(SYSDATE) - 30
Don't run TRUNC on the column - that will render an index on the column useless, ensuring a table scan.
SELECT t.start_date
FROM YOUR_TABLE t
WHERE t.start_date > SYSDATE - INTERVAL '30' DAY;
INTERVAL
is more portable than assuming that you can add or subtract days, although I've noticed some slight differences in the INTERVAL
syntax between Oracle and PostgreSQL.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow