Introduction to PostgreSQL boolean Data Type
The boolean
data type in PostgreSQL is used to store boolean values, which represent true or false. This data type can only store one of two values. In PostgreSQL, boolean
data type is one of the basic data types.
Syntax
In PostgreSQL, you can use the following syntax to create a column with boolean
data type:
column_name BOOLEAN
Use Cases
The boolean
data type is commonly used to store data with two possible states. For example, switch status (on or off), completion status (completed or not), etc. In queries, boolean
data type can be used as conditions in WHERE clauses. It can also be used in comparison with other data types such as strings or numbers.
Examples
Here are two examples of using boolean
data type:
-
Storing switch status
Let’s assume we have a table called
switch
with two columns,id
andis_on
. You can create this table using the following command:CREATE TABLE switch ( id SERIAL PRIMARY KEY, is_on BOOLEAN );
Next, you can insert values into the
is_on
column:INSERT INTO switch (is_on) VALUES (true); INSERT INTO switch (is_on) VALUES (false);
You can retrieve the values of the
is_on
column using the following query:SELECT id, is_on FROM switch;
This query will return the following result:
id | is_on ----+------- 1 | true 2 | false
-
Storing completion status
Let’s assume we have a table called
tasks
with two columns,id
andcompleted
. You can create this table using the following command:CREATE TABLE tasks ( id SERIAL PRIMARY KEY, completed BOOLEAN );
Next, you can insert values into the
completed
column:INSERT INTO tasks (completed) VALUES (false); INSERT INTO tasks (completed) VALUES (true);
You can retrieve the values of the
completed
column using the following query:SELECT id, completed FROM tasks;
This query will return the following result:
id | completed ----+---------- 1 | false 2 | true
Conclusion
The boolean
data type is a basic data type in PostgreSQL used to store boolean values. It is commonly used to store data with two possible states and can be used in conjunction with other data types.