Using CASE Statements for Conditional Logic
CASE statements allow conditional expressions directly within queries.
SELECT customer_id, CASE WHEN amount > 100 THEN 'High' ELSE 'Low' END AS customer_category FROM sales;
MERGE combines INSERT and UPDATE operations to handle conflicts during data upserts.
MERGE INTO customers AS target USING incoming_data AS source ON target.id = source.id WHEN MATCHED THEN UPDATE SET name = source.name WHEN NOT MATCHED THEN INSERT (id, name) VALUES (source.id, source.name);
WINDOW FRAME allows fine-grained control over the rows included in a calculation within a window function.
SELECT order_id, order_date, SUM(amount) OVER (ORDER BY order_date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS rolling_sum FROM orders;
Window Functions perform calculations across a subset of rows (called a "window") that are defined relative to the current row. They allow you to perform operations like ranking, running totals, and differences between rows, all while retaining individual rows in the result set.
SELECT customer_id, purchase_date, amount, SUM(amount) OVER (PARTITION BY customer_id ORDER BY purchase_date) AS running_total FROM purchase_data;