Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return rows with a specific value first?

People also ask

How do I return a specific number of rows in SQL?

The SQL COUNT() function returns the number of rows in a table satisfying the criteria specified in the WHERE clause. It sets the number of rows or non NULL column values. COUNT() returns 0 if there were no matching rows.

How do you 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.

Which clause is used to return specific rows?

The WHERE clause allows you to retrieve only rows you are interested in. If the expression in the WHERE clause is true for any row, then that row is returned.

How do you select only the first rows for each unique value of a column in SQL?

You can use row_number() to get the row number of the row. It uses the over command - the partition by clause specifies when to restart the numbering and the order by selects what to order the row number on.


On SQL Server, Oracle, DB2, and many other database systems, this is what you can use:

ORDER BY CASE WHEN city = 'New York' THEN 1 ELSE 2 END, city

If your SQL dialect is intelligent enough to treat boolean expressions as having a numeric value, then you can use:

SELECT *
FROM `Users`
ORDER BY (`city` = 'New York') DESC, `city`

My answer may be old and not required but someone may need different approach,hence posting it here.

I had same requirement implemented this, worked for me.

Select * from Users
ORDER BY
(CASE WHEN city = 'New York' THEN 0 ELSE 1 END), city
GO

PS

this is for SQL