Need help! SQL order by

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
newbie2php
Forum Commoner
Posts: 35
Joined: Wed Nov 07, 2007 4:44 pm

Need help! SQL order by

Post by newbie2php »

Hi all

Is this at all possible:

Ordering content from a database table in alphabetical order, BUT the first value to be set by myself?

So, for example:

Name Age

Frank 21
Tom 32
Andy 21
Owen 43

So in this example I would want to order that data so that Owen is first, and then we order by alphabetic values, so the outcomes would be

Owen (this is the value I want to appear first)
Andy (then the rest are outputted in alphabetical order)
Frank
Tom

This is just an example, I have alot more data then that and they are not names and ages.
newbie2php
Forum Commoner
Posts: 35
Joined: Wed Nov 07, 2007 4:44 pm

Re: Need help! SQL order by

Post by newbie2php »

And just to add that this needs to be all in one SQL command

Many thanks :D
User avatar
califdon
Jack of Zircons
Posts: 4484
Joined: Thu Nov 09, 2006 8:30 pm
Location: California, USA

Re: Need help! SQL order by

Post by califdon »

Remember, SQL is a logical language, not a mind reader. If there is a logical way to determine the order, you can probably express it in SQL, but if the logic is just "I want Owen to appear first", there is no way to do that in one SQL statement. You could write a UNION query that is really two queries, one appended to the other, the first one specifically selecting ONLY the record you want to appear first and the second selecting everything BUT that record, in some order. Your question sounds like a very peculiar situation, indeed. We might be able to help you more if you could explain WHY you would ever want to do this.
User avatar
Apollo
Forum Regular
Posts: 794
Joined: Wed Apr 30, 2008 2:34 am

Re: Need help! SQL order by

Post by Apollo »

try order by replace(Name,'Owen',NULL)
Post Reply