Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete the 'first' record from a table in SQL Server, without a WHERE condition

Tags:

sql

sql-server

Is it possible to delete the first record from a table in SQL Server, without using any WHERE condition and without using a cursor?

like image 745
Dhanapal Avatar asked Apr 09 '09 10:04

Dhanapal


People also ask

How do you delete top 1 records in SQL?

Using MS SQL Server 2005, if you intend to delete the "top record" (the first one that is presented when you do a simple "*select * from tablename*"), you may use "delete top(1) from tablename"... but be aware that this does not assure which row is deleted from the recordset, as it just removes the first row that would ...

How delete specific records from table in SQL?

To remove one or more rows in a table: First, you specify the table name where you want to remove data in the DELETE FROM clause. Second, you put a condition in the WHERE clause to specify which rows to remove. If you omit the WHERE clause, the statement will remove all rows in the table.

What will happen if no condition is specified in WHERE clause in delete statement?

If you run a DELETE statement with no conditions in the WHERE clause, all of the records from the table will be deleted.


1 Answers

WITH  q AS         (         SELECT TOP 1 *         FROM    mytable         /* You may want to add ORDER BY here */         ) DELETE FROM    q 

Note that

DELETE TOP (1) FROM   mytable 

will also work, but, as stated in the documentation:

The rows referenced in the TOP expression used with INSERT, UPDATE, or DELETE are not arranged in any order.

Therefore, it's better to use WITH and an ORDER BY clause, which will let you specify more exactly which row you consider to be the first.

like image 87
Quassnoi Avatar answered Oct 13 '22 06:10

Quassnoi