SQL ORDER BY: Sort Rows ASC or DESC

SQL ORDER BY sorting records

The SQL ORDER BY clause sorts query results. Ascending order is the default, so these two queries are equivalent:

SELECT id, name, mark
FROM student
ORDER BY mark;
SELECT id, name, mark
FROM student
ORDER BY mark ASC;

To sort from highest to lowest, use DESC:

SELECT id, name, mark
FROM student
ORDER BY mark DESC;
Important: without ORDER BY, SQL does not guarantee the order in which rows are returned.
Order by MySQL query to display rows based on order of columns

SQL ORDER BY Syntax Top ↑

SELECT column1, column2
FROM table_name
ORDER BY column1 ASC;

ASC means ascending order and is the default. DESC means descending order.

Ascending Order Top ↑

For a numeric column, ascending order moves from lower values to higher values:

SELECT id, name, mark
FROM student
ORDER BY mark ASC;
idnamemark
19Tinny18
17Tumyu54
3Arnold55
6Alex John55
4Krish Star60

Descending Order Top ↑

Use DESC to return larger values first:

SELECT id, name, mark
FROM student
ORDER BY mark DESC;

This is useful for highest scores, newest dates, largest prices and similar rankings.

For top records, combine ORDER BY with LIMIT.

ORDER BY on Text Columns Top ↑

For text columns, ascending order follows the column's collation rules:

SELECT id, name, class
FROM student
ORDER BY class ASC;

Descending order reverses that sort:

SELECT id, name, class
FROM student
ORDER BY class DESC;
Text sorting is affected by the column collation, including rules for case, accents and character comparison.

Sort by Multiple Columns Top ↑

SQL applies the sort columns from left to right. This query sorts by class first, then by mark within each class:

SELECT id, name, class, mark
FROM student
ORDER BY class ASC, mark DESC;

Each sort column can use its own direction.

For example, marks can be descending while names are ascending for equal marks:

SELECT id, name, mark
FROM student
ORDER BY mark DESC, name ASC;

Add a Tie-breaker for Predictable Ordering Top ↑

If several rows have the same value in the first sort column, their relative order is not guaranteed unless another sort expression resolves the tie.

Instead of:

SELECT id, name, mark
FROM student
ORDER BY mark DESC;

use a unique or otherwise deterministic secondary column when stable output matters:

SELECT id, name, mark
FROM student
ORDER BY mark DESC, id ASC;

This is especially important for pagination and top-N queries.

ORDER BY with WHERE Top ↑

The WHERE clause filters rows first; ORDER BY sorts the rows that remain.

SELECT id, name, class, mark
FROM student
WHERE class = 'Four'
ORDER BY mark DESC, id ASC;

ORDER BY with LIMIT Top ↑

To return the three highest marks:

SELECT id, name, mark
FROM student
ORDER BY mark DESC, id ASC
LIMIT 3;

Without ORDER BY, LIMIT 3 means only "return three rows"; it does not mean the highest three rows.

See also highest and second-highest record examples.

Sort by an Alias or Expression Top ↑

MySQL can sort using an expression or an alias defined in the SELECT list.

SELECT id,
       name,
       100 - mark AS difference
FROM student
ORDER BY difference DESC;

This avoids creating or updating an extra column merely for display-time sorting.

Sort Numbers Stored in a VARCHAR Column Top ↑

If numeric-looking values are stored in a text column, normal text sorting can produce an unexpected sequence such as 100, 18, 40, 6, 82.

For an existing VARCHAR column named diff, convert the value for sorting:

SELECT id, name, diff
FROM student
ORDER BY CAST(diff AS UNSIGNED) DESC;

See the MySQL CAST and type-conversion tutorial.

If a column represents numbers, storing it with a numeric datatype is usually better than repeatedly casting a VARCHAR value during sorting.

ORDER BY and NULL Values in MySQL Top ↑

In MySQL, NULL values normally sort before non-NULL values in ascending order and after non-NULL values in descending order.

SELECT id, name, class
FROM student3
ORDER BY class ASC;

If you need a different placement, sort first by a NULL expression and then by the column:

SELECT id, name, class
FROM student3
ORDER BY (class IS NULL) ASC,
         class ASC;

This places non-NULL class values before NULL values. See SQL NULL values.

Safe User-selected Sorting in PHP Top ↑

PDO placeholders bind data values, not SQL identifiers or keywords. This does not work:

<?php
$stmt=$dbo->prepare(
    "SELECT id,name,mark
     FROM student
     ORDER BY :sort :direction"
);

If users can choose the sort column or direction, select them from strict application-controlled allowlists:

<?php
$allowed_columns=[
    'name' => 'name',
    'class' => 'class',
    'mark' => 'mark'
];

$allowed_directions=[
    'asc' => 'ASC',
    'desc' => 'DESC'
];

