Boolean in PostgreSQL: Definition and Usage
boolean is a data type that stores truth values: true, false, or null. It is used to represent simple yes/no or on/off conditions in database tables.How It Works
The boolean data type in PostgreSQL stores one of three possible values: true, false, or null (unknown). Think of it like a light switch that can be either on or off, but with an extra option for when you don't know the switch's state.
When you use a boolean column in a table, you can easily check conditions, filter data, or control logic based on whether something is true or false. This makes it very useful for flags, status indicators, or any binary choice.
Example
This example shows how to create a table with a boolean column and insert some values. Then it selects rows where the boolean is true.
CREATE TABLE tasks ( id SERIAL PRIMARY KEY, description TEXT NOT NULL, completed BOOLEAN NOT NULL ); INSERT INTO tasks (description, completed) VALUES ('Wash dishes', false), ('Do homework', true), ('Read book', false); SELECT id, description FROM tasks WHERE completed = true;
When to Use
Use the boolean type when you need to store simple yes/no, true/false, or on/off information. For example, you might track if a user is active, if a task is completed, or if a feature is enabled.
This type helps keep your data clear and your queries simple, avoiding the need to use strings or numbers to represent true or false values.
Key Points
- Boolean stores
true,false, ornull. - It is ideal for flags and binary choices.
- Using boolean makes queries easier and more readable.
- PostgreSQL treats
trueandfalseas keywords, not strings.