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
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 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:
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: