</>
Skip to content
PostgreSQL lessons (16/38)

PostgreSQL — Order By

Basic Order By

SELECT * FROM users ORDER BY name;
SELECT * FROM users ORDER BY name ASC;
SELECT * FROM users ORDER BY name DESC;

Multiple Columns

SELECT * FROM users ORDER BY country ASC, name ASC;

By Expression

SELECT * FROM products ORDER BY price * quantity DESC;

By Column Number

SELECT name, age FROM users ORDER BY 2 DESC;

NULLS Handling

SELECT * FROM users ORDER BY email NULLS FIRST;
SELECT * FROM users ORDER BY email NULLS LAST;

Random Order

SELECT * FROM users ORDER BY RANDOM();

With LIMIT

SELECT * FROM products ORDER BY price DESC LIMIT 5;

Case-Sensitive

-- Case-sensitive
SELECT * FROM users ORDER BY name;

-- Case-insensitive
SELECT * FROM users ORDER BY LOWER(name);

Mini Practice

  1. Sort ascending
  2. Sort descending
  3. Sort by multiple columns
  4. Handle NULL values

Up Next

Continue with Group By — grouping results.

Related Topics

Frequently Asked Questions about Order By

What is Order By in PostgreSQL?

Order By is a fundamental concept in PostgreSQL. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Order By?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Order By.

Why is Order By important in PostgreSQL?

Order By is essential for PostgreSQL development. Understanding this concept will help you write better code and solve real-world problems more effectively.