EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials PostgreSQL Tutorial PostgreSQL ORDER BY
Secondary Sidebar
PostgreSQL Tutorial
  • Basic
    • What is PostgreSQL
    • PostgreSQL Features
    • How to Install PostgreSQL
    • PostgreSQL Versions
    • PostgreSQL Architecture
    • PostgreSQL GUI
    • Postgres Command-Line
    • PostgreSQL Variables
    • PostgreSQL Data Types
    • PostgreSQL NOT NULL
    • PostgreSQL Integer
    • PostgreSQL Boolean
    • PostgreSQL BIGINT
    • PostgreSQL NULLIF
    • PostgreSQL Administration
    • PostgreSQL Commands
    • PostgreSQL Operators
    • PostgreSQL IN Operator
    • Postgres like query
    • PostgreSQL encode
    • PostgreSQL Cheat Sheet
    • PostgreSQL List Databases
    • PostgreSQL Rename Database
  • Control Statement
    • PostgreSQL IF Statement
    • PostgreSQL if else
    • PostgreSQL CASE Statement
    • PostgreSQL LOOP
    • PostgreSQL For Loop
    • PostgreSQL While Loop
  • Joins
    • Joins in PostgreSQL
    • PostgreSQL Inner Join
    • PostgreSQL Outer Join
    • LEFT OUTER JOIN in PostgreSQL
    • PostgreSQL FULL OUTER JOIN
    • PostgreSQL LEFT JOIN
    • PostgreSQL Full Join
    • PostgreSQL Cross Join
    • PostgreSQL NATURAL JOIN
    • PostgreSQL UPDATE JOIN
  • Queries
    • PostgreSQL Queries
    • PostgreSQL INSERT INTO
    • PostgreSQL WHERE Clause
    • PostgreSQL WITH Clause
    • PostgreSQL ORDER BY
    • PostgreSQL ORDER BY Random
    • PostgreSQL ORDER BY DESC
    • PostgreSQL GROUP BY
    • PostgreSQL group_concat
    • PostgreSQL HAVING
    • PostgreSQL Recursive Query
  • Advanced
    • PostgreSQL Schema
    • Postgres List Schemas
    • PostgreSQL Drop Schema
    • PostgreSQL VARCHAR
    • Array in PostgreSQL
    • PostgreSQL DDL
    • PostgreSQL List Users
    • Postgres Default User
    • Postgres add user
    • PostgreSQL User Password
    • PostgreSQL log_statement
    • PostgreSQL repository
    • PostgreSQL shared_buffer
    • PostgreSQL String Functions
    • PostgreSQL Compare Strings
    • PostgreSQL Text Search
    • PostgreSQL TEXT
    • PostgreSQL String Array
    • PostgreSQL where in array
    • PostgreSQL Constraints
    • PostgreSQL UNIQUE Constraint
    • PostgreSQL CHECK Constraint
    • PostgreSQL INTERSECT
    • PostgreSQL Like
    • Cursors in PostgreSQL
    • PostgreSQL UNION ALL
    • Indexes in PostgreSQL
    • PostgreSQL Index Types
    • PostgreSQL REINDEX
    • PostgreSQL UNIQUE Index
    • PostgreSQL Clustered Index
    • PostgreSQL DROP INDEX
    • PostgreSQL DISTINCT
    • PostgreSQL FETCH
    • PostgreSQL RAISE EXCEPTION
    • PostgreSQL Auto Increment
    • Sequence in PostgreSQL
    • Wildcards in PostgreSQL
    • PostgreSQL Subquery
    • PostgreSQL Alias
    • PostgreSQL LIMIT
    • PostgreSQL Limit Offset
    • PostgreSQL LAG()
    • PostgreSQL Table
    • Postgres Show Tables
    • PostgreSQL Describe Table
    • PostgreSQL Lock Table
    • PostgreSQL ALTER TABLE
    • Postgres Rename Table
    • PostgreSQL List Tables
    • PostgreSQL TRUNCATE TABLE
    • PostgreSQL Table Partitioning
    • Postgres DROP Table
    • PostgreSQL Functions
    • PostgreSQL Math Functions
    • PostgreSQL Window Functions
    • Aggregate Functions in PostgreSQL
    • PostgreSQL Primary Key
    • Foreign Key in PostgreSQL
    • PostgreSQL Procedures
    • PostgreSQL Stored Procedures
    • PostgreSQL Views
    • PostgreSQL Materialized Views
    • Postgres Create View
    • PostgreSQL Triggers
    • PostgreSQL DROP TRIGGER
    • PostgreSQL Date Functions
    • PostgreSQL TO_DATE()
    • PostgreSQL datediff
    • PostgreSQL Timestamp
    • PostgreSQL CURRENT_TIMESTAMP()
    • PostgreSQL Notify
    • PostgreSQL LENGTH()
    • PostgreSQL blob
    • PostgreSQL Median
    • PostgreSQL kill query
    • PostgreSQL Formatter
    • PostgreSQL RANK()
    • PostgreSQL Select
    • PostgreSQL Average
    • PostgreSQL DATE_PART()
    • PostgreSQL EXECUTE
    • PostgreSQL COALESCE
    • PostgreSQL EXTRACT()
    • PostgreSQL Sort
    • PostgreSQL TO_CHAR
    • PostgreSQL Interval
    • PostgreSQL Number Types
    • PostgreSQL ROW_NUMBER
    • Alter Column in PostgreSQL
    • PostgreSQL Identity Column
    • PostgreSQL SPLIT_PART()
    • PostgreSQL CONCAT()
    • PostgreSQL replace
    • PostgreSQL TRIM()
    • PostgreSQL MAX
    • PostgreSQL DELETE
    • PostgreSQL Float
    • PostgreSQL OID
    • PostgreSQL log
    • PostgreSQL REGEXP_MATCHES()
    • PostgreSQL MD5 
    • PostgreSQL NOW()
    • PostgreSQL RANDOM
    • PostgreSQL round
    • PostgreSQL Trunc()
    • PostgreSQL TIME
    • PostgreSQL IS NULL
    • PostgreSQL CURRENT_TIME
    • PostgreSQL MOD()
    • Postgresql Count
    • PostgreSQL Datetime
    • PostgreSQL MIN()
    • PostgreSQL age()
    • PostgreSQL enum
    • PostgreSQL OR
    • PostgreSQL Wal
    • PostgreSQL NOT IN
    • PostgreSQL SET
    • PostgreSQL Current Date
    • PostgreSQL Compare Date
    • PostgreSQL SERIAL
    • PostgreSQL UUID
    • PostgreSQL Merge
    • PostgreSQL Database
    • PostgreSQL Clone Database
    • PostgreSQL Copy Database
    • PostgreSQL Show Databases
    • PostgreSQL Restore Database
    • PostgreSQL DROP DATABASE
    • PostgreSQL ALTER DATABASE
    • Postgres DROP Database
    • Postgres Dump Database
    • PostgreSQL OFFSET
    • PostgreSQL GRANT
    • PostgreSQL COMMIT
    • PostgreSQL ROLLUP
    • PostgreSQL JSON
    • EXPLAIN ANALYZE in PostgreSQL
    • PostgreSQL Temporary Table
    • PostgreSQL Show Tables
    • PostgreSQL cluster
    • PostgreSQL Replication
    • PostgreSQL Logical Replication
    • PostgreSQL flush privileges
    • PostgreSQL Tablespaces
    • CAST in PostgreSQL
    • PostgreSQL CTE
    • hstore in PostgreSQL
    • PostgreSQL Encryption
    • PostgreSQL DECODE()
    • PostgreSQL Vacuum
    • PostgreSQL EXCLUDE
    • Postgres Change Password
    • Postgres Delete Cascade
    • PostgreSQL EXCEPT
    • PostgreSQL Roles
    • PostgreSQL Link
    • PostgreSQL Partition
    • PostgreSQL column does not exist
    • PostgreSQL Log Queries
    • PostgreSQL escape single quote
    • PostgreSQL Query Optimization
    • PostgreSQL Character Varying
    • PostgreSQL Transaction
    • PostgreSQL Extensions
    • PostgreSQL Import CSV
    • PostgreSQL Client
    • PostgreSQL caching
    • PostgreSQL Incremental Backup
    • PostgreSQL JSON vs JSONNB
    • PostgreSQL JDBC Driver
    • PostgreSQL Interview Questions

PostgreSQL ORDER BY

PostgreSQL-ORDER-BY

Introduction to PostgreSQL ORDER BY

When we receive data from a table using a select query, it will return a row in an unspecified order. To sort this data using specified order, we need to use order by clause in the select query to retrieve data from a table; we have to use ASC or DESC order to sort data in the specified order; this clause is used to sort data in ascending and descending order in PostgreSQL. We can use one or more column in order by clause to sort data in ascending or descending order, but we make sure that this column is present in that table.

Syntax:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

This clause specifies the sort order of data in a specific order.

SELECTcolumn-list (list of columns)
FROM table_name (name of table)
[WHERE condition] [ORDER BY column1, column2, …, columnN (name of columns)] [ASC | DESC];

SELECT* (list of columns)
FROM table_name (name of table from we retrieving data)
[WHERE condition] [ORDER BY column1, column2, …, columnN (name of columns)] [ASC | DESC];

Select expressions (column list)
From table_name (name of table)
[WHERE condition] [ORDER BY expression (name of column) [ASC | DESC | Using operator] [NULLS FIRST | NULLS LAST];

Below are the parameter description of the above syntax are as follows:

  • Column list: List of columns name from which we have retrieving data.
  • Asterisk (*): All columns from the table that we have retrieving data.
  • Table name: This specifies the table name from which we have retrieving data. There must be at least one name we have to mention in from clause.
  • Where condition: Where specifies that the specific condition needs to be fulfilled to retrieving data from the table. Where the condition is optional in order by clause.
  • ASC (Ascending): This is an optional clause in PostgreSQL order by clause. It will sort the result by ascending order.
  • DESC (Descending): This is an optional clause in PostgreSQL order by clause. It will sort the result by descending order.
  • Nulls first: It will sort all null values before non-nulls in PostgreSQL order by clause result set. This is an optional clause in PostgreSQL order by clause.
  • Nulls last: It will sort all null values after non-nulls in PostgreSQL order by clause result set. This is an optional clause.

How ORDER BY Function works in PostgreSQL?

  • Normally without using order by function in PostgreSQL, data retrieve in an unspecified order.
  • Using order by function in PostgreSQL, our data comes in the specified order. We have used the ASC function to sort data in ascending order.
  • Also, the DESC function is available in PostgreSQL to sort data in descending order.
  • We have used the column name in the order by clause to sort data in our query’s specified order.
  • We have also used multiple column names in a single query to fetch sorted data from the table.
  • This clause is also used without specifying the ASC and DESC function in our query. Suppose we have not provided ASC and DESC function in order by clause our result sorted by using ascending order.
  • The default sequence is ascending order that will return the smallest value first. If suppose in some situations two rows are equal, they compare with each other using the expressions. If rows are the same by using the expression, then the output of the result set depends on the implementation of expressions.
  • In this clause, it is not mandatory that add ASC or DESC after any expressions.
  • In this clause, null value sorts will higher than the other value sorts.
  • In this clause, two operators are used with the help of order by clause with using the keyword to retrieve the result set in ascending or descending order.

Example on Order By In PostgreSQL

We have used the employee table to describe an example of the order by clause in PostgreSQL. Please find below an example of the order by clause in PostgreSQL.

Example #1

Create an employee table to describe order by clause in PostgreSQL.

Code:

CREATE TABLE Employee ( emp_id INT NOT NULL, emp_name character(10) NOT NULL, emp_address character(20) NOT NULL, emp_phone character(14), PRIMARY KEY (emp_id));

Output:

postgreSQL OUTPUT 1

Code:

INSERT INTO Employee (emp_id, emp_name, emp_address, emp_phone) VALUES (1, 'ABC', 'Pune', '1234567890');
INSERT INTO Employee (emp_id, emp_name, emp_address, emp_phone) VALUES (2, 'PQR', 'Pune', '1234567890');
INSERT INTO Employee (emp_id, emp_name, emp_address, emp_phone) VALUES (3, 'XYZ', 'Mumbai', '1234567890');
INSERT INTO Employee (emp_id, emp_name, emp_address, emp_phone) VALUES (4, 'BBS', 'Mumbai', '1234567890');
INSERT INTO Employee (emp_id, emp_name, emp_address, emp_phone) VALUES (5, 'RBS', 'Delhi', '1234567890');

Output:

insert employee

Example #2

Order By Clause to sort rows with a single column.

Code:

SELECT emp_id, emp_name, emp_address from employee order by emp_name ASC;

Output:

postgreSQL ORDERBY 3

Code:

SELECT emp_id, emp_name, emp_address from employee order by emp_name DESC;

Output:

sort rows with single column

Example #3

Order By Clause to sort rows with multiple columns.

Code:

SELECT emp_id, emp_name, emp_address from employee order by emp_name ASC, emp_id DESC;

Output:

postgreSQL ORDERBY 5

SELECT emp_id, emp_name, emp_address from employee order by emp_name DESC, emp_id ASC;

Output:

sort rows with multiple columns

Example #4

Order By Clause to sort rows with expressions.

Code:

SELECT emp_id, LENGTH(emp_address) emp_address, emp_name from employee order by length(emp_address) DESC;

Output:

postgreSQL ORDERBY 8

Code:

SELECT emp_id, LENGTH(emp_address) emp_address, emp_name from employee order by length(emp_address) ASC;

Output:

postgreSQL ORDERBY 9

Example #5

PostgreSQL order by clause to sort rows with using clause.

Code:

SELECT emp_id, emp_name, emp_address from employee order by emp_id USING>;

Output:

postgreSQL ORDERBY 10

Code:

SELECT emp_id, emp_name, emp_address from employee order by emp_id USING<;

Output:

postgreSQL ORDERBY 11

Conclusion

PostgreSQL ORDER BY clause sorting is based on ascending or descending order. We can use single or multiple columns in the query to retrieve data in sorted order. This clause will retrieve data in ascending order by default if we have not defined any sorting function in a query.

Recommended Articles

This has been a guide to PostgreSQL ORDER BY. Here we discuss the introduction and how the ORDER BY function works in PostgreSQL. You may also have a look at the following articles to learn more –

  1. ORDER BY in Oracle
  2. PowerShell String Functions
  3. Hive String Functions
  4. Data Warehouse tools
  5. How to Create Indexes in PostgreSQL?
  6. Examples of PostgreSQL Triggers
  7. How to Create PostgreSQL Views?
Popular Course in this category
PostgreSQL Course (2 Courses, 1 Project)
  2 Online Courses |  1 Hands-on Project |  7+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2023 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more