5.1 INSERT, UPDATE, DELETE Statements
5.1.1 INSERT Statement
The INSERT statement is used to add new records to a table.
Syntax:
INSERT INTO table_name (column1, column2, column3, ...)VALUES (value1, value2, value3, ...);
Example:
Consider a table named Employees with columns EmployeeID, FirstName, and LastName.
-- Inserting a new employeeINSERT INTO Employees (EmployeeID, FirstName, LastName)VALUES (1, 'John', 'Doe');
Query Output:
| EmployeeID | FirstName | LastName |
|---|---|---|
| 1 | John | Doe |
5.1.2 UPDATE Statement
The UPDATE statement is used to modify existing records in a table.
Syntax:
UPDATE table_nameSET column1 = value1, column2 = value2, ...WHERE condition;
Example:
Continuing with the Employees table, let's update John Doe's last name.
-- Updating the last name of employee with ID 1UPDATE EmployeesSET LastName = 'Smith'WHERE EmployeeID = 1;
Query Output:
| EmployeeID | FirstName | LastName |
|---|---|---|
| 1 | John | Smith |
5.1.3 DELETE Statement
The DELETE statement is used to remove records from a table.
Syntax:
DELETE FROM table_name WHERE condition;
Example:
Removing the employee with ID 1 from the Employees table.
-- Deleting the employee with ID 1DELETE FROM Employees WHERE EmployeeID = 1;
Query Output:
| EmployeeID | FirstName | LastName |
|---|---|---|
| (No rows) | (No rows) | (No rows) |
This table would indicate that there are no rows left after the DELETE operation.
Conclusion
Understanding how to use INSERT, UPDATE, and DELETE statements is essential for manipulating data within SQL Server tables. Always be cautious when using DELETE to avoid unintentional data loss.