1

I am executing this query

SELECT COUNT(designer_orders.id) as pr, 
       SUM(IF designer_orders.package_status == 'packed' THEN 0 ELSE 1 END) as pu 
FROM "designer_orders"

Expected output

PR PU
10 5

Getting Output

PR PU
10 0

This block of query not working as expected

SUM(IF designer_orders.package_status == 'packed' THEN 0 ELSE 1 END)
2
  • 1
    That query will not work at all because SQL does not have an IF statement. You need to use CASE Commented Mar 12, 2014 at 10:53
  • @a_horse_with_no_name i just saw if in postgresql documentation. by the way how do i use 'CASE' Commented Mar 12, 2014 at 10:56

2 Answers 2

4

There is no IF in SQL, you need to use CASE.

Additionally the equality operator in SQL is = not ==

SELECT COUNT(id) as pr, 
       SUM(CASE WHEN package_status = 'packed' THEN 0 ELSE 1 END) as pu 
FROM designer_orders;

For an introduction into SQL, please see this chapter of the manual: http://www.postgresql.org/docs/current/static/tutorial-sql.html

For a description of available operators, please see here: http://www.postgresql.org/docs/current/static/functions-conditional.html

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

1 Comment

CASE WHEN should be used here
3

Try this:

SELECT COUNT(designer_orders.id) as pr, SUM(CASE WHEN designer_orders.package_status = 'packed' THEN 0 ELSE 1 END) as pu FROM "designer_orders"

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.