views:

74

answers:

3

I want to delete all data from a table that has a date prior to 01/01/2006

I am trying this:

delete from table_a 
where to_char(last_update_date,'MM/DD/YYYY') < to_char('01/01/2006', 'MM/DD/YYYY')

But this is not working.

What is the best way to compare date's in sql?

+1  A: 

So close, so close... it's like you can almost feel that they were right on the brink of a major breakthrough...

Here, try this:

delete from table_a where last_update_date < '01/01/2006'
Vilx-
That's risky, because date formats are regional.
OMG Ponies
I don't think you can parse this in a wrong way. That is, of course, assuming the parser is forgiving and doesn't expect you to provide the date in a strict format. I don't know Oracle well enough to say.
Vilx-
OMG Ponies
That can be misunderstood by a human, never mind a parser. And that's before you start worrying about an `NLS_DATE_FORMAT` that includes the time, or the common (I think) post-Y2K format of `DD-Mon-RR`. While you can leave it like this if you know your database format is `DD/MM/YYYY` (or, I suppose, `MM/DD/YYYY`), it may still break if it's used by a client or session with a different format mask.
Alex Poole
`date '2006-01-01'` -- it's a builtin, and it's unambiguous. The fact that it sorts asciibetically is simply a bonus.
Adam Musch
Sorry, I think I didn't make myself clear enough. Yes, in the general case you cannot give a date without a format string to accompany it. However, **this specific date** can only be parsed as January 1, 2006. And it doesn't mater which one of the 01's gets parsed as month, and which one as day.
Vilx-
+12  A: 

Use the TO_DATE function to convert a string into an Oracle DATE (includes time):

DELETE FROM TABLE_A
 WHERE last_update_date < TO_DATE('01/01/2006', 'MM/DD/YYYY')

...to delete records with a last_update_date value of December 31, 2005 at 11:59:59.9999 or earlier.

OMG Ponies
wana accept this answer but have to wait X minutes. lame
learn_plsql
@learn_plsql: not lame, it stops people from blindly accepting the first response that happens to work - which doesn't always mean it's the best answer. (In this case, of course, OMG Ponies has given an excellent answer)
Jeffrey Kemp
A: 

IF you use T-SQL, you can make use of DATEDIFF (datepart ,startdate ,enddate ). as follows you would have make use of it!

delete from table_a where WHERE DateDiff(dd, last_update_date, '01/01/2006') > 0

nevertheless, if you think about Oracle. you can make use of To_Date(date||string,format)

***delete from table_a where WHERE To_date(last_update_date,'dd/mm/yyyy') > to_date('01/01/2006','dd/mm/yyyy')***
Vanji
Yeah, Oracle's date functions are lacking when compared to competitors.
OMG Ponies
You could do that if the `last_update_date` field was varchar, but the OP's said it's a date. (And I think you meant `<`).
Alex Poole
Yep Alex, Your point is correct!
Vanji