PostgreSQL Boolean Data Type with Practical Examples
Summary: in this tutorial, you will learn about the PostgreSQL Boolean data type and how to use it in designing database tables.
Introduction to the PostgreSQL Boolean type
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
. However, PostgreSQL is quite flexible when dealing with TRUE
and FALSE
values.
The following table shows the valid literal values for TRUE
and FALSE
in PostgreSQL.
True | False |
---|---|
true | false |
‘t’ | ‘f ‘ |
‘true’ | ‘false’ |
‘y’ | ‘n’ |
‘yes’ | ‘no’ |
‘1’ | ‘0’ |
Note that the leading or trailing whitespace does not matter and all the constant values except for true
and false
must be enclosed in single quotes.
PostgreSQL Boolean examples
Let’s take a look at some examples of using the PostgreSQL Boolean data type.
First, create a new table called stock_availability
to log which products are available.
Second, insert some sample data into the stock_availability
table. We use various literal values for the boolean values.
Third, check for the availability of products:
You can imply the true value by using the Boolean column without any operator. For example, the following query returns all available products:
Similarly, if you want to look for false
values, you compare the value of the Boolean column against any valid Boolean constants.
The following query returns the products that are not available.
Alternatively, you can use the NOT
operator to check if values in the Boolean column are false like this:
Set the default values for Boolean columns
To set a default value for an existing Boolean column, you use the SET DEFAULT
clause in the ALTER TABLE statement.
For example, the following ALTER TABLE
statement sets the default value for the available
column in the stock_availability
table:
If you insert a row without specifying the value for the available
column, PostgreSQL will use FALSE
by default:
Likewise, if you want to set a default value for a Boolean column when you create a table, you use the DEFAULT
constraint in the column definition as follows:
Summary
- Use the PostgreSQL
BOOLEAN
datatype to store the boolean data.