How to reverse order output of a MySQL query

I have a basic write to and retrieve SQL database PHP "thing" and I want to have the output in descending order. How do I do that?

For example, the last entry is shown first, then the entry before that, then the entry before that, etc. The first entry ever is last.

Upvotes: 9

Views: 30548

Answers (7)

IVIike
IVIike

Reputation: 117

Another possible answer if you had the same requirement as me where I needed the newest 24 entries but in reverse order:

SELECT T.* FROM(SELECT * FROM 'table' [WHERE 'condition'] [ORDER BY dbId DESC] LIMIT 24) as T ORDER BY T.dbId ASC;

Upvotes: 1

Hassan Sardar
Hassan Sardar

Reputation: 4523

MySQL general query syntax for SELECT:

SELECT field1, field2,...fieldN FROM table_name
[WHERE Clause][GROUP BY]
[ORDER BY][LIMIT]

Example query 1:

SELECT id,first_name,last_name,email FROM users ORDER BY first_name desc // In this case you can only fetch data by = id,first_name,last_name,email

Example query 2:

SELECT * FROM users ORDER BY first_name desc // In this case all fields will be selected

Note: ORDER BY ASC = Data will sort by Ascending Order & ORDER BY DESC = Data will sort by descending Order

Upvotes: 1

user2801966
user2801966

Reputation: 468

Use:

SELECT field_name
FROM table_name
ORDER BY id DESC

By default, MySQL will show results in ascending order. If you want to show them in reverse order, use ORDER BY field_name DESC.

You can use id or date as the field name.

Upvotes: 14

TecBrat
TecBrat

Reputation: 3729

If there's an auto increment field, you order by that field, descending.

SELECT "column_name"
  FROM "table_name"
  [WHERE "condition"]
  ORDER BY "column_name" [ASC, DESC]; 

That's from ORDER BY Clause - Sort Data In SQL.

Upvotes: 3

Janak Prajapati
Janak Prajapati

Reputation: 886

Write the below query to retrieve data:

SELECT * FROM `table_name` order by id desc

It will retrieve data from the table in descending order.

Upvotes: 1

Oswald
Oswald

Reputation: 31647

Change the ORDER BY statement

  • from ORDER BY col or ORDER BY col ASC or to ORDER BY col DESC
  • from ORDER BY col DESC to ORDER BY col ASC

Upvotes: 4

Ashwini Agarwal
Ashwini Agarwal

Reputation: 4858

Sort using DESC ORDER BY.

SELECT * FROM <TABLE> ORDER BY <COLUMN> DESC

Upvotes: 3

Related Questions