0
0
PostgresqlConceptBeginner · 3 min read

Boolean in PostgreSQL: Definition and Usage

In PostgreSQL, 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.

sql
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;
Output
id | description ----+------------- 2 | Do homework (1 row)
🎯

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, or null.
  • It is ideal for flags and binary choices.
  • Using boolean makes queries easier and more readable.
  • PostgreSQL treats true and false as keywords, not strings.

Key Takeaways

PostgreSQL boolean stores true, false, or null values.
Use boolean for simple yes/no or on/off data.
Boolean columns simplify queries and improve clarity.
Boolean values are keywords, not strings or numbers.