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', 'catalog_returns']. Below is the join graph for these fact tables: ['web_sales(ws_bill_addr_sk) references customer_address(ca_address_sk);', 'web_sales(ws_ship_addr_sk) references customer_address(ca_address_sk);', 'web_sales(ws_bill_cdemo_sk) references customer_demographics(cd_demo_sk);'] ['catalog_returns(cr_returning_addr_sk) references customer_address(ca_address_sk);', 'catalog_returns(cr_reason_sk) references reason(r_reason_sk);', 'catalog_returns(cr_returning_customer_sk) references customer(c_customer_sk);']
- The original query must employ 4 joins.
- The original query must employ the following aggregate functions: ['avg', 'sum', 'count'].
- The original query must employ the following operators in its WHERE clause: ['min', 'sum', 'avg'].
- 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
Certainly! Below is an original and rewritten SQL query pair, based on your specifications and using a similar rewrite approach as described in the demonstration:
[ORIGINAL QUERY]
SELECT w.ws_sold_time_sk, AVG(w.ws_sales_price) AS avg_price, SUM(w.ws_ext_discount_amt) AS total_discount, COUNT(*) AS num_sales FROM web_sales w JOIN customer_address ca ON w.ws_bill_addr_sk = ca.ca_address_sk JOIN customer_demographics cd ON w.ws_bill_cdemo_sk = cd.cd_demo_sk JOIN catalog_returns cr ON w.ws_item_sk = cr.cr_item_sk JOIN customer c ON cr.cr_returning_customer_sk = c.c_customer_sk WHERE w.ws_net_paid > (SELECT MIN(w1.ws_net_paid) FROM web_sales w1) AND w.ws_sales_price > (SELECT SUM(w2.ws_sales_price) FROM web_sales w2 WHERE w2.ws_sold_date_sk = w.ws_sold_date_sk) AND cr.cr_refunded_cash > (SELECT AVG(cr1.cr_fee) FROM catalog_returns cr1) GROUP BY w.ws_sold_time_sk;