Skip to content

Commit e2e6e12

Browse files
authored
Merge pull request #237 from abh1navv/main
SQL-294 - Insert into SQL table or update if exists
2 parents 28b26c0 + cd4226b commit e2e6e12

File tree

5 files changed

+30
-0
lines changed

5 files changed

+30
-0
lines changed

sql-queries-7/README

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
### Relevant Articles:
2+
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
INSERT INTO Department (id, name, code) VALUES (1, 'Computer Science', 'CS');
2+
3+
MERGE INTO Department AS target
4+
USING (SELECT 1 AS id, 'Computer Science' AS name, 'CSE' AS code) AS source
5+
ON target.id = source.id
6+
WHEN MATCHED THEN
7+
UPDATE SET name = source.name, code = source.code
8+
WHEN NOT MATCHED THEN
9+
INSERT (id, name, code) VALUES (source.id, source.name, source.code);
10+
11+
SELECT * from Department;
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
INSERT INTO Department (id, name, code) VALUES (1, 'Computer Science', 'CS');
2+
3+
INSERT INTO Department (id, name, code) VALUES (1, 'Computer Science', 'CSE')
4+
ON CONFLICT (id) DO UPDATE SET name = 'Computer Science', code = 'CSE';
5+
6+
SELECT * from Department;
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
INSERT INTO Department (id, name, code) VALUES (1, 'Computer Science', 'CS');
2+
3+
INSERT INTO Department (id, name, code) VALUES (1, 'Computer Science', 'CSE')
4+
ON DUPLICATE KEY UPDATE name = 'Computer Science', code = 'CSE';
5+
6+
SELECT * from Department;
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
INSERT INTO Department (id, name, code) VALUES (1, 'Computer Science', 'CS');
2+
3+
REPLACE INTO Department (id, name, code) VALUES (1, 'Computer Science', 'CSE');
4+
5+
SELECT * from Department;

0 commit comments

Comments
 (0)