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

PostgreSQL - ORDER BY clause

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.

Syntax:

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.

Examples:

  1. 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.

  2. 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;
    
  3. 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;
    
  4. 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).

Notes:

  • 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.

  1. How to use ORDER BY in PostgreSQL:

    • Use the ORDER BY clause to sort the result set.
    SELECT column1, column2
    FROM your_table
    ORDER BY column1;
    
  2. Sorting results in ascending order with ORDER BY in PostgreSQL:

    • Sort the result set in ascending order.
    SELECT column1, column2
    FROM your_table
    ORDER BY column1 ASC;
    
  3. Sorting results in descending order with ORDER BY in PostgreSQL:

    • Sort the result set in descending order.
    SELECT column1, column2
    FROM your_table
    ORDER BY column1 DESC;
    
  4. ORDER BY multiple columns in PostgreSQL:

    • Sort the result set based on multiple columns.
    SELECT column1, column2, column3
    FROM your_table
    ORDER BY column1, column2;
    
  5. Using NULLS FIRST and NULLS LAST with ORDER BY in PostgreSQL:

    • Control the placement of NULL values in the sort order.
    SELECT column1, column2
    FROM your_table
    ORDER BY column1 ASC NULLS FIRST;
    
  6. Sorting by column position vs. column name in ORDER BY in PostgreSQL:

    • Specify the column position or column name in the ORDER BY clause.
    SELECT column1, column2
    FROM your_table
    ORDER BY 1, 2;
    
  7. ORDER BY and LIMIT in PostgreSQL:

    • Combine ORDER BY with LIMIT to retrieve a specific number of sorted rows.
    SELECT column1, column2
    FROM your_table
    ORDER BY column1
    LIMIT 10;
    
  8. ORDER BY with OFFSET in PostgreSQL:

    • Use OFFSET along with ORDER BY for pagination.
    SELECT column1, column2
    FROM your_table
    ORDER BY column1
    OFFSET 10
    LIMIT 10;
    
  9. ORDER BY and window functions in PostgreSQL:

    • Apply ORDER BY within window functions for analytical queries.
    SELECT column1, column2, ROW_NUMBER() OVER (ORDER BY column1) AS row_num
    FROM your_table;
    
  10. Sorting by expressions with ORDER BY in PostgreSQL:

    • Sort the result set based on expressions.
    SELECT column1, column2
    FROM your_table
    ORDER BY column1 * 2;
    
  11. ORDER BY in subqueries in PostgreSQL:

    • Sort the results of a subquery using ORDER BY.
    SELECT *
    FROM (
       SELECT column1, column2
       FROM your_table
       ORDER BY column1
    ) AS subquery;
    
  12. ORDER BY with CASE statement in PostgreSQL:

    • Customize the sort order using a CASE statement.
    SELECT column1, column2
    FROM your_table
    ORDER BY CASE WHEN column1 = 'SpecificValue' THEN 1 ELSE 2 END, column1;
    
  13. Random ordering with ORDER BY in PostgreSQL:

    • Randomly order the result set.
    SELECT column1, column2
    FROM your_table
    ORDER BY RANDOM();
    
  14. ORDER BY and GROUP BY in PostgreSQL:

    • Sort groups when using GROUP BY.
    SELECT column1, COUNT(*)
    FROM your_table
    GROUP BY column1
    ORDER BY COUNT(*) DESC;
    
  15. Collation and ORDER BY in PostgreSQL:

    • Use collation to control string sorting behavior.
    SELECT column1, column2
    FROM your_table
    ORDER BY column1 COLLATE "en_US";
    
  16. ORDER BY and aggregate functions in PostgreSQL:

    • Sort the result set based on aggregate function results.
    SELECT AVG(column1) AS avg_value
    FROM your_table
    ORDER BY avg_value;
    
  17. ORDER BY with index usage in PostgreSQL:

    • Leverage indexes for efficient sorting.
    CREATE INDEX idx_column1 ON your_table(column1);
    SELECT column1, column2
    FROM your_table
    ORDER BY column1;