You are a database expert and SQL optimizer. You will be given a SQL query and its…
- User
You are a database expert and SQL optimizer. You will be given a SQL query and its rewritten variant. The rewritten query improves performance upon the original while maintaining equivalence. Your task is to create a new pair of original and rewritten queries that invoke a similar rewrite.
[ORIGINAL QUERY]
SELECT c.* FROM customer c WHERE c.address_id IN (SELECT a.address_id FROM address) and c.address_id in (SELECT a.address_id FROM address WHERE a.pin_code = '560012');[REWRITTEN QUERY]
SELECT c.* FROM customer c WHERE c.address_id IN (SELECT a.address_id FROM address WHERE a.pin_code = '560012');Now, consider the TPC-DS schema and create a new original and equivalent rewritten query pair such that the rewrite operation is similar to the provided demonstration.Keep the following points in mind while creating the new query pair:
- The original query must not have any CTEs.
- The original query must make use of the following fact tables: ['web_sales', 'store_sales']. Below is the join graph for these fact tables: ['web_sales(ws_promo_sk) references promotion(p_promo_sk);', 'web_sales(ws_sold_time_sk) references time_dim(t_time_sk);', 'web_sales(ws_ship_hdemo_sk) references household_demographics(hd_demo_sk);'] ['store_sales(ss_hdemo_sk) references household_demographics(hd_demo_sk);', 'store_sales(ss_item_sk) references item(i_item_sk);', 'store_sales(ss_store_sk) references store(s_store_sk);']
- The original query must employ 2 joins.
- The original query must employ the following aggregate functions: ['avg', 'sum'].
- The original query must employ the following operators in its WHERE clause: [].
- The rewritten query must be equivalent to the original query, and must follow a similar rewrite pattern as in the given example. Enclose the original and rewritten queries within
and.
- Assistant
Here is a new pair of original and rewritten queries based on the provided criteria and rewrite pattern:
[ORIGINAL QUERY]
sqlSELECT ss.store_sk, AVG(ss.sales_price) AS avg_sales_price, SUM(ss.quantity) AS total_quantity FROM store_sales ss JOIN item i ON ss.ss_item_sk = i.i_item_sk JOIN promotion p ON ss.ss_promo_sk = p.p_promo_sk WHERE ss.store_sk IN ( SELECT s.store_sk FROM store s WHERE EXISTS (SELECT hd.hd_demo_sk FROM household_demographics hd WHERE hd.hd_income_band_sk = s.store_income_band_sk) ) AND ss.store_sk IN ( SELECT s.store_sk FROM store s WHERE s.store_country = 'USA' ) GROUP BY ss.store_sk;