Skip to content

Commit 0c9028f

Browse files
committed
SQL-294 - Insert into SQL table or update if exists
1 parent 7aecb45 commit 0c9028f

File tree

4 files changed

+54
-0
lines changed

4 files changed

+54
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
CREATE TABLE employees (
2+
id INT PRIMARY KEY,
3+
name VARCHAR(50),
4+
department VARCHAR(50)
5+
);
6+
7+
8+
INSERT INTO employees (id, name, department) VALUES (1, 'Alice', 'Finance');
9+
10+
MERGE INTO employees AS target
11+
USING (SELECT 1 AS id, 'Alice' AS name, 'Accounting' AS department) AS source
12+
ON target.id = source.id
13+
WHEN MATCHED THEN
14+
UPDATE SET name = source.name, department = source.department
15+
WHEN NOT MATCHED THEN
16+
INSERT (id, name, department) VALUES (source.id, source.name, source.department);
17+
18+
19+
SELECT * from employees;
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
CREATE TABLE employees (
2+
id INT PRIMARY KEY,
3+
name VARCHAR(50),
4+
department VARCHAR(50)
5+
);
6+
7+
INSERT INTO employees (id, name, department) VALUES (1, 'Alice', 'Finance');
8+
9+
INSERT INTO employees (id, name, department) VALUES (1, 'Alice', 'Accounting')
10+
ON CONFLICT (id) DO UPDATE SET name = 'Alice', department = 'Accounting';
11+
12+
SELECT * from employees;
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
CREATE TABLE employees (
2+
id INT PRIMARY KEY,
3+
name VARCHAR(50),
4+
department VARCHAR(50)
5+
);
6+
7+
INSERT INTO employees (id, name, department) VALUES (1, 'Alice', 'Finance');
8+
9+
INSERT INTO employees (id, name, department) VALUES (1, 'Alice', 'Accounting')
10+
ON DUPLICATE KEY UPDATE name = 'Alice', department = 'Accounting';
11+
12+
SELECT * from employees;
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
CREATE TABLE employees (
2+
id INT PRIMARY KEY,
3+
name VARCHAR(50),
4+
department VARCHAR(50)
5+
);
6+
7+
INSERT INTO employees (id, name, department) VALUES (1, 'Alice', 'Finance');
8+
9+
REPLACE INTO employees (id, name, department) VALUES (1, 'Alice', 'Accounting');
10+
11+
SELECT * from employees;

0 commit comments

Comments
 (0)