skip to Main Content

I have a SQL query that sorts a table for a local restaurant into categories, but after that I would like to sort alphabetically by title. The end result should sort the categories, and then the content is sorted alphabetically by the title field (like "ORDER BY category, title ASC", only the category gets sorted by case).

My query is

SELECT *
FROM menu
ORDER BY CASE WHEN category = 'Appetizers' THEN 1
              WHEN category = 'Entrees' THEN 2
              WHEN category = 'Desserts' THEN 3
          WHEN category = 'Beverages' THEN 4
          END

I tried adding ", title ASC" to each line, and after the END but it came up as an error. Can this be done at all?

2

Answers


  1. It behaves like any other ORDER sorting

    first it will sort by the CASE and then every entry with the same category by title

    SELECT *
    FROM menu
    ORDER BY CASE WHEN category = 'Appetizers' THEN 1
                  WHEN category = 'Entrees' THEN 2
                  WHEN category = 'Desserts' THEN 3
              WHEN category = 'Beverages' THEN 4
              ELSE 5
              END ASC, title ASC
    
    Login or Signup to reply.
  2. Just need to add title in the ORDER BY clause after the CASE expression.This will sort the data by category based on the CASE and then the title within each category group.

    Query

    SELECT *
    FROM menu
    ORDER BY CASE WHEN category = 'Appetizers' THEN 1
              WHEN category = 'Entrees' THEN 2
              WHEN category = 'Desserts' THEN 3
          WHEN category = 'Beverages' THEN 4
          END, title;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search