0

I am writing a postgres query where I ask to return each order for each user. In case of the user hasn't a order I would like to return Null instead of no return.

My current query:

Select Order.user_id, 
       User.name, 
       Order.id, 
       Order.value, 
       Order.item
FROM Order
       Left Join User
       On Order.user_id = User.id

it returns each user order but in case of user with no order, nothing is returned. How I can return Null (or any string) instead of no return? Thank you so much.

2
  • 2
    Use right instead of left if you want all rows from the rightmost table (users) Commented Jun 15, 2021 at 21:55
  • Yeah, it works. Commented Jun 16, 2021 at 14:34

1 Answer 1

3

You want a left join, but you want user first:

SELECT u.id as user_id, u.name, o.id, o.value, o.item
FROM User u LEFT JOIN
     Order o
     ON o.user_id = u.id;

I also introduced table aliases so the query is easier to write and to read. And . . . change o.user_id to u.id in the SELECT so it has a value when there are no orders.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.