Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to ensure outer join with filter still returns all desired rows?
    primarykey
    data
    text
    <p>Imagine I have two tables in a DB like so:</p> <pre><code>products: product_id name ---------------- 1 Hat 2 Gloves 3 Shoes sales: product_id store_id sales ---------------------------- 1 1 20 2 2 10 </code></pre> <p>Now I want to do a query to list ALL products, and their sales, for store_id = 1. My first crack at it would be to use a left join, and filter to the store_id I want, or a null store_id, in case the product didn't get any sales at store_id = 1, since I want all the products listed:</p> <pre><code>SELECT name, coalesce(sales, 0) FROM products p LEFT JOIN sales s ON p.product_id = s.product_id WHERE store_id = 1 or store_id is null; </code></pre> <p>Of course, this doesn't work as intended, instead I get:</p> <pre><code>name sales --------------- Hat 20 Shoes 0 </code></pre> <p>No Gloves! This is because Gloves did get sales, just not at store_id = 1, so the WHERE clause has filtered them out.</p> <p>How then can I get a list of ALL products and their sales for a specific store?</p> <p>Here are some queries to create the test tables:</p> <pre><code>create temp table test_products as select 1 as product_id, 'Hat' as name; insert into test_products values (2, 'Gloves'); insert into test_products values (3, 'Shoes'); create temp table test_sales as select 1 as product_id, 1 as store_id, 20 as sales; insert into test_sales values (2, 2, 10); </code></pre> <p>UPDATE: I should note that I am aware of this solution:</p> <pre><code>SELECT name, case when store_id = 1 then sales else 0 end as sales FROM test_products p LEFT JOIN test_sales s ON p.product_id = s.product_id; </code></pre> <p>however, it is not ideal... in reality I need to create this query for a BI tool in such a way that the tool can simply add a where clause to the query and get the desired results. Inserting the required store_id into the correct place in this query is not supported by this tool. So I'm looking for other options, if there are any.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload