Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Order By Limit in SQL

Order By Limit in SQL

ORDER BY with LIMIT in SQL

The ORDER BY clause sorts the result set, and the LIMIT clause restricts the number of rows returned. Together, they are often used to get the top N records based on a certain order.


? Syntax:

SELECT column1, column2, ...FROM table_nameORDER BY column_name [ASC | DESC]LIMIT number_of_rows;
  • ORDER BY sorts the results.

  • LIMIT restricts output to the specified number of rows.


? Example:

Get the top 5 highest paid employees:

SELECT employee_name, salaryFROM employeesORDER BY salary DESCLIMIT 5;

This returns the 5 employees with the highest salaries.


Example with ascending order:

Get the 3 earliest events:

SELECT event_name, event_dateFROM eventsORDER BY event_date ASCLIMIT 3;

Notes:

  • LIMIT syntax works in MySQL, PostgreSQL, SQLite.

  • In SQL Server, use TOP instead:

SELECT TOP 5 employee_name, salaryFROM employeesORDER BY salary DESC;
  • In Oracle, use FETCH FIRST syntax (12c+):

SELECT employee_name, salaryFROM employeesORDER BY salary DESCFETCH FIRST 5 ROWS ONLY;

Want me to show how to paginate results using ORDER BY and LIMIT?

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql