Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SQL-294 - Insert into SQL table or update if exists #237

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions sql-queries-7/README
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
### Relevant Articles:

11 changes: 11 additions & 0 deletions sql-queries-7/insert-or-update-if-exists/merge-sql-server.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
INSERT INTO Department (id, name, code) VALUES (1, 'Computer Science', 'CS');

MERGE INTO Department AS target
USING (SELECT 1 AS id, 'Computer Science' AS name, 'CSE' AS code) AS source
ON target.id = source.id
WHEN MATCHED THEN
UPDATE SET name = source.name, code = source.code
WHEN NOT MATCHED THEN
INSERT (id, name, code) VALUES (source.id, source.name, source.code);

SELECT * from Department;
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
INSERT INTO Department (id, name, code) VALUES (1, 'Computer Science', 'CS');

INSERT INTO Department (id, name, code) VALUES (1, 'Computer Science', 'CSE')
ON CONFLICT (id) DO UPDATE SET name = 'Computer Science', code = 'CSE';

SELECT * from Department;
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
INSERT INTO Department (id, name, code) VALUES (1, 'Computer Science', 'CS');

INSERT INTO Department (id, name, code) VALUES (1, 'Computer Science', 'CSE')
ON DUPLICATE KEY UPDATE name = 'Computer Science', code = 'CSE';

SELECT * from Department;
5 changes: 5 additions & 0 deletions sql-queries-7/insert-or-update-if-exists/replace-mysql.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
INSERT INTO Department (id, name, code) VALUES (1, 'Computer Science', 'CS');

REPLACE INTO Department (id, name, code) VALUES (1, 'Computer Science', 'CSE');

SELECT * from Department;