Delete TOP - SQL Server Database
In SQL Server Database, the DELETE
statement is used to remove one or more rows from a table. The TOP
keyword, when used with DELETE
statement, specifies the number of rows to be deleted from the beginning of the result set. In this page, we will discuss how to use the DELETE TOP
statement in SQL Server Database.
Syntax
The basic syntax of the DELETE TOP
statement is as follows:
DELETE TOP (expression) FROM table_name WHERE condition;
Here, expression
is a numeric or integer value that specifies the number of rows to be deleted.
Example
Consider the following table named Employee
:
ID | Name | Salary |
---|---|---|
1 | John | 50000 |
2 | Mary | 60000 |
3 | Alex | 70000 |
4 | Tom | 45000 |
5 | Jack | 55000 |
To delete the first two rows (rows with IDs 1 and 2) from the Employee
table, the following SQL code can be used:
DELETE TOP (2) FROM Employee WHERE ID IN (SELECT TOP (2) ID FROM Employee);
This code will delete the two rows from the table where the ID is in the list of the first two rows from the Employee
table.
Output
Once the code is executed, the rows will be deleted from the Employee
table. In this example, the output will be as follows:
ID | Name | Salary |
---|---|---|
3 | Alex | 70000 |
4 | Tom | 45000 |
5 | Jack | 55000 |
Explanation
The DELETE TOP
statement with WHERE
condition is used to delete a specific number of rows from the beginning of the result set. The WHERE
clause is used to specify the condition that needs to be met in order to delete the rows.
In the example above, we used the DELETE
statement with the TOP
operator to delete the first two rows from the Employee
table, where the ID
is in the list of the first two rows from the Employee
table.
Use
The DELETE TOP
statement is particularly useful when you need to delete a specific number of rows from a table based on a condition. It is also useful when you need to delete a large number of rows from a table, but want to do it in small increments so that other users can still access the table while the deletion is taking place.
Important Points
- The
DELETE TOP
statement is used to a specific number of rows from a table based on a condition. - The
WHERE
clause is used to specify the condition that needs to be met in order to delete the rows. - The
DELETE TOP
statement is particularly useful when you need to delete a large number of rows from a table in small increments.
Summary
In this page, we discussed how to use the DELETE TOP
statement SQL Server Database. We covered the syntax, example, output, explanation, use, and important points of the DELETE TOP
statement. By using this statement, you can delete a specific number of rows from a table based on a condition.