Ask Your Question
3

How can subqueries be used to update rows in a table in postgres?

asked 2023-03-07 11:00:00 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-02-06 22:00:00 +0000

woof gravatar image

Subqueries can be used to update rows in a table in PostgreSQL in the following way:

  1. First, identify the rows that need to be updated by using a subquery to select the appropriate rows based on certain conditions.

  2. Use the subquery as a filter for the UPDATE statement to update the selected rows.

For example, suppose you want to update the price of a product in the "products" table based on the average price of other products in the same category. You can use the following query:

UPDATE products
SET price = price * 1.1 -- increase price by 10%
WHERE category_id = (
  SELECT category_id
  FROM products
  WHERE product_id = 12345
) 
AND price < (
  SELECT AVG(price)
  FROM products
  WHERE category_id = (
    SELECT category_id
    FROM products
    WHERE product_id = 12345
  )
);

In this query, the subquery is used to select the category ID of the product with ID 12345. This category ID is then used as a filter in the main query to update the prices of all products in the same category whose price is lower than the average price of that category. The AVG function is used to calculate the average price for the category.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-03-07 11:00:00 +0000

Seen: 12 times

Last updated: Feb 06 '22