tags:

views:

197

answers:

2

I have a table MRU, that has 3 columns.

(VALUE varchar(255); TYPE varchar(20); DT_ADD datetime)

This is a table simply storing an entry and recording the date time it was recorded. What I wanted to do is: delete the oldest entry whenever I add a new entry that exceeds a certain number.

here is my query:

delete from MRU 
where type = 'FILENAME' 
ORDER BY DT_ADD limit 1;

The error message is: SQL Error: near "ORDER": syntax error ...

The query returns an error.

Thanks

+3  A: 

First of all, it always helps posting as much information as you have. In this particular instance, "an error" is unhelpful and it would've taken you perhaps 2 seconds to copy and paste the actual error message given, which would give us valuable clues when helping you.

Instead, I went to the documentation for the DELETE statement of SQLite, found here, and notice that lo and behold, DELETE does not have ORDER BY, unless it is compiled in a specific manner. I assume your version isn't, although without the error message it is hard to tell.

What you can try instead is this:

delete from MRU where DT_ADD = (
    SELECT MIN(DT_ADD) FROM MRU WHERE type = 'FILENAME'
)
Lasse V. Karlsen
Note, though, that the table declaration given doesn't contain a single column that we can assume to be the primary key.
Dathan
Yeah, noticed that, rewriting as we speak.
Lasse V. Karlsen
lack of PK is probably why they want to use `limit 1`. It would be better to just fix the design and `DELETE ... WHERE ID=n`
KM
Thanks, everyone for the answers. The error message says syntax error near "ORDER". Do you mean order doesn't work for all version of SQLite, just certain version that were compiled specifically have order by?
rvpals
Can someone explain th significance of no primary key and delete in SQLite?
rvpals
Rev 2 of this answer won't work, as it will delete *all* records that have the min(dt_add) value. user only wants to delete a single one. user will have to add some sort of identifier to the table to get this to work (and use rev 1's DDL SQL) or recompile the SQLite library with SSQLITE_ENABLE_UPDATE_DELETE_LIMIT set. I recommend the former.
sheepsimulator
Considering that the table is named "MRU", for Most Recently Used, I seriously doubt there will be more than one entry with any given date-time for "when added". If there is, then yes, a redesign is a good idea. Mind you, a redesign to get a unique primary key is a good decision in any way.
Lasse V. Karlsen
+2  A: 

I'm not saying that you should do so, since it's completely non-portable, but if there's a compelling need, this will work:

In SQLite the rowid column always exists unless an integer primary key is defined elsewhere. This can be used in something like:

delete from MRU where rowid = (
    select rowid from MRU order by DT_ADD limit 1
)
pkh