Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete all rows except first N from a table having single column

Tags:

mysql

I need a single query. Delete all rows from the table except the top N rows. The table has only one column. Like,

|friends_name|
==============
| Arunji     |
| Roshit     |
| Misbahu    |
| etc...     |

This column may contain repeated names as well.

  • Contains repeated names

  • Only one column.

like image 408
Nidheesh Avatar asked Jun 25 '13 08:06

Nidheesh


People also ask

How do I select all rows except one in SQL?

The SQL EXCEPT operator is used to return all rows in the first SELECT statement that are not returned by the second SELECT statement. Each SELECT statement will define a dataset. The EXCEPT operator will retrieve all records from the first dataset and then remove from the results all records from the second dataset.

How do I exclude the first row in SQL?

The OFFSET FETCH clause allows you to skip N first rows in a result set before starting to return any rows. In this syntax: The ROW and ROWS , FIRST and NEXT are the synonyms. Therefore, you can use them interchangeably.


1 Answers

If you can order your records by friends_name, and if there are no duplicates, you could use this:

DELETE FROM names
WHERE
  friends_name NOT IN (
    SELECT * FROM (
      SELECT friends_name
      FROM names
      ORDER BY friends_name
      LIMIT 10) s
  )

Please see fiddle here.

Or you can use this:

DELETE FROM names ORDER BY friends_name DESC
LIMIT total_records-10

where total_records is (SELECT COUNT(*) FROM names), but you have to do this by code, you can't put a count in the LIMIT clause of your query.

like image 96
fthiella Avatar answered Nov 15 '22 19:11

fthiella