2

I have this table as an example:

CREATE TABLE "public"."items" (
    "name" text NOT NULL,
    "type" text NOT NULL
)

With initial values:

INSERT INTO "items" ("name", "type") VALUES
('apple',   'fruit'),
('banana',  'fruit'),
('chair',   'furniture'),
('table',   'furniture'),
('grape',   'fruit'),
('cabbage', 'vegetable'),
('beef',    'meat'),
('water',   'drinks'),
('lamp',    'furniture');

How can I query rows from this table with one statement so that I get the rows with the fruit type first?

Given that:

  • There's a lot of types (could be in thousands of different types)
  • I don't care the order of the result other than I want to prioritize getting fruit type first

For example if I want to query 5 rows from this table, the result would be 'apple', 'banana', 'grape', 'cabbage' and 'beef'.

1
  • @wildplasser Thank you, that solves it! Commented Sep 13, 2021 at 10:33

1 Answer 1

4

You can use a boolean expression as the first ORDER BY expression:


SELECT * FROM items
ORDER BY (type='fruit') DESC, name
   ;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.