Is it possible to delete the first record from a table in SQL Server
, without using any WHERE
condition and without using a cursor?
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 ...
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.
If you run a DELETE statement with no conditions in the WHERE clause, all of the records from the table will be deleted.
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 withINSERT
,UPDATE
, orDELETE
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With