Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort certain values to the top

I have a MySQL table with the following data (simplified):

INSERT INTO `stores` (`storeId`, `name`, `country`) VALUES
(1, 'Foo', 'us'),
(2, 'Bar', 'jp'),
(3, 'Baz', 'us'),
(4, 'Foo2', 'se'),
(5, 'Baz2', 'jp'),
(6, 'Bar3', 'jp');

Now, I want to be able to get a paginated list of stores that begins with the customers country.

For example, an american customer would see the following list:

Foo
Baz
Bar
Foo2
Baz2
Bar3

The naive solution I'm using right now (example with an american customer and page size 3):

(SELECT * FROM stores WHERE country = "us") UNION (SELECT * FROM stores WHERE country != "us") LIMIT 0,3

Are there any better ways of doing this? Could ORDER BY be used and told to put a certain value at the top?

like image 397
mthurlin Avatar asked Jul 03 '09 12:07

mthurlin


People also ask

How do I sort Top 10 data in Excel?

To use a Top 10 AutoFilter in Excel, click the AutoFilter drop-down arrow button next to the column heading for the field by which to filter the table. Next, roll down to the “Number Filters” choice. Then select the “Top 10…” option from the side menu that appears to open the “Top 10 AutoFilter” dialog box.

How do I sort specific rows?

Sort a Selection of RowsHighlight the rows by holding down the Shift key and clicking on the row numbers you want to sort. Right-click on the selected area and select Sort Rows. In the Sort form, enter your sort criteria and click OK.


3 Answers

Try this:

SELECT * FROM stores ORDER BY country = "us" DESC,  storeId
like image 181
Joachim Sauer Avatar answered Sep 21 '22 06:09

Joachim Sauer


To get the searched-for country first, and the remainder alphabetically:

SELECT * 
FROM   stores 
ORDER BY country = 'us' DESC, country ASC
like image 36
rooskie Avatar answered Sep 19 '22 06:09

rooskie


You have to link each value of a country with a numeric, with a case :

select *
from stores
order by case when country = "us" then 1
              else 0
         end desc
like image 31
Cyril Gandon Avatar answered Sep 21 '22 06:09

Cyril Gandon