$sort_key=$_GET['sort'] ?? 'name';
$direction_key=strtolower(
    $_GET['direction'] ?? 'asc'
);

$sort=$allowed_columns[$sort_key] ?? 'name';
$direction=$allowed_directions[$direction_key] ?? 'ASC';

$sql="SELECT id,name,class,mark
      FROM student
      ORDER BY $sort $direction, id ASC";

$stmt=$dbo->query($sql);
Do not concatenate an arbitrary GET or POST value directly into an ORDER BY clause. Use fixed SQL or a strict allowlist.

See changing record display order from user input for the practical interface idea.

ORDER BY after UNION Top ↑

When combining rows from two sources with UNION ALL, the final ORDER BY sorts the combined result.

SELECT dt, topic_id, userid
FROM (
    SELECT topic_id, rdtp AS dt, userid
    FROM forum_reply

    UNION ALL

    SELECT topic_id, tdtp AS dt, userid
    FROM forum_topics
) AS t
ORDER BY dt DESC
LIMIT 10;

This returns the ten most recent rows across both sources, assuming the date-time values are comparable.

ORDER BY Performance Notes Top ↑

  • Sorting large result sets can require extra work and memory.
  • An appropriate index can help some ORDER BY queries, depending on the WHERE clause, index order and query plan.
  • Expressions such as CAST(column AS UNSIGNED) can make index-based ordering less straightforward.
  • For pagination, use a deterministic ORDER BY so rows do not move unpredictably between pages.
  • Use EXPLAIN when a production query is slow rather than assuming every ORDER BY requires a new index.

Common ORDER BY Mistakes Top ↑

Assuming rows have a natural order Top ↑

Without ORDER BY, the database is free to return rows in any order allowed by the execution plan.

Forgetting a tie-breaker Top ↑

If many rows share the same sort value, add another column such as a unique ID when deterministic ordering matters.

Using DESC only on the first column by assumption Top ↑

Each ORDER BY expression has its own direction. Write the required ASC or DESC explicitly when mixing directions.

Sorting numeric values stored as text Top ↑

Text values sort lexically. Use the correct numeric datatype whenever possible or CAST legacy text values when required.

Using LIMIT without ORDER BY for "top" records Top ↑

LIMIT restricts row count. ORDER BY defines which rows are highest, lowest, newest or otherwise first.

Binding column names as PDO parameters Top ↑

Prepared-statement placeholders are for data values, not identifiers or ASC/DESC keywords. Use an allowlist for user-selected sorting.

SQL WHERE SQL LIMIT SQL SELECT

Highest Records SQL UNION CAST / Convert

Full student table with SQL Dump

Frequently Asked Questions Top ↑

Q1: What is the default order of SQL ORDER BY?

Ascending order is the default. ORDER BY column and ORDER BY column ASC are equivalent.

Q2: How do I sort from highest to lowest?

Use DESC after the sort expression, for example ORDER BY mark DESC.

Q3: Can I sort by more than one column?

Yes. List the columns from highest sorting priority to lowest, and give each column its own ASC or DESC direction if required.

Q4: Why do rows with the same value appear in a different order?

Rows tied on all specified ORDER BY expressions do not have a guaranteed relative order. Add a deterministic tie-breaker such as a unique ID when stable output matters.

Q5: How do I get the highest three records?

Sort the relevant value in descending order and then apply LIMIT 3, preferably with a secondary tie-breaker.

Q6: Can PDO bind a column name in ORDER BY?

No. PDO placeholders bind data values, not SQL identifiers or ASC/DESC keywords. Use fixed SQL or select the allowed identifier from a strict application allowlist.

Q7: How does MySQL sort NULL values?

MySQL normally sorts NULL before non-NULL values in ascending order and after non-NULL values in descending order. An additional expression can be used when another placement is required.





Subscribe to our YouTube Channel here



plus2net.com
jigger

11-06-2013

just want to asked guys, hope you help me this is the scenario i have at least 3 data in my database from ID 1, 2, 3, and i want to display this file or post, data display is OK but i want to display like this 3, 2, 1 how can make it that way.
annu

10-10-2014

Suppose if we are using 1st, 2nd and 3rd in class instead of two three and four how will this query will work in that case
Steve Highley

27-10-2014

The desc qualifier (which stands for descending, i.e. high to low) changes the sequence from the default of low to high.

Data is ordered depending on the data type. Text is ordered according to collating sequence, numbers from low to high (e.g. -100 is before 5), and dates are ordered from earliest to latest.

So 'Three' is greater than 'Four' because T is after F in the collating sequence.

But 3 is less than 4 whether stored as numbers or text.

I hope that helps.

yamsoti

26-03-2016

I want to display 2 highest mark from class 4, it has marks 70, 60, 60, 50. How do I prepare the query.
smo1234

07-04-2016

Your can read how to get second highest by using order by and limit
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2026   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer