Thursday, February 12, 2009

Trunc function in SQL

In sql when when we use the BETWEEN function to bring out data for a period of date range, some of the records might not come up in the result

for e.g.

SELECT *
FROM orders
WHERE order_date between to_date ('2003/01/01', 'yyyy/mm/dd')
AND to_date ('2003/12/31', 'yyyy/mm/dd');

If the order_date column in database has a time componenet in it, then the results might not come up for the dates 2003/01/01 and 2003/12/31

To solve this problem, we remove the time componenet from the query using the TRUNC function

SELECT *
FROM orders
WHERE trunc(order_date) between to_date ('2003/01/01', 'yyyy/mm/dd')
AND to_date ('2003/12/31', 'yyyy/mm/dd');

No comments: