Sorting by Calculated Boolean

Post Reply
sroth
Posts: 44
Joined: Mon Jul 23, 2007 11:21 am

Sorting by Calculated Boolean

Post by sroth »

I need to sort my results based on an integer field matching a value passed into my query. If the field matches the passed value, I want these rows sorted to the top. If the field does not match the value, I want these rows sorted after the rows that do match.

Something like this:
Order By IF id=$passedValue THEN 0 ELSE 1 END

Any help would be appreciated.
User avatar
mark
Site Admin
Posts: 5519
Joined: Tue Apr 25, 2000 6:56 pm

Sorting by Calculated Boolean

Post by mark »

If id is numeric you could do "order by fabs(id-$passedValue)". All records would be ordered by their numeric distance from the passed value which may or may not be useful.
sroth
Posts: 44
Joined: Mon Jul 23, 2007 11:21 am

Sorting by Calculated Boolean

Post by sroth »

Thanks, the id is numeric, but I need a true boolean because I have a secondary sort level that would be blown out unless I can truly have a boolean calculation on by first level.

Order By IF id=$passedValue THEN 0 ELSE 1 END, PostDate, Author
User avatar
mark
Site Admin
Posts: 5519
Joined: Tue Apr 25, 2000 6:56 pm

Sorting by Calculated Boolean

Post by mark »

If we turn up the arcane knob a bit...

order by 1-bitisset(1,fabs(id-$passedValue)), PostDate, Author

You may consider using 2 sql's. The first to get the selected id(s) and the second to get the rest. Don't forget to exclude the selected id(s) in the 2nd sql.
sroth
Posts: 44
Joined: Mon Jul 23, 2007 11:21 am

Sorting by Calculated Boolean

Post by sroth »

That did the trick. Not the most readable but it works. Thanks.
Post Reply