PGoCareerGoCareer prep tools
LoginSign up
  • Java
  • Python
  • AI
  • React
  • Angular
  • PHP
  • Node.js
  • SQL
  • DSA
  • HTML
  • CSS
  • JS
  • Spring
  • ML
  • MongoDB

SQL · Theory

UPSERT

← All stacks

Theory

284/439

UPSERT

Upsert = insert or update if the key exists. MySQL: INSERT … ON DUPLICATE KEY UPDATE … or REPLACE (harsher). Example: refresh Asha’s marks if roll 12 exists, else insert.

Needs a PRIMARY/UNIQUE key to detect ‘exists’.

Trap — upsert without a unique key — always inserts.

On the example next to this theory: UPSERT: create two demo rows, then SELECT qty >= 2 ordered. Say which labels come back.

Exam tip

INSERT … ON DUPLICATE KEY UPDATE marks = 90;

UPSERT — sample query

-- UPSERT
CREATE TABLE demo (
  id INTEGER PRIMARY KEY,
  label TEXT NOT NULL,
  qty INTEGER DEFAULT 0
);
INSERT INTO demo (id, label, qty) VALUES
  (1, 'alpha', 2),
  (2, 'beta', 5);
SELECT label, qty FROM demo WHERE qty >= 2 ORDER BY qty DESC;

UPSERT: create two demo rows, then SELECT qty >= 2 ordered. Say which labels come back.

Short notes

  • DefUpsert = INSERT or UPDATE on key clash.
  • RuleNeed PK/UNIQUE. Prefer ON DUPLICATE KEY UPDATE.
  • TrapNo unique key.

Questions

1

MySQL upsert?

284 / 439

P

GoCareerGo

Utilities · Preparation Hub · Resume · CV · Tools — one workspace.

Workspace

DashboardProfilePreparation HubResume builderCV builderCareer planning

PDF Tools

Merge PDFSplit PDFCompress PDFImage to PDFAll toolsJobs

Image & QR

Compress ImageResize ImageQR ScannerQR GeneratorBlogIT interview prep

Company

FAQFeedbackContactPrivacyTermsSitemap

© 2026 GoCareerGo. Keep moving forward.