0

In my query, I want to join tables only if the first table's specified column is null. How I can do the join. This is an INNER JOIN and there are 3 tables.

Here is my query.

SELECT item_id,item_name
  FROM item i
INNTER JOIN supplier s ON i.item_id=s.items_id
INNER JOIN order O ON O.id=s.req_id
WHERE price>400 AND category='ALL'; 

this join should be available only if the column 'item_order_id' in the item table is NULL. If that column is not null, this join shuold not be done. How can I do in in Postgres (I use postgres 8).

3
  • 1
    add AND i.item_order_id IS NULL to the where clause ? Commented Nov 6, 2013 at 11:13
  • "Postgres 8" covers five major releases (8.0, 8.1, 8.2, 8.3 and 8.4) - you should state your exact version. Also note that only 8.4 is still supported (but only for a few more months) so you should really plan an upgrade to a current (e.g. 9.3) release. Commented Nov 6, 2013 at 11:19
  • I use 8.0.3. versioning upgrade can be a good idea. but for my system environment I have to keep current version. Commented Nov 6, 2013 at 11:23

1 Answer 1

2

Option 1. Put the condition in the WHERE clause:

SELECT item_id,item_name
  FROM item i
INNER JOIN supplier s ON i.item_id=s.items_id
INNER JOIN order O ON O.id=s.req_id
WHERE price>400 AND category='ALL' AND i.item_order_id IS NULL; 

Option 2. Put the condition in the join:

SELECT item_id,item_name
  FROM item i
INNER JOIN supplier s ON i.item_id=s.items_id AND i.item_order_id IS NULL
INNER JOIN order O ON O.id=s.req_id
WHERE price>400 AND category='ALL' ; 
Sign up to request clarification or add additional context in comments.

3 Comments

thanks for reply. How ever,I am using this query inside a function. This join should be happened only if the item_order_id is null. Can't we put this joining inside the where clause ? I means some thing like this, inside the function and in the where clause CASE when item_order_id IS NULL ..
I don't understand what your concern is. Option 2 joins only those records where item_order_id is null. Both options produce the same result. There may be performance issues, so if that is your concern you should check the explain plan for both options (against fully loaded tables).
@KlasLindbäck: no there are no performance issues. The two queries will generate exactly the same plan(s).

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.