Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Select Certain Value First

SELECT     AssetValue
FROM         Assets
WHERE     (AssetType = 'Country')

Very simple Select Statement, but it outputs

Afghanistan
Albania
Algeria
....

How do I make United States and Canada appear on the top of this? Is this possible with SQL or do I need to do something in my ASP code? My PK is a INT Identity.

like image 390
atrljoe Avatar asked Apr 18 '11 15:04

atrljoe


People also ask

How do I SELECT the first value in SQL?

We could use FIRST_VALUE() in SQL Server to find the first value from any table. FIRST_VALUE() function used in SQL server is a type of window function that results in the first value in an ordered partition of the given data set.

How do I SELECT a specific value in SQL?

To select rows using selection symbols for character or graphic data, use the LIKE keyword in a WHERE clause, and the underscore and percent sign as selection symbols. You can create multiple row conditions, and use the AND, OR, or IN keywords to connect the conditions.

What does First () do in SQL?

The FIRST() function returns the first value of the selected column.


2 Answers

SELECT     AssetValue
FROM         Assets
WHERE     (AssetType = 'Country')
ORDER BY CASE AssetValue 
          WHEN 'US' THEN 1 
          WHEN 'Canada' THEN 2 ELSE 3 END, AssetValue 
like image 66
Martin Smith Avatar answered Oct 09 '22 14:10

Martin Smith


If you do not wish to hard code, the most generic solution is having an extra field to indicate the preferential items. You would call it OrderPreference. The higher OrderPreference, the first the item would appear. Every item else would have OrderPreference equals ZERO. The query:

SELECT     AssetValue
FROM         Assets
WHERE     (AssetType = 'Country')
ORDER BY OrderPreference desc, AssetValue

By the looks of it, Assets is a table you use for other things (not only countries), so you could use this approach to solve the same problem for others asset types, if they come up.

like image 43
Adriano Carneiro Avatar answered Oct 09 '22 15:10

Adriano Carneiro