SQL ORDER BY Tutorial

SQL Tutorial: ORDER BY with Example

Deepen your understanding of SQL commands and their real-world applications in managing databases. Learn how the ORDER BY keyword can be utilized to sort data based on specific columns in either ascending or descending order.

Key Insights

  • The ORDER BY keyword in SQL is essential in sorting data contained in tables.
  • It allows the user to sort data based on specific columns, making it easier to analyze or present.
  • The command for using ORDER BY incorporates a selection from the table, followed by ORDER BY and the specific column, often ending with either DESC or ASC to denote the sorting order.
  • An example presented involves a basketball league with player records and statistics.
  • Using an SQL query with ORDER BY, one can easily find the top rebounders in the league.
  • After running the query, the result presents the data sorted according to the specified order, showcasing how efficient and effective the ORDER BY keyword is in SQL.

How ORDER BY Works

  • Sorts Result Rows

    Sorts the data based on a specific column or columns.

  • ASC vs DESC

    DESC for descending (top scorers first); default is ASC ascending.

  • Syntax

    SELECT * FROM table ORDER BY column_1 DESC;

  • Multi-Column Sort

    ORDER BY team ASC, points DESC sorts by team then by points within each team.

ORDER by

  • The ORDER BY keyword is used to sort data in our table.

  • ORDER BY sorts data based on a specific column(s) in either ascending or descending order.

  • Syntax: SELECT * FROM table ORDER BY column_1 DESC ;

Example

Let’s say we have a basketball league and we keep records of each player, which team they are on, and their basic statistics.

Stats Table

If we wanted to use a SQL query to find the top rebounders, we would write the following:

SQL Bootcamp: Live & Hands-on, In NYC or Online, Learn From Experts, Free Retake, Small Class Sizes,  1-on-1 Bonus Training. Named a Top Bootcamp by Forbes, Fortune, & Time Out. Noble Desktop. Learn More.

SQL ORDER BY

Once we hit ENTER and run, our result should be as follows:

SQL ORDER BY Result

Learn more in these courses

How to Learn SQL

Master SQL with hands-on training. SQL is one of the most in-demand programming languages and is used across a variety of professions.

Yelp Facebook LinkedIn YouTube Twitter Instagram