SQL ORDER BY: output sorteren [TUTORIAL] (2024)

Wie gegevens opvraagt uit relationele databases met SQL zal vaak de behoefte hebben om de output op een bepaalde manier te ordenen. Als je veel data opvraagt met een SQL query dan kan de output namelijk onoverzichtelijk worden en daarmee lastig te interpreteren.

In dit blog gaan we in op de SQL ORDER BY clause, waarmee je output in oplopende of aflopende volgorde sorteert.

Wil je op je eigen computer meedoen met deze tutorial? Volg dan deze stappen om SQL en PgAdmin te installeren. Ook de database die we gebruiken in dit blog download je op voorgaande installatiepagina.

Inhoud

  • Wat is de SQL ORDER BY clause?
  • Voorbeeldtoepassingen van SQL ORDER BY

Wat is SQL ORDER BY?

Binnen SQL gebruik je ORDER BY om output te sorteren. Je hebt de mogelijkheid om op één of meerdere columns te sorteren, zowel oplopend als aflopend.

Verschillende versies van SQL kunnen bij dezelfde query een andere volgorde in de output geven. Dit maakt het ordenen van je output nog belangrijker omdat het resultaat van een query anders erg verwarrend kan zijn.

De syntax heeft de volgende structuur: SELECT kolom1, kolom2 FROM tabel ORDER BY kolom1 ASC|DESC, kolom2 ASC|DESC;

Met ASC (ascending oftewel oplopend) of DESC (descending oftewel aflopend) geef je aan hoe je je output wilt sorteren. Als je niet aangeeft hoe je wilt sorteren dan wordt ASC standaard gebruikt. Je hoeft ASC dus niet toe te voegen als je aflopend sorteert, maar het is wel goed gebruik omdat het aangeeft dat je deze keuze bewust maakt.

Leren werken met SQL voor data analayse? Na onze 2-daagse SQL cursus kun je volledig zelfstandig werken met SQL.

In bovenstaande syntax structuur zie je dat je op meerdere kolommen kunt sorteren. Het is tevens mogelijk om binnen de ene kolom oplopend aan te houden, en binnen de volgende kolom aflopend.

Tenslotte is het mogelijk om te sorteren op kolommen die niet in je selectie zitten. Dit is echter niet heel gebruikelijk omdat het voor degene die alleen de output leest niet duidelijk is hoe de data geordend zijn.

Ook interessant: een volledige uitleg van SQL SELECT

Voorbeeldtoepassingen van SQL ORDER BY

Nu zullen we laten zien hoe je een SQL ORDER BY statement gebruikt in de praktijk. Hiervoor gebruiken we de IMDb voorbeeld dataset die beschreven staat op deze pagina. Je kunt de dataset ook downloaden via de pagina en als je nog geen mogelijkheid hebt om met SQL te werken op jouw computer dan kun je deze installatie-stappen volgen. In de installatiestappen laten we ook zien hoe je de IMDb database configureert op jouw computer.

We zullen in al onze voorbeelden binnen dit blog gebruik maken van de SQL tabel actors, oftewel de tabel met acteurs die voorkomen in de verschillende films in de database.

Om een indruk te krijgen van de tabel voeren we de volgende query uit:

SELECT *FROM actors;

SQL ORDER BY: output sorteren [TUTORIAL] (1)

We zien dat onze tabel een kolom bevat met id\'s, een met voornamen, een met achternamen, een met gender ("M" of "F") en een kolom met het aantal films waarin een acteur voor komt. Nu we een indruk hebben van alle data kunnen we gaan sorteren door gebruik te maken van ORDER BY.

Sorteren op één kolom

Je kunt rijen sorteren op basis van waarden binnen een specifieke kolom. Zo kun je bijvoorbeeld met onderstaande query sorteren op het aantal films waar acteurs in spelen. Je kunt zowel oplopend (ASC) of aflopend (DESC) sorteren. Als je niets specificeert wordt oplopend gesorteerd.

SELECT *FROM actorsORDER BY film_count DESC;

SQL ORDER BY: output sorteren [TUTORIAL] (2)

We zien de eerste 9 rijen van de output. Rijen zijn gesorteerd op film_count van hoog naar laag. De acteur die in de meeste films heeft gespeeld is Kevin Bacon met 9 films.

Het is ook mogelijk om een kolom-nummer in te geven in plaats van een kolomnaam. Onderstaande query geeft hetzelfde resultaat, aangezien film_count de vijfde kolom is.

SELECT *FROM actorsORDER BY 5 DESC;

Sorteren op meerdere kolommen

Het is ook mogelijk om te sorteren op meerdere kolommen. Dit is vooral handig als er dubbelingen zitten in een bepaalde kolom.

Zo zijn er meerdere acteurs die in drie films spelen. Het kan handig zijn om voor acteurs die in drie films spelen, een verdere sortering te hebben op bijvoorbeeld de voornamen van actuers.

Dit realiseer je met onderstaande query.

SELECT *FROM actorsORDER BY film_count DESC, first_name ASC;

SQL ORDER BY: output sorteren [TUTORIAL] (3)

Zoals je ziet sorteren we de rijen eerst zo dat film_count afloopt, waarna de voornamen oplopend worden gesorteerd over rijen met dezelfde film_count.

Je bent nu in staat je output te sorteren zoals je wenst.

Ook interessant:

  • Waarom SQL leren een goed idee is
  • Voorbeelden van wat je met SQL kunt
  • Hoe leer ik SQL in 4 stappen

Wil je nog veel meer leren over SQL? Bekijk dan onze SQL cursus voor data analyse of download onderstaande opleidingsbrochure. In onze SQL cursus wisselen theorie en praktijkoefening elkaar steeds af. Nadat je deze training hebt gevolgd kun je zelfstandig met SQL werken. Je kunt ook altijd even contact opnemen via info@datasciencepartners.nl of 020 - 24 43 146 als je een vraag hebt.

SQL ORDER BY: output sorteren [TUTORIAL] (2024)

FAQs

How do I sort SQL query output? ›

To ORDER BY a list in SQL, use the ORDER BY clause followed by the column names to sort the results. You can specify the sorting order by adding ASC for ascending or DESC for descending order after each column.

How do I get output in alphabetical order in SQL? ›

Enter ORDER BY criteria; .

Here are some examples: For example, if you wanted to display results in alphabetical order based on a column called NAME, you'd use ORDER BY NAME; . Ascending order is the default sort order, but you could also specify that you want it ascending using ORDER BY NAME ASC; if you'd like.

How to create a sort order in SQL? ›

SQL ORDER BY Keyword
  1. ORDER BY. The ORDER BY command is used to sort the result set in ascending or descending order. ...
  2. ASC. The ASC command is used to sort the data returned in ascending order. ...
  3. DESC. The DESC command is used to sort the data returned in descending order.

How do you order output columns in SQL? ›

To change the order of columns displayed in a result set, report, or application, use the column order in a SELECT (Transact-SQL) statement. Always specify the columns by name in your queries and applications in the order in which you would like them to appear. Don't use SELECT * in applications.

What is the default ordering in case of SQL query output? ›

In SQL ORDER BY clause, we need to define ascending or descending order in which result needs to be sorted. By default, SQL Server sorts out results using ORDER BY clause in ascending order. Specifying ASC in order by clause is optional.

How to sort output in MySQL? ›

The MySQL ORDER BY Keyword

The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

How do you reverse the order of output in SQL? ›

The alternative is to use DESC, which is abbreviated from “descending”. Hence, if you would like your results plotted in reverse order, DESC is the keyword to add at the end of the ORDER BY clause.

How to order output by last three characters in SQL? ›

SELECT *FROM yourTableName ORDER BY RIGHT(yourColumnName,3) yourSortingOrder; Just replace the 'yourSortingOrder' to ASC or DESC to set the ascending or descending order respectively. Here is the query to order by last 3 chars. Case 1 − Get the result in ascending order.

Which command can show results in alphabetical order? ›

The sort command arranges data alphabetically or numerically in ascending or descending order.

How do I create a custom sort order? ›

Follow these steps:
  1. Select the columns to sort. ...
  2. In the ribbon, click Data > Sort.
  3. In the Sort popup window, in the Sort by drop-down, choose the column on which you need to sort. ...
  4. From the Order drop-down, select Custom List.
  5. In the Custom Lists box, select the list that you want, and then click OK to sort the worksheet.

How to sort in SQL without ORDER BY? ›

That could be possible if you would create a index on your table where first(or only) key is DEPARTMENT_ID and you would force your query engine to use this index. This should be a plain SELECT statement as well. But even then, it won't guarantee correct sort order. You cannot, at least not reliably.

How do you sort values in a column in SQL? ›

To sort by a column:

Type: SELECT columns FROM table ORDER BY sort_column [ASC | DESC]; columns is one or more comma-separated column names, sort_column is the name of the column on which to sort the result, and table is the name of the table that contains columns and sort_column.

How do I run an ORDER BY in SQL? ›

SQL ORDER BY clause is used after the WHERE clause (i.e. after filtering the data) to sort the result in either Ascending or Descending order. DESC: Keyword is used to arrange the result in Descending Order. Note: Ascending is a default sort order.

How to create table from SQL query output? ›

If you would like to create a new table, the first step is to use the CREATE TABLE clause and the name of the new table (in our example: gamer ). Then, use the AS keyword and provide a SELECT statement that selects data for the new table.

How do you take output in SQL? ›

The output pane has the following tabs:
  1. Query Result: Displays the results of the most recent Run Statement operation in a display table.
  2. Script Output: Displays the text output from your statements executed as a script using the script engine.
  3. DBMS Output: Displays the output of DBMS_OUTPUT package statements.

What are different methods for sorting results in the query? ›

SQL - SORTING Results
  • Sorting Results in Ascending Order.
  • Sorting Results in Descending Order.
  • Sorting Results in a Preferred Order.

How do you sort a query set? ›

To sort QuerySets, Django uses the order_by() method:
  1. ExampleGet your own Django Server. Order the result alphabetically by firstname: mydata = Member. objects. ...
  2. Example. Order the result firstname descending: mydata = Member. ...
  3. Example. Order the result first by lastname ascending, then descending on id: mydata = Member.

How to output SQL query results? ›

To export query results (Interactive SQL OUTPUT statement)

At the end of the query, type OUTPUT TO 'filename'. For example, to export the entire Employees table to the file employees. txt, enter the following query: SELECT * FROM Employees; OUTPUT TO 'employees.

References

Top Articles
Latest Posts
Article information

Author: Trent Wehner

Last Updated:

Views: 5402

Rating: 4.6 / 5 (56 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Trent Wehner

Birthday: 1993-03-14

Address: 872 Kevin Squares, New Codyville, AK 01785-0416

Phone: +18698800304764

Job: Senior Farming Developer

Hobby: Paintball, Calligraphy, Hunting, Flying disc, Lapidary, Rafting, Inline skating

Introduction: My name is Trent Wehner, I am a talented, brainy, zealous, light, funny, gleaming, attractive person who loves writing and wants to share my knowledge and understanding with you.