Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order alphabetically, but with one value at the top

This:

    - book.prices.order(:currency_code).each do |price|

returns all a book's prices ordered alphabetically by currency code:

AUD 19.99 
GBP 9.99 
NZD 26.00 
USD 14.95

Now, how can I neatly get GBP to always appear at the top of the list, with the others sorting alphabetically, like this:

GBP 9.99 
AUD 19.99 
NZD 26.00 
USD 14.95

This answer shows the SQL solution, but I'm not sure about the Rails way.

like image 780
snowangel Avatar asked Jul 14 '13 09:07

snowangel


People also ask

How do I arrange in alphabetical order in SQL?

The SQL ORDER BY Keyword The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

Does ORDER BY come before where?

The ORDER BY clause is used to get the sorted records on one or more columns in ascending or descending order. The ORDER BY clause must come after the WHERE, GROUP BY, and HAVING clause if present in the query.

What do you call reverse alphabetical order in SQL jargon?

If you'd rather show the results in the opposite order, you'd use ORDER BY NAME DESC; . DESC means "descending order." If you want to sort based on two columns, separate them by commas. For example, ORDER BY LAST_NAME ASC, FIRST_NAME DESC; would display results sorted alphabetically by last name.

How do you order two things in SQL?

After the ORDER BY keyword, add the name of the column by which you'd like to sort records first (in our example, salary). Then, after a comma, add the second column (in our example, last_name ). You can modify the sorting order (ascending or descending) separately for each column.


1 Answers

Since ordering is normally done on DB level, just use the SQL solution in rails:

- book.prices.order("`currency_code` = 'GBP' desc, currency_code").each do |price|

you can use sql snippets in Rails (ActiveRecord) query methods.
Depending on your DB you might have to choose the right SQL solutiuon, so probably

- book.prices.order("CASE WHEN currency_code = 'GBP' THEN 1 ELSE 2 END, currency_code").each do |price|

works in your case.
You can check the resulting sql in rails console:

book.prices.order("CASE WHEN currency_code = 'GBP' THEN 1 ELSE 2 END,  currency_code").to_sql

and check, whether it works in you DB.

An other way is of cause to add an extra column for sorting, this way you can even position commonwelth currencies in front of others etc.

like image 69
Martin M Avatar answered Sep 29 '22 05:09

Martin M