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













3















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?










share|improve this question




























    3















    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?










    share|improve this question


























      3












      3








      3








      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?










      share|improve this question
















      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






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 7 at 22:20









      Max Voisard

      576




      576










      asked Mar 7 at 22:12









      cameraguy258cameraguy258

      1678




      1678






















          4 Answers
          4






          active

          oldest

          votes


















          10














          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





          share|improve this answer




















          • 1





            He already added name to the order 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














          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





          share|improve this answer






























            0














            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)






            share|improve this answer






























              0














              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.






              share|improve this answer






















                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
                );



                );













                draft saved

                draft discarded


















                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









                10














                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





                share|improve this answer




















                • 1





                  He already added name to the order 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
















                10














                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





                share|improve this answer




















                • 1





                  He already added name to the order 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














                10












                10








                10







                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





                share|improve this answer















                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






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Mar 7 at 22:17

























                answered Mar 7 at 22:15









                Daniel GimenezDaniel Gimenez

                11.6k22749




                11.6k22749







                • 1





                  He already added name to the order 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





                  He already added name to the order 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














                1














                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





                share|improve this answer



























                  1














                  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





                  share|improve this answer

























                    1












                    1








                    1







                    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





                    share|improve this answer













                    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






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Mar 7 at 22:18









                    HoganHogan

                    55.5k967103




                    55.5k967103





















                        0














                        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)






                        share|improve this answer



























                          0














                          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)






                          share|improve this answer

























                            0












                            0








                            0







                            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)






                            share|improve this answer













                            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)







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Mar 7 at 22:24









                            Rich AndrewsRich Andrews

                            1897




                            1897





















                                0














                                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.






                                share|improve this answer



























                                  0














                                  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.






                                  share|improve this answer

























                                    0












                                    0








                                    0







                                    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.






                                    share|improve this answer













                                    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.







                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Mar 7 at 23:23









                                    EmilEmil

                                    159214




                                    159214



























                                        draft saved

                                        draft discarded
















































                                        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.




                                        draft saved


                                        draft discarded














                                        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





















































                                        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







                                        Popular posts from this blog

                                        Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme

                                        Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

                                        2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived