Fantastic! So far you have done exercises based on the CTEs with data modifying statements. You may also use
DELETE statements with nested CTEs. Imagine you need to raise prices of all store products by 7 percent, if the average selling price of products in the store is the lowest from among all the stores. Look at the example below.
WITH avg_prices AS (
avg(price) AS avg_price
GROUP BY grocery_store_id
min_avg_prices AS (
MIN(avg_price) AS min_price
SET price = price + price * 0.07
WHERE grocery_store_id IN (
FROM avg_prices ap
JOIN min_avg_prices map
ON ap.avg_price = map.min_price
We construct two nested CTEs. The first uses store id to identify and average product prices for each store. The second CTE selects the minimum average price from those returned by the first.
UPDATE statement we calculate and apply a new product price, increased by 7 percent, to grocery stores whose ids are identified with the lowest average product price.
To obtain ids of grocery stores with the least average prices, we compare
grocery_store_ids to the ids obtained from the subquery. The subquery compares minimal value from the second CTE and average value from first CTE, getting the
grocery_store_id from the first CTE.