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?
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 .
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With