INSERT, UPDATE, and DELETE Database Rows
In SQL, the INSERT
, UPDATE
, and DELETE
statements are used to manipulate database rows in different ways:
INSERT:
The INSERT
statement is used to add new rows or records into a table. It allows you to specify the values for each column of the table or insert data from another source, such as a subquery or another table.
The basic syntax for the INSERT
statement is as follows:
INSERT INTO table_name (column1, column2, ..., columnN)
VALUES (value1, value2, ..., valueN);
Here's an example of inserting a new row into the "Employees" table:
INSERT INTO Employees (EmployeeID, FirstName, LastName, Age, Department)
VALUES (1, 'John', 'Doe', 30, 'HR');
This will add a new employee with the specified details to the "Employees" table.
UPDATE:
The UPDATE
statement is used to modify existing rows in a table. It allows you to change the values of one or more columns in the table based on certain conditions.
The basic syntax for the UPDATE
statement is as follows:
UPDATE table_name
SET column1 = value1, column2 = value2, ..., columnN = valueN
WHERE condition;
Here's an example of updating the "Age" and "Department" columns of an employee with a specific EmployeeID:
This will change the "Age" to 32 and the "Department" to "Marketing" for the employee with EmployeeID 1
DELETE:
The DELETE
statement is used to remove rows from a table. It allows you to delete one or more rows that match a specified condition.
The basic syntax for the DELETE
statement is as follows:
Here's an example of deleting an employee from the "Employees" table based on their EmployeeID:
This will remove the employee with EmployeeID 1 from the "Employees" table.
It's essential to use these statements with caution, especially the DELETE
statement, as it permanently removes data from the table. Always make sure to use appropriate filtering conditions in the WHERE
clause to target only the desired rows for updates and deletions. Additionally, consider taking backups or using transactions to avoid data loss or unintended changes.