Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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.