PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 24, 2022

[FIXED] How to update a table without creating new rows

 October 24, 2022     postgresql, sql-update     No comments   

Issue

Imagine I have a set of key-value data from a primary key to values:

id foo
1 abc
2 def
3 ghj

... that need to be updated in a table.

And I want to update all of these in one query. Naturally, upserts come to mind, which works quite well:

INSERT INTO my_table (id, foo) VALUES ((1, 'abc'), (2, 'def'), (3, 'ghj')) 
ON CONFLICT (id) DO UPDATE SET foo = excluded.foo;

This works fine, but what if I don't actually want to insert the row with id=3 when it doesn't already exist in the table my_table?


Solution

I don't see why you would need an INSERT at all if you just want to UPDATE the rows?

update my_table 
  set foo = v.foo 
from ( 
  VALUES (1, 'abc'), (2, 'def'), (3, 'ghj')
) as v(id, foo)
where v.id = my_table.id;


Answered By - a_horse_with_no_name
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing