# RETURNING & Upsert

> Get the written rows back with RETURNING, and handle duplicate keys with ON CONFLICT instead of an error.

Subject: SQL | Lesson 31 of 44 | 6 min read
Interactive lesson: https://codewithanimation.in/sql/returning-and-upsert
Previous: [UPDATE & DELETE](https://codewithanimation.in/sql/update-and-delete.md) | Next: [Transactions & ACID](https://codewithanimation.in/sql/transactions-and-acid.md)

## Two small additions that save a lot of code

`RETURNING` goes at the end of `INSERT`, `UPDATE` or `DELETE` and makes the statement answer with rows, like a `SELECT`. For `INSERT` you get the new row. For `UPDATE` you get the new content of each changed row. For `DELETE` you get the row that was removed.

`ON CONFLICT` goes after `VALUES` and says what to do when a row would break a unique key, instead of raising an error. `DO NOTHING` skips the row. `DO UPDATE SET ...` updates the row that is already there.

## No second query, no race

After inserting a row you almost always need its id. Asking with a second query is slower and can pick the wrong row if someone else inserts at the same moment. `RETURNING id` gives the right answer in the same step.

"Insert it, or update it if it already exists" is a very common need. Doing it in your own code takes two statements and can fail when two people run it at once. One `ON CONFLICT` statement does it in one step.

## Insert, return and upsert

```sql
INSERT INTO members (name, email)
VALUES ('Dara', 'dara@mail.test')
RETURNING id, name;
```

The statement returns the row Dara got: id 4. Now the upsert:

```sql
INSERT INTO members (id, name, email)
VALUES (2, 'Ben2', 'b2@mail.test')
ON CONFLICT (id) DO UPDATE
  SET name = EXCLUDED.name, email = EXCLUDED.email
RETURNING id, name, email;
```

Id 2 already exists, so instead of an error, that row is updated. `EXCLUDED` is the name for the row you tried to insert. With `DO NOTHING` the row is skipped, the tag says `INSERT 0 0`, and `RETURNING` gives back nothing, because no row was written.

## Common mistake: Conflict target and double hits

`DO UPDATE` needs a conflict target, such as `(id)`: PostgreSQL has to know which unique rule you mean. A conflict on a different unique column, such as a repeated email, still raises an error.

One statement may not update the same existing row twice. If two of your `VALUES` rows have the same key, PostgreSQL stops with `ON CONFLICT DO UPDATE command cannot affect row a second time`. Make sure the rows you send do not repeat the key.

In the tag `INSERT 0 n`, n counts rows inserted and rows updated, so you cannot tell from the tag alone which was which. Use `RETURNING` if you need to know.

## Tip: Use RETURNING for ids, ON CONFLICT for "create or update"

Prefer `RETURNING id` over a second query. Prefer `ON CONFLICT` over "check, then insert" in your code. The manual also shows `RETURNING old.price, new.price` to see both versions of an updated row.

## Try it: Return rows, then upsert

Run INSERT ... RETURNING and watch the RETURNING table. Then run both ON CONFLICT versions on id 2, and the last one that touches the same key twice.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/sql/returning-and-upsert

## Check yourself

### Question 1

What does `RETURNING *` give back at the end of a `DELETE`?

- A. The rows that were deleted
- B. The rows that are left in the table
- C. Only the number of rows deleted

Correct answer: A

For DELETE, the default data available to RETURNING is the content of the deleted row.

- Why not B: RETURNING shows the rows the statement touched, not the whole table.
- Why not C: The count is in the command tag. RETURNING gives the actual rows.

### Question 2

`INSERT ... ON CONFLICT (id) DO NOTHING RETURNING id` runs with an id that already exists. What does it return?

- A. No rows, and the tag is INSERT 0 0
- B. The existing id
- C. An error

Correct answer: A

The conflicting row is skipped, so no row was written, and RETURNING has nothing to return.

- Why not B: RETURNING only reports rows that the statement actually wrote.
- Why not C: DO NOTHING is exactly what avoids the error.

### Question 3

In `DO UPDATE SET name = EXCLUDED.name`, what is EXCLUDED?

- A. The row you proposed to insert
- B. The row that is already in the table
- C. A list of rows that were rejected earlier

Correct answer: A

EXCLUDED is the special name for the row that was proposed for insertion.

- Why not B: The existing row is referred to by the table name. EXCLUDED is the new one.
- Why not C: EXCLUDED is only the row from this INSERT that caused the conflict.

## Remember this

- RETURNING gives back the rows an INSERT, UPDATE or DELETE wrote: new row, new content, deleted row.
- ON CONFLICT DO NOTHING skips a duplicate. ON CONFLICT (key) DO UPDATE updates the existing row using EXCLUDED.
- DO UPDATE needs a conflict target, and one statement may not hit the same row twice.
- Use RETURNING id instead of a second query, and ON CONFLICT instead of check-then-insert.
