HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlMinor

How to limit the amount of values within a postgres table which are updated

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
thepostgresamountlimitwhicharewithinupdatedhowvalues

Problem

using the following sample:
CREATE TABLE tbl(
x integer,
y integer
)

INSERT INTO tbl
SELECT g AS x FROM generate_series(1, 10) AS g;


Which gives:

x  | y 
----+---
  1 |  
  2 |  
  3 |  
  4 |  
  5 |  
  6 |  
  7 |  
  8 |  
  9 |  
 10 |  
(10 rows)


I'd like to have something like (note - I do not care about the ordering of the three values updated in y here):

x  | y 
----+---
  1 |  1
  2 |  2
  3 |  3
  4 |  
  5 |  
  6 |  
  7 |  
  8 |  
  9 |  
 10 |  
(10 rows)


I've tried to do this using the following:

UPDATE tbl
SET y = x
WHERE y IS NULL
LIMIT 3;


But I get the error ERROR: syntax error at or near "LIMIT", which I'm not sure how to fix.
Solution

I think the following works:

update tbl 
set y = x 
where x in (select x from tbl where y is null limit 3);


I can't think of a scenario this would fail, if there's a better approach it'd be good to know.

Solution

Using common table expressions or CTE might be a good solution, more dynamically (easily changed if the conditions of the updated pattern are modified ) , in terms of performance it should be tested.

Use,

WITH cte AS (
    SELECT x 
    from tbl
    where y is null
    limit 3
)
UPDATE tbl
SET y = cte.x
FROM cte
WHERE tbl.x = cte.x ;


https://dbfiddle.uk/3h9Zqili

Code Snippets

WITH cte AS (
    SELECT x 
    from tbl
    where y is null
    limit 3
)
UPDATE tbl
SET y = cte.x
FROM cte
WHERE tbl.x = cte.x ;

Context

StackExchange Database Administrators Q#321687, answer score: 4

Revisions (0)

No revisions yet.