SQL SELECT Sort by specific rowHow can I prevent SQL injection in PHP?How do I perform an IF…THEN in an SQL SELECT?Add a column with a default value to an existing table in SQL ServerHow to concatenate text from multiple rows into a single text string in SQL server?Inserting multiple rows in a single SQL query?How do I limit the number of rows returned by an Oracle query after ordering?SQL Server query - Selecting COUNT(*) with DISTINCTSQL Server: How to Join to first rowHow do I UPDATE from a SELECT in SQL Server?SQL select only rows with max value on a column
How to preserve electronics (computers, iPads and phones) for hundreds of years
What should be the ideal length of sentences in a blog post for ease of reading?
Does Doodling or Improvising on the Piano Have Any Benefits?
Would a primitive species be able to learn English from reading books alone?
How to write Quadratic equation with negative coefficient
What is the meaning of "You've never met a graph you didn't like?"
Would this string work as string?
How to make a list of partial sums using forEach
What is the meaning of the following sentence?
Do I have to take mana from my deck or hand when tapping a dual land?
Personal or impersonal in a technical resume
Is there a distance limit for minecart tracks?
Language involving irrational number is not a CFL
How do I prevent inappropriate ads from appearing in my game?
Should I assume I have passed probation?
Difference between shutdown options
Can I run 125kHz RF circuit on a breadboard?
If the only attacker is removed from combat, is a creature still counted as having attacked this turn?
Is there a way to play vibrato on the piano?
Proving an identity involving cross products and coplanar vectors
When is "ei" a diphthong?
Unable to disable Microsoft Store in domain environment
Why does the Persian emissary display a string of crowned skulls?
Should I warn new/prospective PhD Student that supervisor is terrible?
SQL SELECT Sort by specific row
How can I prevent SQL injection in PHP?How do I perform an IF…THEN in an SQL SELECT?Add a column with a default value to an existing table in SQL ServerHow to concatenate text from multiple rows into a single text string in SQL server?Inserting multiple rows in a single SQL query?How do I limit the number of rows returned by an Oracle query after ordering?SQL Server query - Selecting COUNT(*) with DISTINCTSQL Server: How to Join to first rowHow do I UPDATE from a SELECT in SQL Server?SQL select only rows with max value on a column
Suppose I have a table food
, which I query SELECT name FROM food ORDER BY name
:
| name
|--------
| Apple
| Banana
| Carrot
| Donut
...
I wish to specify that specific items of my choice be pinned to the top (e.g. "Lemon" and then "Carrot"), if they are in the table. Like so:
| name
| -------
| Lemon
| Carrot
| Apple
| Banana
| Donut
...
What kind of SQL query can I use to get this specific sort?
sql
add a comment |
Suppose I have a table food
, which I query SELECT name FROM food ORDER BY name
:
| name
|--------
| Apple
| Banana
| Carrot
| Donut
...
I wish to specify that specific items of my choice be pinned to the top (e.g. "Lemon" and then "Carrot"), if they are in the table. Like so:
| name
| -------
| Lemon
| Carrot
| Apple
| Banana
| Donut
...
What kind of SQL query can I use to get this specific sort?
sql
add a comment |
Suppose I have a table food
, which I query SELECT name FROM food ORDER BY name
:
| name
|--------
| Apple
| Banana
| Carrot
| Donut
...
I wish to specify that specific items of my choice be pinned to the top (e.g. "Lemon" and then "Carrot"), if they are in the table. Like so:
| name
| -------
| Lemon
| Carrot
| Apple
| Banana
| Donut
...
What kind of SQL query can I use to get this specific sort?
sql
Suppose I have a table food
, which I query SELECT name FROM food ORDER BY name
:
| name
|--------
| Apple
| Banana
| Carrot
| Donut
...
I wish to specify that specific items of my choice be pinned to the top (e.g. "Lemon" and then "Carrot"), if they are in the table. Like so:
| name
| -------
| Lemon
| Carrot
| Apple
| Banana
| Donut
...
What kind of SQL query can I use to get this specific sort?
sql
sql
edited Mar 7 at 22:20
Max Voisard
576
576
asked Mar 7 at 22:12
cameraguy258cameraguy258
1678
1678
add a comment |
add a comment |
4 Answers
4
active
oldest
votes
You can use a case statement in your order by clause to prioritize items with a certain name.
The following will put Lemon and Carrot in priority order by assigning them the values of 1 and 2 from the case, where all others will get the value 3. Those remaining that were assigned 3 will then be sorted by the second expression in the order by clause, which is just the name column.
SELECT *
FROM food
ORDER BY
CASE name
WHEN 'Lemon' THEN 1
WHEN 'Carrot' THEN 2
ELSE 3
END,
name
1
He already addedname
to theorder by
clause, so it's good.
– Marc
Mar 7 at 22:16
1
Very good answer, and exactly what I was looking for.
– cameraguy258
Mar 7 at 22:35
this was also the only answer which was not RDBMS specific @cameraguy258
– Raymond Nijland
Mar 7 at 22:37
add a comment |
Make a look up table like this:
WITH odering(F, Ord) AS
(
VALUES ('Lemmon', 2),
('Carrot', 1)
)
SELECT name
FROM table t
LEFT JOIN ordering Ord on T.name = Ord.name
ORDER BY COALESCE(Ord.Ord, 0) DESC, Name ASC
add a comment |
Chances are, this is going to be RDBMS specific. The one being used is not specified.
MySQL, commonly used, provides a function field(). Good for custom sorts on bounded values.
mysql> create temporary table food as select 'Apple' as food union select 'Banana' union select 'Carrot' union select 'Donut';
Query OK, 4 rows affected (0.00 sec)
Records: 4 Duplicates: 0 Warnings: 0
mysql> select * from food;
+--------+
| food |
+--------+
| Apple |
| Banana |
| Carrot |
| Donut |
+--------+
4 rows in set (0.00 sec)
mysql> select * from food order by field (food, 'Carrot', 'Apple', 'Banana', 'Donut');
+--------+
| food |
+--------+
| Carrot |
| Apple |
| Banana |
| Donut |
+--------+
4 rows in set (0.00 sec)
add a comment |
I'd use CTE and go like this:
WITH FoodOrder(name, foodOrder)
AS
(
SELECT name
, foodOrder = CASE name
WHEN 'Lemon' THEN 200
WHEN 'Carrot' THEN 100
ELSE 0
END
FROM food
)
SELECT name
FROM FoodOrder
ORDER BY foodOrder DESC, name
Please note that if you will choose enough spacing between CASE values (0, 100 ,200) you can easily add another prioritized food afterwards if needed without overwriting already existing values.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55053638%2fsql-select-sort-by-specific-row%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
4 Answers
4
active
oldest
votes
4 Answers
4
active
oldest
votes
active
oldest
votes
active
oldest
votes
You can use a case statement in your order by clause to prioritize items with a certain name.
The following will put Lemon and Carrot in priority order by assigning them the values of 1 and 2 from the case, where all others will get the value 3. Those remaining that were assigned 3 will then be sorted by the second expression in the order by clause, which is just the name column.
SELECT *
FROM food
ORDER BY
CASE name
WHEN 'Lemon' THEN 1
WHEN 'Carrot' THEN 2
ELSE 3
END,
name
1
He already addedname
to theorder by
clause, so it's good.
– Marc
Mar 7 at 22:16
1
Very good answer, and exactly what I was looking for.
– cameraguy258
Mar 7 at 22:35
this was also the only answer which was not RDBMS specific @cameraguy258
– Raymond Nijland
Mar 7 at 22:37
add a comment |
You can use a case statement in your order by clause to prioritize items with a certain name.
The following will put Lemon and Carrot in priority order by assigning them the values of 1 and 2 from the case, where all others will get the value 3. Those remaining that were assigned 3 will then be sorted by the second expression in the order by clause, which is just the name column.
SELECT *
FROM food
ORDER BY
CASE name
WHEN 'Lemon' THEN 1
WHEN 'Carrot' THEN 2
ELSE 3
END,
name
1
He already addedname
to theorder by
clause, so it's good.
– Marc
Mar 7 at 22:16
1
Very good answer, and exactly what I was looking for.
– cameraguy258
Mar 7 at 22:35
this was also the only answer which was not RDBMS specific @cameraguy258
– Raymond Nijland
Mar 7 at 22:37
add a comment |
You can use a case statement in your order by clause to prioritize items with a certain name.
The following will put Lemon and Carrot in priority order by assigning them the values of 1 and 2 from the case, where all others will get the value 3. Those remaining that were assigned 3 will then be sorted by the second expression in the order by clause, which is just the name column.
SELECT *
FROM food
ORDER BY
CASE name
WHEN 'Lemon' THEN 1
WHEN 'Carrot' THEN 2
ELSE 3
END,
name
You can use a case statement in your order by clause to prioritize items with a certain name.
The following will put Lemon and Carrot in priority order by assigning them the values of 1 and 2 from the case, where all others will get the value 3. Those remaining that were assigned 3 will then be sorted by the second expression in the order by clause, which is just the name column.
SELECT *
FROM food
ORDER BY
CASE name
WHEN 'Lemon' THEN 1
WHEN 'Carrot' THEN 2
ELSE 3
END,
name
edited Mar 7 at 22:17
answered Mar 7 at 22:15
Daniel GimenezDaniel Gimenez
11.6k22749
11.6k22749
1
He already addedname
to theorder by
clause, so it's good.
– Marc
Mar 7 at 22:16
1
Very good answer, and exactly what I was looking for.
– cameraguy258
Mar 7 at 22:35
this was also the only answer which was not RDBMS specific @cameraguy258
– Raymond Nijland
Mar 7 at 22:37
add a comment |
1
He already addedname
to theorder by
clause, so it's good.
– Marc
Mar 7 at 22:16
1
Very good answer, and exactly what I was looking for.
– cameraguy258
Mar 7 at 22:35
this was also the only answer which was not RDBMS specific @cameraguy258
– Raymond Nijland
Mar 7 at 22:37
1
1
He already added
name
to the order by
clause, so it's good.– Marc
Mar 7 at 22:16
He already added
name
to the order by
clause, so it's good.– Marc
Mar 7 at 22:16
1
1
Very good answer, and exactly what I was looking for.
– cameraguy258
Mar 7 at 22:35
Very good answer, and exactly what I was looking for.
– cameraguy258
Mar 7 at 22:35
this was also the only answer which was not RDBMS specific @cameraguy258
– Raymond Nijland
Mar 7 at 22:37
this was also the only answer which was not RDBMS specific @cameraguy258
– Raymond Nijland
Mar 7 at 22:37
add a comment |
Make a look up table like this:
WITH odering(F, Ord) AS
(
VALUES ('Lemmon', 2),
('Carrot', 1)
)
SELECT name
FROM table t
LEFT JOIN ordering Ord on T.name = Ord.name
ORDER BY COALESCE(Ord.Ord, 0) DESC, Name ASC
add a comment |
Make a look up table like this:
WITH odering(F, Ord) AS
(
VALUES ('Lemmon', 2),
('Carrot', 1)
)
SELECT name
FROM table t
LEFT JOIN ordering Ord on T.name = Ord.name
ORDER BY COALESCE(Ord.Ord, 0) DESC, Name ASC
add a comment |
Make a look up table like this:
WITH odering(F, Ord) AS
(
VALUES ('Lemmon', 2),
('Carrot', 1)
)
SELECT name
FROM table t
LEFT JOIN ordering Ord on T.name = Ord.name
ORDER BY COALESCE(Ord.Ord, 0) DESC, Name ASC
Make a look up table like this:
WITH odering(F, Ord) AS
(
VALUES ('Lemmon', 2),
('Carrot', 1)
)
SELECT name
FROM table t
LEFT JOIN ordering Ord on T.name = Ord.name
ORDER BY COALESCE(Ord.Ord, 0) DESC, Name ASC
answered Mar 7 at 22:18
HoganHogan
55.5k967103
55.5k967103
add a comment |
add a comment |
Chances are, this is going to be RDBMS specific. The one being used is not specified.
MySQL, commonly used, provides a function field(). Good for custom sorts on bounded values.
mysql> create temporary table food as select 'Apple' as food union select 'Banana' union select 'Carrot' union select 'Donut';
Query OK, 4 rows affected (0.00 sec)
Records: 4 Duplicates: 0 Warnings: 0
mysql> select * from food;
+--------+
| food |
+--------+
| Apple |
| Banana |
| Carrot |
| Donut |
+--------+
4 rows in set (0.00 sec)
mysql> select * from food order by field (food, 'Carrot', 'Apple', 'Banana', 'Donut');
+--------+
| food |
+--------+
| Carrot |
| Apple |
| Banana |
| Donut |
+--------+
4 rows in set (0.00 sec)
add a comment |
Chances are, this is going to be RDBMS specific. The one being used is not specified.
MySQL, commonly used, provides a function field(). Good for custom sorts on bounded values.
mysql> create temporary table food as select 'Apple' as food union select 'Banana' union select 'Carrot' union select 'Donut';
Query OK, 4 rows affected (0.00 sec)
Records: 4 Duplicates: 0 Warnings: 0
mysql> select * from food;
+--------+
| food |
+--------+
| Apple |
| Banana |
| Carrot |
| Donut |
+--------+
4 rows in set (0.00 sec)
mysql> select * from food order by field (food, 'Carrot', 'Apple', 'Banana', 'Donut');
+--------+
| food |
+--------+
| Carrot |
| Apple |
| Banana |
| Donut |
+--------+
4 rows in set (0.00 sec)
add a comment |
Chances are, this is going to be RDBMS specific. The one being used is not specified.
MySQL, commonly used, provides a function field(). Good for custom sorts on bounded values.
mysql> create temporary table food as select 'Apple' as food union select 'Banana' union select 'Carrot' union select 'Donut';
Query OK, 4 rows affected (0.00 sec)
Records: 4 Duplicates: 0 Warnings: 0
mysql> select * from food;
+--------+
| food |
+--------+
| Apple |
| Banana |
| Carrot |
| Donut |
+--------+
4 rows in set (0.00 sec)
mysql> select * from food order by field (food, 'Carrot', 'Apple', 'Banana', 'Donut');
+--------+
| food |
+--------+
| Carrot |
| Apple |
| Banana |
| Donut |
+--------+
4 rows in set (0.00 sec)
Chances are, this is going to be RDBMS specific. The one being used is not specified.
MySQL, commonly used, provides a function field(). Good for custom sorts on bounded values.
mysql> create temporary table food as select 'Apple' as food union select 'Banana' union select 'Carrot' union select 'Donut';
Query OK, 4 rows affected (0.00 sec)
Records: 4 Duplicates: 0 Warnings: 0
mysql> select * from food;
+--------+
| food |
+--------+
| Apple |
| Banana |
| Carrot |
| Donut |
+--------+
4 rows in set (0.00 sec)
mysql> select * from food order by field (food, 'Carrot', 'Apple', 'Banana', 'Donut');
+--------+
| food |
+--------+
| Carrot |
| Apple |
| Banana |
| Donut |
+--------+
4 rows in set (0.00 sec)
answered Mar 7 at 22:24
Rich AndrewsRich Andrews
1897
1897
add a comment |
add a comment |
I'd use CTE and go like this:
WITH FoodOrder(name, foodOrder)
AS
(
SELECT name
, foodOrder = CASE name
WHEN 'Lemon' THEN 200
WHEN 'Carrot' THEN 100
ELSE 0
END
FROM food
)
SELECT name
FROM FoodOrder
ORDER BY foodOrder DESC, name
Please note that if you will choose enough spacing between CASE values (0, 100 ,200) you can easily add another prioritized food afterwards if needed without overwriting already existing values.
add a comment |
I'd use CTE and go like this:
WITH FoodOrder(name, foodOrder)
AS
(
SELECT name
, foodOrder = CASE name
WHEN 'Lemon' THEN 200
WHEN 'Carrot' THEN 100
ELSE 0
END
FROM food
)
SELECT name
FROM FoodOrder
ORDER BY foodOrder DESC, name
Please note that if you will choose enough spacing between CASE values (0, 100 ,200) you can easily add another prioritized food afterwards if needed without overwriting already existing values.
add a comment |
I'd use CTE and go like this:
WITH FoodOrder(name, foodOrder)
AS
(
SELECT name
, foodOrder = CASE name
WHEN 'Lemon' THEN 200
WHEN 'Carrot' THEN 100
ELSE 0
END
FROM food
)
SELECT name
FROM FoodOrder
ORDER BY foodOrder DESC, name
Please note that if you will choose enough spacing between CASE values (0, 100 ,200) you can easily add another prioritized food afterwards if needed without overwriting already existing values.
I'd use CTE and go like this:
WITH FoodOrder(name, foodOrder)
AS
(
SELECT name
, foodOrder = CASE name
WHEN 'Lemon' THEN 200
WHEN 'Carrot' THEN 100
ELSE 0
END
FROM food
)
SELECT name
FROM FoodOrder
ORDER BY foodOrder DESC, name
Please note that if you will choose enough spacing between CASE values (0, 100 ,200) you can easily add another prioritized food afterwards if needed without overwriting already existing values.
answered Mar 7 at 23:23
EmilEmil
159214
159214
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55053638%2fsql-select-sort-by-specific-row%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown