PostgresSQL ORDER BY clause with CASE for sorted columnAdd a column with a default value to an existing table in SQL ServerParameterize an SQL IN clauseSQL join: where clause vs. on clauseSQLite - UPSERT *not* INSERT or REPLACEHow do I insert into a table if a value does not exist, but only for certain criteria? (MS SQL Server)INNER JOIN ON vs WHERE clauseSQL multiple column orderingUsing group by on multiple columnsDynamic Order by SELECT with multiple columnsSQL select only rows with max value on a column

Are neural networks prone to catastrophic forgetting?

How can an advanced civilization forget how to manufacture its technology?

Print the last, middle and first character of your code

Who has taken "my" Managed package namespace? Can we find out?

What are the bumps on the Vega rocket

Maximum charterer insertion

Single word for "refusing to move to next activity unless present one is completed."

Novel where a group of scientists in a spaceship encounter various aliens

Why are they 'nude photos'?

Are randomly-generated passwords starting with "a" less secure?

CentOS 7 -> find: missing Argument for "-exec"

How to know whether a Tamron lens is compatible with Canon EOS 60D?

Is "take care'n of" correct?

When casting Eldritch Blast with the Agonizing Blast eldritch invocation, what do I add to my damage roll?

Referring to different instances of the same character in time travel

If your plane is out-of-control, why does military training instruct releasing the joystick to neutralize controls?

Is anyone advocating the promotion of homosexuality in UK schools?

Does throwing a penny at a train stop the train?

3D print appears to print very weak walls in long print

ESTA: "Is your travel to the US occurring in transit to another country?" when going on a cruise

Shortest distance around a pyramid?

Flatten array with OPENJSON: OPENJSON on a value that may not be an array? [ [1] ], vs [1]

Is there any word for "disobedience to God"?

Machine learning and operations research projects



PostgresSQL ORDER BY clause with CASE for sorted column


Add a column with a default value to an existing table in SQL ServerParameterize an SQL IN clauseSQL join: where clause vs. on clauseSQLite - UPSERT *not* INSERT or REPLACEHow do I insert into a table if a value does not exist, but only for certain criteria? (MS SQL Server)INNER JOIN ON vs WHERE clauseSQL multiple column orderingUsing group by on multiple columnsDynamic Order by SELECT with multiple columnsSQL select only rows with max value on a column






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I have a simple form of SELECT ORDER BY query which is using CASE for creating sorted id's.
I referred two approaches based on https://gist.github.com/cpjolicoeur/3590737 and used one of them.



SELECT id FROM tasks t ORDER BY 
CASE
WHEN t.type = 'TypeA' THEN 1
WHEN t.type = 'TypeB' THEN 2
WHEN t.type = 'TypeC' THEN 3
END,
CASE
WHEN t.state = 'Interrupted' THEN 4
WHEN t.state = 'Terminated' THEN 5
WHEN t.state = 'Completed' THEN 6
WHEN t.state = 'Killed' THEN 7
WHEN t.state = 'Warning' THEN 8
WHEN t.state = 'Starting' THEN 9
WHEN t.state = 'New' THEN 10
WHEN t.state = 'Running' THEN 11
END,
modified ASC;


The above query is based on below criteria to sort ids:



  1. TypeA with state:
    Interrupted,Terminated,Completed,Killed,Warning,Starting,New,Running

  2. TypeB with state:
    Interrupted,Terminated,Completed,Killed,Warning,Starting,New,Running

  3. TypeC with state:
    Interrupted,Terminated,Completed,Killed,Warning,Starting,New,Running

I need to modify this sql for below sorting criteria now:



  1. TypeA with state: Interrupted,Terminated,Completed,Killed

  2. TypeB with state: Interrupted,Terminated,Completed,Killed

  3. TypeC with state: Interrupted,Terminated

  4. TypeA with state: Warning,Starting,New,Running

  5. TypeB with state: Warning,Starting,New,Running

  6. TypeC with state: Completed,Killed,Warning,Starting,New,Running

Please note the ordering of 'state'(as specified) is equally important here for a 'type'



I am trying to modify above sql so that it meets the new criteria. Being not an sql expert I am looking for most efficient way to rewrite this sql which could also accommodate slight changes on sorting criteria in near future.



To further clarify sharing example below:



sample data



id | type | state
----+-------+-------------
1 | TypeC | Completed
2 | TypeA | Completed
3 | TypeA | Running
4 | TypeB | Completed
5 | TypeB | Running
6 | TypeC | Terminated
7 | TypeC | Unknown
8 | TypeA | Completed
9 | TypeB | Interrupted
10 | TypeB | Completed
11 | TypeB | Interrupted
12 | TypeC | Killed
13 | TypeC | Running
14 | TypeB | Warning
15 | TypeB | Running
16 | TypeB | Killed


expected data



id | type | state
--- +-------+-------------
1 | TypeA | Completed
8 | TypeA | Completed
9 | TypeB | Interrupted
11 | TypeB | Interrupted
4 | TypeB | Completed
10 | TypeB | Completed
16 | TypeB | Killed
7 | TypeC | Unknown
6 | TypeC | Terminated
3 | TypeA | Running
14 | TypeB | Warning
5 | TypeB | Running
15 | TypeB | Running
1 | TypeC | Completed
12 | TypeC | Killed
13 | TypeC | Running









share|improve this question






























    0















    I have a simple form of SELECT ORDER BY query which is using CASE for creating sorted id's.
    I referred two approaches based on https://gist.github.com/cpjolicoeur/3590737 and used one of them.



    SELECT id FROM tasks t ORDER BY 
    CASE
    WHEN t.type = 'TypeA' THEN 1
    WHEN t.type = 'TypeB' THEN 2
    WHEN t.type = 'TypeC' THEN 3
    END,
    CASE
    WHEN t.state = 'Interrupted' THEN 4
    WHEN t.state = 'Terminated' THEN 5
    WHEN t.state = 'Completed' THEN 6
    WHEN t.state = 'Killed' THEN 7
    WHEN t.state = 'Warning' THEN 8
    WHEN t.state = 'Starting' THEN 9
    WHEN t.state = 'New' THEN 10
    WHEN t.state = 'Running' THEN 11
    END,
    modified ASC;


    The above query is based on below criteria to sort ids:



    1. TypeA with state:
      Interrupted,Terminated,Completed,Killed,Warning,Starting,New,Running

    2. TypeB with state:
      Interrupted,Terminated,Completed,Killed,Warning,Starting,New,Running

    3. TypeC with state:
      Interrupted,Terminated,Completed,Killed,Warning,Starting,New,Running

    I need to modify this sql for below sorting criteria now:



    1. TypeA with state: Interrupted,Terminated,Completed,Killed

    2. TypeB with state: Interrupted,Terminated,Completed,Killed

    3. TypeC with state: Interrupted,Terminated

    4. TypeA with state: Warning,Starting,New,Running

    5. TypeB with state: Warning,Starting,New,Running

    6. TypeC with state: Completed,Killed,Warning,Starting,New,Running

    Please note the ordering of 'state'(as specified) is equally important here for a 'type'



    I am trying to modify above sql so that it meets the new criteria. Being not an sql expert I am looking for most efficient way to rewrite this sql which could also accommodate slight changes on sorting criteria in near future.



    To further clarify sharing example below:



    sample data



    id | type | state
    ----+-------+-------------
    1 | TypeC | Completed
    2 | TypeA | Completed
    3 | TypeA | Running
    4 | TypeB | Completed
    5 | TypeB | Running
    6 | TypeC | Terminated
    7 | TypeC | Unknown
    8 | TypeA | Completed
    9 | TypeB | Interrupted
    10 | TypeB | Completed
    11 | TypeB | Interrupted
    12 | TypeC | Killed
    13 | TypeC | Running
    14 | TypeB | Warning
    15 | TypeB | Running
    16 | TypeB | Killed


    expected data



    id | type | state
    --- +-------+-------------
    1 | TypeA | Completed
    8 | TypeA | Completed
    9 | TypeB | Interrupted
    11 | TypeB | Interrupted
    4 | TypeB | Completed
    10 | TypeB | Completed
    16 | TypeB | Killed
    7 | TypeC | Unknown
    6 | TypeC | Terminated
    3 | TypeA | Running
    14 | TypeB | Warning
    5 | TypeB | Running
    15 | TypeB | Running
    1 | TypeC | Completed
    12 | TypeC | Killed
    13 | TypeC | Running









    share|improve this question


























      0












      0








      0








      I have a simple form of SELECT ORDER BY query which is using CASE for creating sorted id's.
      I referred two approaches based on https://gist.github.com/cpjolicoeur/3590737 and used one of them.



      SELECT id FROM tasks t ORDER BY 
      CASE
      WHEN t.type = 'TypeA' THEN 1
      WHEN t.type = 'TypeB' THEN 2
      WHEN t.type = 'TypeC' THEN 3
      END,
      CASE
      WHEN t.state = 'Interrupted' THEN 4
      WHEN t.state = 'Terminated' THEN 5
      WHEN t.state = 'Completed' THEN 6
      WHEN t.state = 'Killed' THEN 7
      WHEN t.state = 'Warning' THEN 8
      WHEN t.state = 'Starting' THEN 9
      WHEN t.state = 'New' THEN 10
      WHEN t.state = 'Running' THEN 11
      END,
      modified ASC;


      The above query is based on below criteria to sort ids:



      1. TypeA with state:
        Interrupted,Terminated,Completed,Killed,Warning,Starting,New,Running

      2. TypeB with state:
        Interrupted,Terminated,Completed,Killed,Warning,Starting,New,Running

      3. TypeC with state:
        Interrupted,Terminated,Completed,Killed,Warning,Starting,New,Running

      I need to modify this sql for below sorting criteria now:



      1. TypeA with state: Interrupted,Terminated,Completed,Killed

      2. TypeB with state: Interrupted,Terminated,Completed,Killed

      3. TypeC with state: Interrupted,Terminated

      4. TypeA with state: Warning,Starting,New,Running

      5. TypeB with state: Warning,Starting,New,Running

      6. TypeC with state: Completed,Killed,Warning,Starting,New,Running

      Please note the ordering of 'state'(as specified) is equally important here for a 'type'



      I am trying to modify above sql so that it meets the new criteria. Being not an sql expert I am looking for most efficient way to rewrite this sql which could also accommodate slight changes on sorting criteria in near future.



      To further clarify sharing example below:



      sample data



      id | type | state
      ----+-------+-------------
      1 | TypeC | Completed
      2 | TypeA | Completed
      3 | TypeA | Running
      4 | TypeB | Completed
      5 | TypeB | Running
      6 | TypeC | Terminated
      7 | TypeC | Unknown
      8 | TypeA | Completed
      9 | TypeB | Interrupted
      10 | TypeB | Completed
      11 | TypeB | Interrupted
      12 | TypeC | Killed
      13 | TypeC | Running
      14 | TypeB | Warning
      15 | TypeB | Running
      16 | TypeB | Killed


      expected data



      id | type | state
      --- +-------+-------------
      1 | TypeA | Completed
      8 | TypeA | Completed
      9 | TypeB | Interrupted
      11 | TypeB | Interrupted
      4 | TypeB | Completed
      10 | TypeB | Completed
      16 | TypeB | Killed
      7 | TypeC | Unknown
      6 | TypeC | Terminated
      3 | TypeA | Running
      14 | TypeB | Warning
      5 | TypeB | Running
      15 | TypeB | Running
      1 | TypeC | Completed
      12 | TypeC | Killed
      13 | TypeC | Running









      share|improve this question
















      I have a simple form of SELECT ORDER BY query which is using CASE for creating sorted id's.
      I referred two approaches based on https://gist.github.com/cpjolicoeur/3590737 and used one of them.



      SELECT id FROM tasks t ORDER BY 
      CASE
      WHEN t.type = 'TypeA' THEN 1
      WHEN t.type = 'TypeB' THEN 2
      WHEN t.type = 'TypeC' THEN 3
      END,
      CASE
      WHEN t.state = 'Interrupted' THEN 4
      WHEN t.state = 'Terminated' THEN 5
      WHEN t.state = 'Completed' THEN 6
      WHEN t.state = 'Killed' THEN 7
      WHEN t.state = 'Warning' THEN 8
      WHEN t.state = 'Starting' THEN 9
      WHEN t.state = 'New' THEN 10
      WHEN t.state = 'Running' THEN 11
      END,
      modified ASC;


      The above query is based on below criteria to sort ids:



      1. TypeA with state:
        Interrupted,Terminated,Completed,Killed,Warning,Starting,New,Running

      2. TypeB with state:
        Interrupted,Terminated,Completed,Killed,Warning,Starting,New,Running

      3. TypeC with state:
        Interrupted,Terminated,Completed,Killed,Warning,Starting,New,Running

      I need to modify this sql for below sorting criteria now:



      1. TypeA with state: Interrupted,Terminated,Completed,Killed

      2. TypeB with state: Interrupted,Terminated,Completed,Killed

      3. TypeC with state: Interrupted,Terminated

      4. TypeA with state: Warning,Starting,New,Running

      5. TypeB with state: Warning,Starting,New,Running

      6. TypeC with state: Completed,Killed,Warning,Starting,New,Running

      Please note the ordering of 'state'(as specified) is equally important here for a 'type'



      I am trying to modify above sql so that it meets the new criteria. Being not an sql expert I am looking for most efficient way to rewrite this sql which could also accommodate slight changes on sorting criteria in near future.



      To further clarify sharing example below:



      sample data



      id | type | state
      ----+-------+-------------
      1 | TypeC | Completed
      2 | TypeA | Completed
      3 | TypeA | Running
      4 | TypeB | Completed
      5 | TypeB | Running
      6 | TypeC | Terminated
      7 | TypeC | Unknown
      8 | TypeA | Completed
      9 | TypeB | Interrupted
      10 | TypeB | Completed
      11 | TypeB | Interrupted
      12 | TypeC | Killed
      13 | TypeC | Running
      14 | TypeB | Warning
      15 | TypeB | Running
      16 | TypeB | Killed


      expected data



      id | type | state
      --- +-------+-------------
      1 | TypeA | Completed
      8 | TypeA | Completed
      9 | TypeB | Interrupted
      11 | TypeB | Interrupted
      4 | TypeB | Completed
      10 | TypeB | Completed
      16 | TypeB | Killed
      7 | TypeC | Unknown
      6 | TypeC | Terminated
      3 | TypeA | Running
      14 | TypeB | Warning
      5 | TypeB | Running
      15 | TypeB | Running
      1 | TypeC | Completed
      12 | TypeC | Killed
      13 | TypeC | Running






      sql postgresql






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 26 at 9:24







      akhi

















      asked Mar 26 at 3:10









      akhiakhi

      2441 gold badge7 silver badges20 bronze badges




      2441 gold badge7 silver badges20 bronze badges






















          1 Answer
          1






          active

          oldest

          votes


















          1














          Maybe something like this?



          CASE 
          WHEN t.type = 'TypeA' AND t.state
          IN ( 'Interrupted','Terminated','Completed','Killed')
          THEN 1
          WHEN t.type = 'TypeB' AND t.state
          IN ( 'Interrupted','Terminated','Completed','Killed')
          THEN 2
          ..
          ..


          EDIT



          I would recommend you to create a hierarchy table, this way your query gets simpler.



          CREATE TABLE type_state_hier AS
          select * FROM
          (
          VALUES
          (1,'TypeA','Interrupted'),
          (2,'TypeA','Terminated'),
          (3,'TypeA','Completed'),
          (4,'TypeA','Killed'),
          (5,'TypeB','Interrupted'),
          (6,'TypeB','Terminated'),
          (7,'TypeB','Completed'),
          (8,'TypeB','Killed'),
          (9,'TypeC','Interrupted'),
          (10,'TypeC','Terminated'),
          (11,'TypeA','Warning'),
          (12,'TypeA','Starting'),
          (13,'TypeA','New'),
          (14,'TypeA','Running'),
          (15,'TypeB','Warning'),
          (16,'TypeB','Starting'),
          (17,'TypeB','New'),
          (18,'TypeB','Running'),
          (19,'TypeC','Completed'),
          (20,'TypeC','Killed'),
          (21,'TypeC','Warning'),
          (22,'TypeC','Starting'),
          (23,'TypeC','New'),
          (24,'TypeC','Running')
          ) As s(rnk,type,state)
          ;


          Now, query it with a simple join with your main table.



          select t.* from tasks t 
          join type_state_hier h on
          h.type=t.type and h.state = t.state
          order by h.rnk ,t.id


          If you don't want to create a table, simply use it as a CTE (refer demo)



          DEMO






          share|improve this answer

























          • Does it ensure the desired state ordering is achieved?

            – akhi
            Mar 26 at 3:40











          • @akhi : how will I know? You mentioned it, without providing any sample data/ expected output to describe your question.

            – Kaushik Nayak
            Mar 26 at 3:46












          • okay, so IN ensures the match is done based on the ordering that we specify i.e in braces (1,2 ,3,4...)

            – akhi
            Mar 26 at 3:51











          • @akhi : it doesn't. as I said, you didn't make it clear in your question.

            – Kaushik Nayak
            Mar 26 at 3:53











          • sorry if it was not clear, have added a note and edited the question. Actually the original query ensures the ordering of state as well.

            – akhi
            Mar 26 at 3:57










          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%2f55349296%2fpostgressql-order-by-clause-with-case-for-sorted-column%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          Maybe something like this?



          CASE 
          WHEN t.type = 'TypeA' AND t.state
          IN ( 'Interrupted','Terminated','Completed','Killed')
          THEN 1
          WHEN t.type = 'TypeB' AND t.state
          IN ( 'Interrupted','Terminated','Completed','Killed')
          THEN 2
          ..
          ..


          EDIT



          I would recommend you to create a hierarchy table, this way your query gets simpler.



          CREATE TABLE type_state_hier AS
          select * FROM
          (
          VALUES
          (1,'TypeA','Interrupted'),
          (2,'TypeA','Terminated'),
          (3,'TypeA','Completed'),
          (4,'TypeA','Killed'),
          (5,'TypeB','Interrupted'),
          (6,'TypeB','Terminated'),
          (7,'TypeB','Completed'),
          (8,'TypeB','Killed'),
          (9,'TypeC','Interrupted'),
          (10,'TypeC','Terminated'),
          (11,'TypeA','Warning'),
          (12,'TypeA','Starting'),
          (13,'TypeA','New'),
          (14,'TypeA','Running'),
          (15,'TypeB','Warning'),
          (16,'TypeB','Starting'),
          (17,'TypeB','New'),
          (18,'TypeB','Running'),
          (19,'TypeC','Completed'),
          (20,'TypeC','Killed'),
          (21,'TypeC','Warning'),
          (22,'TypeC','Starting'),
          (23,'TypeC','New'),
          (24,'TypeC','Running')
          ) As s(rnk,type,state)
          ;


          Now, query it with a simple join with your main table.



          select t.* from tasks t 
          join type_state_hier h on
          h.type=t.type and h.state = t.state
          order by h.rnk ,t.id


          If you don't want to create a table, simply use it as a CTE (refer demo)



          DEMO






          share|improve this answer

























          • Does it ensure the desired state ordering is achieved?

            – akhi
            Mar 26 at 3:40











          • @akhi : how will I know? You mentioned it, without providing any sample data/ expected output to describe your question.

            – Kaushik Nayak
            Mar 26 at 3:46












          • okay, so IN ensures the match is done based on the ordering that we specify i.e in braces (1,2 ,3,4...)

            – akhi
            Mar 26 at 3:51











          • @akhi : it doesn't. as I said, you didn't make it clear in your question.

            – Kaushik Nayak
            Mar 26 at 3:53











          • sorry if it was not clear, have added a note and edited the question. Actually the original query ensures the ordering of state as well.

            – akhi
            Mar 26 at 3:57















          1














          Maybe something like this?



          CASE 
          WHEN t.type = 'TypeA' AND t.state
          IN ( 'Interrupted','Terminated','Completed','Killed')
          THEN 1
          WHEN t.type = 'TypeB' AND t.state
          IN ( 'Interrupted','Terminated','Completed','Killed')
          THEN 2
          ..
          ..


          EDIT



          I would recommend you to create a hierarchy table, this way your query gets simpler.



          CREATE TABLE type_state_hier AS
          select * FROM
          (
          VALUES
          (1,'TypeA','Interrupted'),
          (2,'TypeA','Terminated'),
          (3,'TypeA','Completed'),
          (4,'TypeA','Killed'),
          (5,'TypeB','Interrupted'),
          (6,'TypeB','Terminated'),
          (7,'TypeB','Completed'),
          (8,'TypeB','Killed'),
          (9,'TypeC','Interrupted'),
          (10,'TypeC','Terminated'),
          (11,'TypeA','Warning'),
          (12,'TypeA','Starting'),
          (13,'TypeA','New'),
          (14,'TypeA','Running'),
          (15,'TypeB','Warning'),
          (16,'TypeB','Starting'),
          (17,'TypeB','New'),
          (18,'TypeB','Running'),
          (19,'TypeC','Completed'),
          (20,'TypeC','Killed'),
          (21,'TypeC','Warning'),
          (22,'TypeC','Starting'),
          (23,'TypeC','New'),
          (24,'TypeC','Running')
          ) As s(rnk,type,state)
          ;


          Now, query it with a simple join with your main table.



          select t.* from tasks t 
          join type_state_hier h on
          h.type=t.type and h.state = t.state
          order by h.rnk ,t.id


          If you don't want to create a table, simply use it as a CTE (refer demo)



          DEMO






          share|improve this answer

























          • Does it ensure the desired state ordering is achieved?

            – akhi
            Mar 26 at 3:40











          • @akhi : how will I know? You mentioned it, without providing any sample data/ expected output to describe your question.

            – Kaushik Nayak
            Mar 26 at 3:46












          • okay, so IN ensures the match is done based on the ordering that we specify i.e in braces (1,2 ,3,4...)

            – akhi
            Mar 26 at 3:51











          • @akhi : it doesn't. as I said, you didn't make it clear in your question.

            – Kaushik Nayak
            Mar 26 at 3:53











          • sorry if it was not clear, have added a note and edited the question. Actually the original query ensures the ordering of state as well.

            – akhi
            Mar 26 at 3:57













          1












          1








          1







          Maybe something like this?



          CASE 
          WHEN t.type = 'TypeA' AND t.state
          IN ( 'Interrupted','Terminated','Completed','Killed')
          THEN 1
          WHEN t.type = 'TypeB' AND t.state
          IN ( 'Interrupted','Terminated','Completed','Killed')
          THEN 2
          ..
          ..


          EDIT



          I would recommend you to create a hierarchy table, this way your query gets simpler.



          CREATE TABLE type_state_hier AS
          select * FROM
          (
          VALUES
          (1,'TypeA','Interrupted'),
          (2,'TypeA','Terminated'),
          (3,'TypeA','Completed'),
          (4,'TypeA','Killed'),
          (5,'TypeB','Interrupted'),
          (6,'TypeB','Terminated'),
          (7,'TypeB','Completed'),
          (8,'TypeB','Killed'),
          (9,'TypeC','Interrupted'),
          (10,'TypeC','Terminated'),
          (11,'TypeA','Warning'),
          (12,'TypeA','Starting'),
          (13,'TypeA','New'),
          (14,'TypeA','Running'),
          (15,'TypeB','Warning'),
          (16,'TypeB','Starting'),
          (17,'TypeB','New'),
          (18,'TypeB','Running'),
          (19,'TypeC','Completed'),
          (20,'TypeC','Killed'),
          (21,'TypeC','Warning'),
          (22,'TypeC','Starting'),
          (23,'TypeC','New'),
          (24,'TypeC','Running')
          ) As s(rnk,type,state)
          ;


          Now, query it with a simple join with your main table.



          select t.* from tasks t 
          join type_state_hier h on
          h.type=t.type and h.state = t.state
          order by h.rnk ,t.id


          If you don't want to create a table, simply use it as a CTE (refer demo)



          DEMO






          share|improve this answer















          Maybe something like this?



          CASE 
          WHEN t.type = 'TypeA' AND t.state
          IN ( 'Interrupted','Terminated','Completed','Killed')
          THEN 1
          WHEN t.type = 'TypeB' AND t.state
          IN ( 'Interrupted','Terminated','Completed','Killed')
          THEN 2
          ..
          ..


          EDIT



          I would recommend you to create a hierarchy table, this way your query gets simpler.



          CREATE TABLE type_state_hier AS
          select * FROM
          (
          VALUES
          (1,'TypeA','Interrupted'),
          (2,'TypeA','Terminated'),
          (3,'TypeA','Completed'),
          (4,'TypeA','Killed'),
          (5,'TypeB','Interrupted'),
          (6,'TypeB','Terminated'),
          (7,'TypeB','Completed'),
          (8,'TypeB','Killed'),
          (9,'TypeC','Interrupted'),
          (10,'TypeC','Terminated'),
          (11,'TypeA','Warning'),
          (12,'TypeA','Starting'),
          (13,'TypeA','New'),
          (14,'TypeA','Running'),
          (15,'TypeB','Warning'),
          (16,'TypeB','Starting'),
          (17,'TypeB','New'),
          (18,'TypeB','Running'),
          (19,'TypeC','Completed'),
          (20,'TypeC','Killed'),
          (21,'TypeC','Warning'),
          (22,'TypeC','Starting'),
          (23,'TypeC','New'),
          (24,'TypeC','Running')
          ) As s(rnk,type,state)
          ;


          Now, query it with a simple join with your main table.



          select t.* from tasks t 
          join type_state_hier h on
          h.type=t.type and h.state = t.state
          order by h.rnk ,t.id


          If you don't want to create a table, simply use it as a CTE (refer demo)



          DEMO







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 26 at 10:29

























          answered Mar 26 at 3:33









          Kaushik NayakKaushik Nayak

          24.9k5 gold badges14 silver badges33 bronze badges




          24.9k5 gold badges14 silver badges33 bronze badges












          • Does it ensure the desired state ordering is achieved?

            – akhi
            Mar 26 at 3:40











          • @akhi : how will I know? You mentioned it, without providing any sample data/ expected output to describe your question.

            – Kaushik Nayak
            Mar 26 at 3:46












          • okay, so IN ensures the match is done based on the ordering that we specify i.e in braces (1,2 ,3,4...)

            – akhi
            Mar 26 at 3:51











          • @akhi : it doesn't. as I said, you didn't make it clear in your question.

            – Kaushik Nayak
            Mar 26 at 3:53











          • sorry if it was not clear, have added a note and edited the question. Actually the original query ensures the ordering of state as well.

            – akhi
            Mar 26 at 3:57

















          • Does it ensure the desired state ordering is achieved?

            – akhi
            Mar 26 at 3:40











          • @akhi : how will I know? You mentioned it, without providing any sample data/ expected output to describe your question.

            – Kaushik Nayak
            Mar 26 at 3:46












          • okay, so IN ensures the match is done based on the ordering that we specify i.e in braces (1,2 ,3,4...)

            – akhi
            Mar 26 at 3:51











          • @akhi : it doesn't. as I said, you didn't make it clear in your question.

            – Kaushik Nayak
            Mar 26 at 3:53











          • sorry if it was not clear, have added a note and edited the question. Actually the original query ensures the ordering of state as well.

            – akhi
            Mar 26 at 3:57
















          Does it ensure the desired state ordering is achieved?

          – akhi
          Mar 26 at 3:40





          Does it ensure the desired state ordering is achieved?

          – akhi
          Mar 26 at 3:40













          @akhi : how will I know? You mentioned it, without providing any sample data/ expected output to describe your question.

          – Kaushik Nayak
          Mar 26 at 3:46






          @akhi : how will I know? You mentioned it, without providing any sample data/ expected output to describe your question.

          – Kaushik Nayak
          Mar 26 at 3:46














          okay, so IN ensures the match is done based on the ordering that we specify i.e in braces (1,2 ,3,4...)

          – akhi
          Mar 26 at 3:51





          okay, so IN ensures the match is done based on the ordering that we specify i.e in braces (1,2 ,3,4...)

          – akhi
          Mar 26 at 3:51













          @akhi : it doesn't. as I said, you didn't make it clear in your question.

          – Kaushik Nayak
          Mar 26 at 3:53





          @akhi : it doesn't. as I said, you didn't make it clear in your question.

          – Kaushik Nayak
          Mar 26 at 3:53













          sorry if it was not clear, have added a note and edited the question. Actually the original query ensures the ordering of state as well.

          – akhi
          Mar 26 at 3:57





          sorry if it was not clear, have added a note and edited the question. Actually the original query ensures the ordering of state as well.

          – akhi
          Mar 26 at 3:57








          Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







          Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















          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%2f55349296%2fpostgressql-order-by-clause-with-case-for-sorted-column%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

          Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

          SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

          은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현