⬅ Previous Topic
SQL WHERE ClauseNext Topic ⮕
GROUP BY Clause in SQL⬅ Previous Topic
SQL WHERE ClauseNext Topic ⮕
GROUP BY Clause in SQLWhen you run a SQL query, the results may seem... a bit random. But what if you want to see students in alphabetical order, or arrange marks from highest to lowest? That’s where ORDER BY
steps in — a simple yet powerful clause that helps you control the order of your output.
SELECT column1, column2, ...
FROM table_name
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;
We’ll work with the following data:
CREATE TABLE students (
roll_no INT PRIMARY KEY,
name VARCHAR(50),
class VARCHAR(10),
age INT,
city VARCHAR(30)
);
INSERT INTO students VALUES
(1, 'Aarav Sharma', '10A', 15, 'Delhi'),
(2, 'Diya Iyer', '9B', 14, 'Chennai'),
(3, 'Rohit Menon', '10A', 15, 'Kochi'),
(4, 'Sneha Patil', '8C', 13, 'Pune'),
(5, 'Mehul Agarwal', '9B', 14, 'Delhi');
List students by age in ascending order:
SELECT name, age FROM students
ORDER BY age;
name | age
---------------+-----
Sneha Patil | 13
Diya Iyer | 14
Mehul Agarwal | 14
Aarav Sharma | 15
Rohit Menon | 15
Now let’s flip the order and sort by age descending:
SELECT name, age FROM students
ORDER BY age DESC;
name | age
---------------+-----
Aarav Sharma | 15
Rohit Menon | 15
Diya Iyer | 14
Mehul Agarwal | 14
Sneha Patil | 13
Sort student names in A-Z order:
SELECT name, class FROM students
ORDER BY name;
Let’s say you want to sort by class first, and then by name within each class:
SELECT name, class FROM students
ORDER BY class, name;
name | class
----------------+-------
Sneha Patil | 8C
Diya Iyer | 9B
Mehul Agarwal | 9B
Aarav Sharma | 10A
Rohit Menon | 10A
You can sort one column ascending and another descending. For example, sort by class (ascending), but age (descending):
SELECT name, class, age FROM students
ORDER BY class ASC, age DESC;
You can combine ORDER BY with WHERE to filter and then sort:
SELECT name, age FROM students
WHERE age >= 14
ORDER BY name;
You can technically sort using column numbers from the SELECT clause, but it’s risky and non-descriptive:
SELECT name, age FROM students
ORDER BY 2 DESC;
Better to use explicit column names for clarity.
The ORDER BY
clause brings structure and sense to your result sets. Whether you're ranking top students, grouping city-wise attendance, or alphabetizing names for reports — this clause transforms chaos into clarity.
Now that your data is sorted and structured, it's time to explore the LIMIT clause — a way to fetch only the top results from a large dataset.
SELECT name, marks FROM students ORDER BY marks DESC;
⬅ Previous Topic
SQL WHERE ClauseNext Topic ⮕
GROUP BY Clause in SQLYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.