Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group results to boolean value in PostgreSQL

Tags:

sql

postgresql

I have a query which returns

Select bool_val
from .....

The query returns many rows with values of True or False or no rows at all.

I want the query to ALWAYS return True Or False based on condition that if there is one true the result is True otherwise False.

For example: query result:

False
False
True
False

Should return True.

query result:

False
False

Should return False.

query result:

no rows

Should return False since the query is empty.

How can I do that with a query without IFs using PostgreSQL?

like image 555
avi Avatar asked Feb 23 '17 08:02

avi


People also ask

How do I give a boolean value in PostgreSQL?

PostgreSQL supports a single Boolean data type: BOOLEAN that can have three values: true , false and NULL . PostgreSQL uses one byte for storing a boolean value in the database. The BOOLEAN can be abbreviated as BOOL . In standard SQL, a Boolean value can be TRUE , FALSE , or NULL .

Is there a Boolean data type in PostgreSQL?

PostgreSQL provides the standard SQL type boolean ; see Table 8.19. The boolean type can have several states: “true”, “false”, and a third state, “unknown”, which is represented by the SQL null value.

How do I create a boolean column in PostgreSQL?

Alter table users add column priv_user boolean default false ; boolean value (true-false) save in DB like (t-f) value . Show activity on this post. If you are using postgresql then you have to use column type BOOLEAN in lower case as boolean.

What is the difference between Bool and boolean in PostgreSQL?

PostgreSQL Boolean is a simple data type that we have used to represent only the structure of true or false data or values. PostgreSQL will support the SQL99 defined Boolean data type of SQL standard; Boolean is also known as “bool”, bool is an alias of Boolean data type in PostgreSQL.


1 Answers

You can use a boolean aggregate:

select bool_or(bool_val)
from the_table;

To also get a false when the table contains no rows, use coalesce() (thanks Elad)

select coalesce(bool_or(bool_val), false)
from the_table;

Another - possibly faster - option is:

select exists (select 1 from the_table where bool_val)
like image 139
a_horse_with_no_name Avatar answered Sep 28 '22 09:09

a_horse_with_no_name