skip to Main Content

If we have a table named “names”

| id | name |
|----|------|
| 1  |  ab  |
| 2  |  bc  |
| 3  |  ab  |

and we give the SQL statement


DELETE FROM names WHERE name = 'ab';

rows with id of 1 and 3 are deleted.

How to write a query with name = ‘ab’ without considering id and delete only one row in descending order of id?

2

Answers


  1. DELETE FROM names WHERE name='ab' LIMIT 1
    

    You can give LIMIT in DELETE query too and MySQL will only delete those many records matching the criteria.

    And, it will also work with ORDER BY.

    DELETE FROM names WHERE name='ab' ORDER BY id DESC LIMIT 1
    

    This will delete the record with id = 3 in your case.

    Login or Signup to reply.
  2. If you are using SQL Server, you can make use of the TOP keyword in the DELETE statement

    DELETE TOP (1) FROM names WHERE name = 'ab';
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search