# set a column with value from different table

Say that you have Table A:

* username
* email

And Table B:

* item\_id
* username

You want to add email to `table B` where the value taken from `table A`. After adding a column on Table B, this query can be used:

```sql
UPDATE tableB
SET    email = tableA.Email
FROM   tableA
WHERE  tableB.username = tableA.username
AND    tableB.email IS DISTINCT FROM tableA.email;  -- optional, see below
```

The final `WHERE` clause prevents updates that wouldn't change anything - which is practically always a good idea (almost full cost but no gain, exotic exceptions apply). If both old and new value are guaranteed to be `NOT NULL`, simplify to:

```
AND   tableB.email <> tableA.email
```

Taken from: <https://stackoverflow.com/questions/13473499/update-a-column-of-a-table-with-a-column-of-another-table-in-postgresql>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://til.yulrizka.com/db/set-a-column-with-value-from-different-table.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
