In SQL, the INSERT
, UPDATE
, and DELETE
statements are used to manipulate database rows in different ways:
INSERT:
TheINSERT
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:
TheUPDATE
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:
UPDATE Employees SET Age = 32, Department = 'Marketing' WHERE EmployeeID = 1;
This will change the "Age" to 32 and the "Department" to "Marketing" for the employee with EmployeeID 1.
DELETE:
TheDELETE
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:
DELETE FROM table_name WHERE condition;
Here's an example of deleting an employee from the "Employees" table based on their EmployeeID:
DELETE FROM Employees WHERE EmployeeID = 1;
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.