0

I want to delete table rows from xyz table where row count should be greater than 10, but I don't have any column that holds row position. I don't want to add additional column such as Id. Here is my table structure:

name(as text)  subject(as text)  filename(as text)

and here is my query which deletes entire table

delete from questions where (select Count(*) from questions)  between  10 and 20

I am not getting what to write instead of (select Count(*) from questions)

any solutions?

Korhan Ozturk
  • 11,148
  • 6
  • 36
  • 49
Dhanesh
  • 781
  • 2
  • 9
  • 16

6 Answers6

1

Another solution might be to maintain a timestamp on each record and drop the oldest one when a new one comes in. It seems bizarre that you have so little need for the data you've persisted. I wonder about your requirements and your design.

duffymo
  • 305,152
  • 44
  • 369
  • 561
1

I think this would work:

DELETE FROM table WHERE name NOT IN (SELECT TOP 10 name FROM table)

This is assuming that name is unique.

Mike Bockus
  • 2,079
  • 17
  • 23
0

Create a replica table with same scheme say test2

insert into test2 select * from test limit 10

delete from test;

insert into test select * from test2;
Naveen Kumar
  • 4,543
  • 1
  • 18
  • 36
0

MySQL does not provide a row id, but there seems to be a workaround using session variables, as posted in the answer to this thread: Equivalent of Oracle’s RowID in MySQL

Community
  • 1
  • 1
vaisakh
  • 1,041
  • 9
  • 19
0

Making 2 assumptions: name is you id column and you want to sort by name.

One way to do it would be to:

DELETE FROM Xyz WHERE name NOT IN (SELECT name FROM Xyz ORDER BY name LIMIT 10);

But that will likely just give you:

ERROR 1235 (42000): This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'

As a workaround to that you can use a temporary table:

CREATE TEMPORARY TABLE temp SELECT * FROM Xyz ORDER BY name LIMIT 10;
DELETE FROM Xyz WHERE name NOT IN (SELECT name FROM temp);
DROP TABLE temp;
barsju
  • 4,408
  • 1
  • 19
  • 24
0

This is weird.

1) Why don't you want an additional column?
2) Which rows do you want to delete? Unless the choice is made on name, subject or filename, you will need an additional column.
2a) If which rows are deleted does not matter, you can simply stop inserting after 10 rows. You can also have a CHECK constraint which enforces this for you, though I'm not sure if MySQL supports such an advanced construct.
3) Is the number really 10? If so, are you sure a database is the storage you need for this? I gotta go with @duffymo here, this smells of bad design.

aib
  • 45,516
  • 10
  • 73
  • 79