Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update a column based on other column with postgresql

I have a table with the following columns:

id  integer
sumqty numeric
maxqty  numeric

The columns id, sumqty are updated by other functions regularly. I need to write a function that pass on these two columns and update the maxqty column.

for example:

id, sumqty, maxqty
5    20
5    70
5    45
3    20
1    12
1    2.5

after function runs, desired output will be:

id, sumqty, maxqty
5    20      45
5    10      45
5    45      45
3    20      20
1    12      12
1    2.5     12

I wrote this code:

update A set maxqty= (select MAX(sumqty)  OVER (PARTITION BY id))

but it doesn't always works. Sometimes it doesn't give me the actualy MAX.

What is the problem with my code?

like image 947
SMW Avatar asked Oct 22 '25 04:10

SMW


1 Answers

Use correlated subquery instead:

SqlFiddleDemo

UPDATE mytable t1
SET maxqty= (SELECT MAX(sumqty) 
             FROM mytable t2
             WHERE t1.id = t2.id );

Result:

╔═════╦═════════╦════════╗
║ id  ║ sumqty  ║ maxqty ║
╠═════╬═════════╬════════╣
║  5  ║ 20      ║     45 ║
║  5  ║ 10      ║     45 ║
║  5  ║ 45      ║     45 ║
║  3  ║ 20      ║     20 ║
║  1  ║ 12      ║     12 ║
║  1  ║ 2.5     ║     12 ║
╚═════╩═════════╩════════╝

More efficient way:

WITH cte AS
( 
  SELECT id, MAX(sumqty) AS sumqty
  FROM mytable
  GROUP BY id
)
UPDATE mytable m
SET maxqty = c.sumqty
FROM cte c
WHERE m.id = c.id;

Your original query:

update mytable 
set maxqty= (select MAX(sumqty)  OVER (PARTITION BY id);

Gives:

╔═════╦═════════╦════════╗
║ id  ║ sumqty  ║ maxqty ║
╠═════╬═════════╬════════╣
║  5  ║ 20      ║ 20     ║
║  5  ║ 10      ║ 10     ║
║  5  ║ 45      ║ 45     ║
║  3  ║ 20      ║ 20     ║
║  1  ║ 12      ║ 12     ║
║  1  ║ 2.5     ║ 2.5    ║
╚═════╩═════════╩════════╝

It is because UPDATE works per row. And your subquery has only one row to process not bunch of them.

like image 50
Lukasz Szozda Avatar answered Oct 23 '25 19:10

Lukasz Szozda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!