HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlModerate

How to count boolean values in PostgreSQL?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
postgresqlbooleanhowvaluescount

Problem

How to count, how may true and false for the field public in postgresql user table
i have tried this query

select 
sum(case when false then 1 else 0 end) as false, 
sum(case when true then 1 else 0 end) as true
from  public.user;


but am not getting any value and if i remove public from query then i will get correct counts only i have value true

table : name|   DOB     | public
values : bb | 20/2/1991/| true

op : true = 1 and false  = 0


but am getting the same answer when i make public as false

table : name|   DOB     | public
values : bb | 20/2/1991/| false

op : true = 1 and false  = 0


so someone please help me to solve this

Solution

Use the filter() clause:

select count(*) filter (where "public") as public_count,
       count(*) filter (where not "public") as not_public_count
from  public."user";


Note that user is a reserved keyword, you have to use double quotes in order to use it as a table name.

The above assumes that the column public is of type boolean

Code Snippets

select count(*) filter (where "public") as public_count,
       count(*) filter (where not "public") as not_public_count
from  public."user";

Context

StackExchange Database Administrators Q#205012, answer score: 15

Revisions (0)

No revisions yet.