sql-server
  1. sql-server-delete-data

Delete Data - (SQL Server Database)

Deleting data from a SQL Server database is a common task that is performed with the DELETE statement. In this page, we will discuss how to delete data from a table using SQL Server.

Syntax

Here is the basic syntax for the DELETE statement:

DELETE FROM table_name WHERE condition;
  • table_name: The name of the table from which you want to delete data.
  • condition: The condition that must be satisfied for the record to be deleted.

Example

Consider the following table named students:

ID NAME AGE
1 John 22
2 Jane 20
3 Mark 24
4 Jack 21

To delete a student with ID equal to 2, you can use the following DELETE statement:

DELETE FROM students WHERE ID = 2;

This will remove the second row as shown below:

ID NAME AGE
1 John 22
3 Mark 24
4 Jack 21

Output

When you execute the DELETE statement, you will receive a message indicating the number of rows affected by the query.

(1 row(s) affected)

This tells you that one row was deleted as a result of the query.

Explanation

The DELETE statement is used to remove one or more records from a table. In the example above, we deleted a single record from the students table where the student ID was equal to 2. If you want to delete all records from a table, you can omit the WHERE clause from the DELETE statement, but be careful as this will delete all rows from the table.

Use

The DELETE statement is frequently used in applications to remove stale or incorrect data. Be careful when using this statement and make sure to check the WHERE clause to ensure that you are only deleting the intended records.

Important Points

  • Be careful when using the DELETE statement, particularly without a WHERE clause as this will delete all records from the table.
  • Always run a sample query before performing a DELETE on a large table to ensure that you are deleting the correct records.

Summary

In this page, we discussed how to delete data from a SQL Server database using the DELETE statement. We covered the syntax, example, output, explanation, use, and important points of the DELETE statement. By understanding how to use the DELETE statement, you can safely remove data from your database as needed.

Published on: