Problem
You need to calculate a running total in SQL Server and provide a solution that is also reproducible in MySQL.
Input
employee_id | first_name | last_name | salary |
---|---|---|---|
1 | John | Doe | 50000.00 |
2 | Jane | Smith | 60000.00 |
3 | Bob | Johnson | 55000.00 |
Try Hands-On: Fiddle
Desired Output
On inserting a new row, if the entry already exists, it should update the existing entry.
For example, we want to update the employee_id = 1’s salary to 55000.
employee_id | first_name | last_name | salary |
---|---|---|---|
1 | John | Doe | 55000.00 |
2 | Jane | Smith | 60000.00 |
3 | Bob | Johnson | 55000.00 |
Solution 1:
You can use the INSERT INTO … ON DUPLICATE KEY UPDATE statement in MySQL to achieve this.
This statement will insert a new row into the table, or if a duplicate key violation occurs (i.e., a row with the same primary or unique key exists), it will update the existing row with the new values. Here’s the SQL query:
INSERT INTO employees (employee_id, first_name, last_name, salary)
VALUES
(1, 'John', 'Doe', 55000.00)
ON DUPLICATE KEY UPDATE
first_name = VALUES(first_name),
last_name = VALUES(last_name),
salary = VALUES(salary);
Explanation:
In this example, we’re trying to insert a row with employee_id 1, which already exists in the table.
Instead of inserting a new row, this query will update the existing row with the new salary value (55000.00).
You can execute this query to insert or update data into the employees table as needed.
Recommended Courses
Recommended Tutorial
More SQL Questions
- How to select only rows with max value on a column?
- How to transpose columns to rows in SQL?
- How to select first row in each GROUP BY group?
- How to concatenate text from multiple rows into a single text string in MySQL?
- How to get the rows which have the max value for a column for each group in another column in SQL?
- How to select first row in each GROUP BY group?