SQL (Structured Query Language) is a powerful language for managing and operating relational databases.UPDATE
Statements are a method in SQL to modify records already present in databases. Here are some classicsUPDATE
Statement case:
1. Update column values for specific rows:
UPDATE employees SET salary = salary * 1.1 WHERE employee_id = 123;
This statement willemployees
In the tableemployee_id
For employees of 123salary
Increase by 10%.
2. Update multiple lines based on conditions:
UPDATE employees SET salary = salary * 1.05 WHERE department_id = 5;
This statement willemployees
In the tabledepartment_id
For all employees of 5salary
Increased by 5%.
3.Use subquery to update:
UPDATE employees SET salary = (SELECT AVG(salary) FROM employees WHERE department_id = 5) WHERE department_id = 5;
This statement willdepartment_id
For all employees of 5salary
Updated to the average salary of the same department.
4. Update multiple columns:
UPDATE employees SET first_name = 'John', last_name = 'Doe' WHERE employee_id = 123;
This statement willemployees
In the tableemployee_id
For employees of 123first_name
andlast_name
Updated to 'John' and 'Doe'.
5. Use JOIN to update the relevant table:
UPDATE orders SET = 'Shipped' FROM orders JOIN order_details ON orders.order_id = order_details.order_id WHERE order_details.product_id = 456;
This statement willorder_details
In the tableproduct_id
For all orders of 456status
Updated to 'Shipped'.
6. Use LIMIT to limit the number of update rows (supported in some database systems):
UPDATE employees SET salary = salary * 1.05 WHERE department_id = 5 LIMIT 10;
This statement willemployees
In the tabledepartment_id
For the top 10 employees of 5salary
Increased by 5%.
7. Use CASE statement to perform conditional update:
UPDATE employees SET salary = CASE WHEN department_id = 1 THEN salary * 1.1 WHEN department_id = 2 THEN salary * 1.05 ELSE salary END WHERE department_id IN (1, 2);
This statement is based ondepartment_id
The difference is, rightemployees
Employees in the tablesalary
Make different proportions of increase.
In useUPDATE
Be careful when performing statements, because once executed, the data in the database will be modified directly. It is best to use it before performing an update operationSELECT
The statement checks the data to be updated to ensure that the update conditions are correct. In addition, for important data update operations, it is recommended to perform them in the test environment first, and then perform them in the production environment after confirming that they are correct.
This is all about this article about the Update statement in Sql. For more related SQL update statement content, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!