MadSeb
MadSeb

Reputation: 8234

MySQL ORDER BY order

In MySQL, is there a difference between those 2 queries?

SELECT * FROM .... ORDER BY Created,Id DESC 

and

SELECT * FROM .... ORDER BY Created DESC, Id DESC

Desired behaviour: order (descending ) by "Created" ( a timestamp) but when two items have the same "Created" value then fall back to ordering ( desc ) using the Id.

Upvotes: 0

Views: 417

Answers (5)

Michael Durrant
Michael Durrant

Reputation: 96484

The defult sorting for dates is in ASC - Ascending order.

So the 1st query will have items in ascending order and the second query will have them in descending order.

Upvotes: 0

hjpotter92
hjpotter92

Reputation: 80639

In the first one, the default ordering(ASC) is used for Created column.

Upvotes: 0

John Smith
John Smith

Reputation: 721

I think first one wont work?

You could do

SELECT * FROM .... ORDER BY Created ASC, Id DESC
SELECT * FROM .... ORDER BY Created DESC, Id ASC

but it will slow down slightly if you do different ones.

Upvotes: 0

cegfault
cegfault

Reputation: 6632

Yes, there is a difference. The default order is ascending, so:

SELECT * FROM .... ORDER BY Created,Id DESC 

Will order by Created ascending, and then Id descending

SELECT * FROM .... ORDER BY Created DESC, Id DESC

Will order by Created descending, and then Id descending

Upvotes: 1

Ken White
Ken White

Reputation: 125688

Of course there's a difference. The first orders by CREATED in ascending order, and then if there are multiples sorts those rows on ID descending. The second sorts by CREATED in descending order first, then by ID descending if there are multiples.

The second one should do what you want.

(Of course, this begs the question: Why didn't you just try it yourself to find out?)

Upvotes: 0

Related Questions