Home >Database >Mysql Tutorial >How Can I Update PostgreSQL Table Rows Using a Subquery?

How Can I Update PostgreSQL Table Rows Using a Subquery?

Barbara Streisand
Barbara StreisandOriginal
2025-01-05 14:38:41345browse

How Can I Update PostgreSQL Table Rows Using a Subquery?

Updating Table Rows in PostgreSQL Using a Subquery

In PostgreSQL, updating existing rows using values returned from a SELECT statement can be accomplished through a convenient syntax.

Consider the provided table schema:

CREATE TABLE public.dummy (
  address_id SERIAL,
  addr1 character(40),
  addr2 character(40),
  city character(25),
  state character(2),
  zip character(5),
  customer boolean,
  supplier boolean,
  partner boolean
);

To update the table based on a subquery, use the following syntax:

UPDATE dummy
SET customer = subquery.customer,
    address = subquery.address,
    partn = subquery.partn
FROM (
  SELECT address_id, customer, address, partn
  FROM /* big hairy SQL */ ...
) AS subquery
WHERE dummy.address_id = subquery.address_id;

This syntax is not standard SQL but is convenient for this type of query. For example, to update the customer, address, and partn columns based on the results of a complex join, you could use the following subquery:

SELECT address_id,
       CASE
           WHEN cust.addr1 IS NOT NULL THEN TRUE
           ELSE FALSE
       END AS customer,
       CASE
           WHEN suppl.addr1 IS NOT NULL THEN TRUE
           ELSE FALSE
       END AS address,
       CASE
           WHEN partn.addr1 IS NOT NULL THEN TRUE
           ELSE FALSE
       END AS partn
FROM (
    SELECT *
    FROM address
) pa
LEFT OUTER JOIN cust_original AS cust
    ON (pa.addr1 = cust.addr1
        AND pa.addr2 = cust.addr2
        AND pa.city = cust.city
        AND pa.state = cust.state
        AND SUBSTRING(cust.zip, 1, 5) = pa.zip
    )
LEFT OUTER JOIN supp_original AS suppl
    ON (pa.addr1 = suppl.addr1
        AND pa.addr2 = suppl.addr2
        AND pa.city = suppl.city
        AND pa.state = suppl.state
        AND pa.zip = SUBSTRING(suppl.zip, 1, 5)
    )
LEFT OUTER JOIN partner_original AS partn
    ON (pa.addr1 = partn.addr1
        AND pa.addr2 = partn.addr2
        AND pa.city = partn.city
        AND pa.state = partn.state
        AND pa.zip = SUBSTRING(partn.zip, 1, 5)
)
WHERE pa.address_id = address_id;

By executing this update, the specified columns in the dummy table will be updated with the values obtained from the subquery.

The above is the detailed content of How Can I Update PostgreSQL Table Rows Using a Subquery?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn