Get Top 10 rows in PostgreSQL (Top N Rows)

To retrieve the top 10 rows from a table in PostgreSQL, you can use the LIMIT clause in your SQL query. To Retrieve first N records in PostgreSQL we will be using limit keyword. Let’s see how to get top 10 rows in PostgreSQL and Get First N rows in PostgreSQL.

We will depict the usage of limit clause with examples

 

Table name : Employee_op

Get Top 10 rows in PostgreSQL (Top N Rows) 1

 

 

Basic Usage with LIMIT : Get First N rows in Postgresql:

 

SELECT * FROM employee_op LIMIT 10;

Gets first 10 rows from the table as shown below

Output:

Get Top 10 rows in PostgreSQL (Top N Rows) 2

 

Get Top N rows in PostgreSQL:

The LIMIT clause restricts the number of rows returned by the query to the specified number. You can also combine LIMIT with ORDER BY to specify the criteria for the top rows.

Example: Top 10 Highest Salaries

SELECT *FROM employees_op ORDER BY salary DESCLIMIT 10;

This query returns the top 10 rows from the employees table ordered by the salary column in descending order, so you get the employees with the highest salaries.

Output:

Get Top 10 rows in PostgreSQL (Top N Rows) 3

 

 

Example: Top 10 Most Recent Hires
 

SELECT *FROM employees_opORDER BY hired_date DESCLIMIT 10;

This query returns the top 10 rows from the employees table ordered by the hired_date column in descending order, so you get the most recently hired employees.

Output:

Get Top 10 rows in PostgreSQL (Top N Rows) 4

 

Author

  • Sridhar Venkatachalam

    With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark.

    View all posts