Sort by Category, Then Price Descending
Mediumsql
Write a query returning id, name, category, price for every product, sorted by category ascending (A-Z), and within each category by price descending (highest first).
sqlCREATE TABLE products ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, category TEXT NOT NULL, price INTEGER NOT NULL );
Sample data:
sqlINSERT INTO products (id, name, category, price) VALUES (1, 'ProLaptop', 'Electronics', 85000), (2, 'Desk Lamp', 'Home', 900), (3, 'ProPhone', 'Electronics', 45000), (4, 'Python Basics', 'Books', 350), (5, 'Novel', 'Books', 220), (6, 'Headphones', 'Electronics', 3000), (7, 'Rug', 'Home', 4500);
Example 1
Input
(none)
Output
id name category price 4 Python Basics Books 350 5 Novel Books 220 1 ProLaptop Electronics 85000 3 ProPhone Electronics 45000 6 Headphones Electronics 3000 7 Rug Home 4500 2 Desk Lamp Home 900
The second ORDER BY key only breaks ties within the first key's groups. Reference: SELECT id, name, category, price FROM products ORDER BY category ASC, price DESC;