Genadinik
Genadinik

Reputation: 18649

Can I make a query which orders things by two columns?

I have a hiking site. When people search for hikes, they care about two issues:

  1. How close is it in distance from them, and
  2. When is the event

So sometimes I need to present the search results ordered first by date, but if the date is the same, then the hikes need to be ordered by distance. And vice versa.

Is that sort of thing possible in SQL?

Upvotes: 1

Views: 50

Answers (3)

OMG Ponies
OMG Ponies

Reputation: 332711

The ORDER BY clause is the last clause of a SELECT statement. It takes a list of columns, separated by commas. The list is processed left to right, so

ORDER BY distance, event_start

...will order by distance first. Where there are duplicate distances, those will be ordered based on the event_start column values. By default, the ordering is in ASCending order -- you need to specify DESC before the comma to reverse the logic. IE:

ORDER BY distance DESC, event_start

...will put the largest distances at the top of the result set.

Upvotes: 3

Alex Howansky
Alex Howansky

Reputation: 53636

select * from table order by field1, field2;

Upvotes: 0

George Johnston
George Johnston

Reputation: 32278

Just append the order-by statements, one after another. Simplied I'm sure:

SELECT 
  Distance,
  EventTime,
FROM Table1
ORDER BY Distance DESC, EventTime ASC
  • Note, you can order-by descending and ascending values within the same query.

Upvotes: 5

Related Questions