Using GREATEST and LEAST Functions in PostgreSQL
📖 Scenario: You work in a small company that tracks monthly sales for three products. You want to find the highest and lowest sales values for each month to understand which product performed best and worst.
🎯 Goal: Create a table with monthly sales data for three products. Then write a query using the GREATEST and LEAST functions to find the highest and lowest sales for each month.
📋 What You'll Learn
Create a table named
monthly_sales with columns month (text), product_a (integer), product_b (integer), and product_c (integer).Insert exactly three rows with sales data for January, February, and March.
Write a SELECT query that includes the original columns plus two new columns:
highest_sale using GREATEST and lowest_sale using LEAST.Ensure the query returns all rows with correct highest and lowest sales values per month.
💡 Why This Matters
🌍 Real World
Companies often compare multiple product sales to identify best and worst performers each month.
💼 Career
Knowing how to use GREATEST and LEAST helps data analysts quickly summarize and compare multiple columns in reports.
Progress0 / 4 steps