ORDER BY and DISTINCT
In any e-commerce application, users have the option of sorting the products based on price, rating, etc. Also, for any product, users could know all the distinct brands available for the product. Let's learn how to retrieve such ordered results and unique data!
Database The database contains a
product
table that stores the data of products like name, category, price, brand and rating.
You can check the schema and data ofproduct
table in the code playground.ORDER BY
We use
ORDER BY
clause to order rows. By default,ORDER BY
sorts the data in theascending order
.Syntax
SQL
Example
Get all products in the order of lowest
price
and highestrating
in "Puma" brand.SQL
Output
name | price | rating |
---|---|---|
Black Shirt | 600 | 4.8 |
Blue Jeans | 800 | 3.6 |
Blue Shirt | 1000 | 4.3 |
Try it Yourself!
Get all the shirts from
producttable in the descending order of theirratingand in the ascending order ofprice.Note: Assusme the products as shirts, if the
namecontains "Shirt".
DISTINCT
DISTINCT
clause is used to return the distinct i.e unique values.Syntax
SQL
Example
- Get all the brands present in theproducttable.
SQL
Output
Brand |
---|
Absa |
Apple |
... |
Try it Yourself!
- Get a list of distinct categories available in theproducttable
View Schema
name | category | price | brand | rating |
---|---|---|---|---|
Blue Shirt | Clothing | 750 | Denim | 3.8 |
Blue Jeans | Clothing | 800 | Puma | 3.6 |
Black Jeans | Clothing | 750 | Denim | 4.5 |
Blue Shirt | Clothing | 1000 | Puma | 4.3 |
Chocolate Cake | Food | 25 | Britannia | 3.7 |
Strawberry Cake | Food | 60 | Cadbury | 4.1 |
Chocolate Cake | Food | 60 | Cadbury | 2.5 |
Strawberry Cake | Food | 10 | Britannia | 4.6 |
Smart Watch | Gadgets | 17000 | Apple | 4.9 |
Smart Cam | Gadgets | 2600 | Realme | 4.7 |
Smart TV | Gadgets | 40000 | Sony | 4 |
Bourbon Small | Food | 10 | Britannia | 3.9 |
Bourbon Special | Food | 15 | Britannia | 4.6 |
Bourbon With Extra Cookies | Food | 30 | Britannia | 4.4 |
White Shirt | Clothing | 700 | Denim | 4.3 |
Black Shirt | Clothing | 600 | Puma | 4.8 |
Black T-Shirt | Clothing | 600 | Roadster | 4.2 |
White T-Shirt | Clothing | 700 | Levi's | 4 |
Blue T-Shirt | Clothing | 600 | Nike | 4.7 |
Realme Smart Band | Gadgets | 3000 | Realme | 4.6 |
Raw Cashew | Food | 370 | Absa | 3.9 |
Cashew Nuts | Food | 550 | Upcrop | 4.3 |
Chocolate Cashew | Food | 670 | Urban Platter | 3.5 |
Potato Chips India’s Magic Masala | Food | 42 | Lay's | 4.4 |
Banana Chips | Food | 550 | Calicut Kerala | 4.3 |
Potato Chips Cream & onion | Food | 63 | Lay's | 4.5 |
Potato Chips Classic Salted | Food | 45 | Lay's | 4 |
Harry Potter and the Philosopher's Stone | Novel | 222 | 4.7 | |
Harry Potter and the Chamber of Secrets | Novel | 343 | 4.4 | |
Harry Potter and the Prisoner of Azkaban | Novel | 284 | 4.2 | |
Harry Potter and the Goblet of Fire | Novel | 431 | 4.6 | |
OnePlus 6T | Smartphone | 32990 | OnePlus | 4.5 |
Redmi K20 | Smartphone | 24999 | Redmi | 4.1 |