PostgreSQL Tutorial
Data Types
Querying & Filtering Data
Managing Tables
Modifying Data
Conditionals
Control Flow
Transactions & Constraints
Working with JOINS & Schemas
Roles & Permissions
Working with Sets
Subquery & CTEs
User-defined Functions
Important In-Built Functions
PostgreSQL PL/pgSQL
Variables & Constants
Stored Procedures
Working with Triggers
Working with Views & Indexes
Errors & Exception Handling
The ORDER BY
clause in PostgreSQL is used to sort the rows returned by a SELECT
statement in either ascending or descending order based on one or more columns. It plays a crucial role in retrieving data in a specific order to cater to the requirements of various applications or reports.
SELECT column1, column2, ... FROM table_name [WHERE condition] ORDER BY column1 [ASC | DESC], column2 [ASC | DESC], ...
column1, column2, ...
: The columns by which you want to sort the results.ASC
: Sorts the results in ascending order (default).DESC
: Sorts the results in descending order.Basic Usage:
To retrieve all records from a table named employees
sorted by the last_name
column in ascending order:
SELECT * FROM employees ORDER BY last_name;
Since ASC
is the default, it's optional.
Sorting by Multiple Columns:
To sort by department
first and then by last_name
within each department:
SELECT * FROM employees ORDER BY department, last_name;
Combining Ascending and Descending Order:
If you want to sort by the department
in descending order and then by the last_name
in ascending order:
SELECT * FROM employees ORDER BY department DESC, last_name ASC;
Using Numeric Position:
Instead of using column names, you can use the numeric position of the columns as they appear in the SELECT
statement:
SELECT first_name, last_name, department FROM employees ORDER BY 3, 2;
This sorts the results by the department
(3rd column) and then by last_name
(2nd column).
Performance: The performance of sorting can vary depending on the dataset size and indexes. For faster sorting, it's often beneficial to have an index on the columns used in the ORDER BY
clause.
NULL Values: By default, PostgreSQL treats NULL
values as the highest possible value. Therefore, when sorting in ascending order, NULL
values will appear last. When sorting in descending order, NULL
values will appear first. You can control this behavior with the NULLS FIRST
or NULLS LAST
options.
SELECT * FROM employees ORDER BY department DESC NULLS LAST;
Working with LIMIT
: Often, the ORDER BY
clause is combined with the LIMIT
clause to retrieve only a subset of sorted rows. For example, to get the top 10 highest-paid employees:
SELECT * FROM employees ORDER BY salary DESC LIMIT 10;
In summary, the ORDER BY
clause in PostgreSQL allows you to retrieve rows in a specific order based on one or multiple columns. It provides flexibility in how data is presented and is a fundamental aspect of SQL querying.
How to use ORDER BY in PostgreSQL:
ORDER BY
clause to sort the result set.SELECT column1, column2 FROM your_table ORDER BY column1;
Sorting results in ascending order with ORDER BY in PostgreSQL:
SELECT column1, column2 FROM your_table ORDER BY column1 ASC;
Sorting results in descending order with ORDER BY in PostgreSQL:
SELECT column1, column2 FROM your_table ORDER BY column1 DESC;
ORDER BY multiple columns in PostgreSQL:
SELECT column1, column2, column3 FROM your_table ORDER BY column1, column2;
Using NULLS FIRST and NULLS LAST with ORDER BY in PostgreSQL:
SELECT column1, column2 FROM your_table ORDER BY column1 ASC NULLS FIRST;
Sorting by column position vs. column name in ORDER BY in PostgreSQL:
ORDER BY
clause.SELECT column1, column2 FROM your_table ORDER BY 1, 2;
ORDER BY and LIMIT in PostgreSQL:
ORDER BY
with LIMIT
to retrieve a specific number of sorted rows.SELECT column1, column2 FROM your_table ORDER BY column1 LIMIT 10;
ORDER BY with OFFSET in PostgreSQL:
OFFSET
along with ORDER BY
for pagination.SELECT column1, column2 FROM your_table ORDER BY column1 OFFSET 10 LIMIT 10;
ORDER BY and window functions in PostgreSQL:
ORDER BY
within window functions for analytical queries.SELECT column1, column2, ROW_NUMBER() OVER (ORDER BY column1) AS row_num FROM your_table;
Sorting by expressions with ORDER BY in PostgreSQL:
SELECT column1, column2 FROM your_table ORDER BY column1 * 2;
ORDER BY in subqueries in PostgreSQL:
ORDER BY
.SELECT * FROM ( SELECT column1, column2 FROM your_table ORDER BY column1 ) AS subquery;
ORDER BY with CASE statement in PostgreSQL:
CASE
statement.SELECT column1, column2 FROM your_table ORDER BY CASE WHEN column1 = 'SpecificValue' THEN 1 ELSE 2 END, column1;
Random ordering with ORDER BY in PostgreSQL:
SELECT column1, column2 FROM your_table ORDER BY RANDOM();
ORDER BY and GROUP BY in PostgreSQL:
GROUP BY
.SELECT column1, COUNT(*) FROM your_table GROUP BY column1 ORDER BY COUNT(*) DESC;
Collation and ORDER BY in PostgreSQL:
SELECT column1, column2 FROM your_table ORDER BY column1 COLLATE "en_US";
ORDER BY and aggregate functions in PostgreSQL:
SELECT AVG(column1) AS avg_value FROM your_table ORDER BY avg_value;
ORDER BY with index usage in PostgreSQL:
CREATE INDEX idx_column1 ON your_table(column1); SELECT column1, column2 FROM your_table ORDER BY column1;