1

I just started learning how to code. I was wondering how to combine multiple SELECT statements in one query.

SELECT count(*) AS "SENT" FROM message_items WHERE status = 'SENT';

SELECT count(*)  AS "NOT SENT" FROM message_items WHERE status = 'NOT SENT';

SELECT count(*) AS "INVALID NUMBER" FROM message_items WHERE status = 'INVALID NUMBER';

2 Answers 2

3

Use conditional aggregation:

SELECT
    COUNT(*) FILTER (WHERE status = 'SENT') AS "SENT",
    COUNT(*) FILTER (WHERE status = 'NOT SET') AS "NOT SENT",
    COUNT(*) FILTER (WHERE status = 'INVALID NUMBER') AS "INVALID NUMBER"
FROM message_items;

If you wanted to generate counts over the entire table, then the above is suitable. If instead you want to generate counts per some other column, then just add that column to the above select clause and then aggregate by that column using GROUP BY.

Sign up to request clarification or add additional context in comments.

1 Comment

It worked! Thanks for also providing the term so I could read up on it. :D
0

You can use GROUP BY

SELECT count(*), status FROM message_items GROUP BY status;

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.