SQL: Structured Query LanguageSQL FundamentalsBoolean Data Types

When should you use a BOOLEAN column?

Question 15 of 30 · Updated

On this page

Use a BOOLEAN column when an attribute represents a true-or-false proposition: for example, whether notifications are enabled, whether a product is published, or whether an account is archived. In PostgreSQL, BOOLEAN (also called BOOL) supports TRUE and FALSE, and a nullable Boolean column can additionally contain NULL to represent an unknown or missing value.

Choose BOOLEAN when the meaning is genuinely binary. If the attribute instead represents several mutually exclusive states, a workflow stage, a quantity, a timestamp or a history of events, another data model may be more suitable.

1. Recognizing a Boolean attribute#

Business requirementSuitable designWhy
Email notifications enabled?BOOLEANTwo independent logical possibilities
Product published?BOOLEAN if publication is strictly binarySimple true-or-false flag
Order pending, shipped, delivered or cancelled?Status column with allowed valuesMore than two mutually exclusive states
When was a document approved?TimestampRecords the event time
How many attempts remain?INTEGERRepresents a count, not a proposition
Inspection passed, failed, or result not yet recorded?Nullable BOOLEAN, if NULL really means unknownDistinguishes missing results from negative results

Name Boolean columns so their meaning reads as a proposition: is_archived, email_enabled, has_completed_onboarding. Avoid ambiguous names such as flag, status or negative names that create confusing double negation. A clear name makes predicates easier to understand.

2. Defining a Boolean column with sensible defaults#

Consider a notification preferences table. Email and SMS preferences are independent: a user may enable both, either one, or neither.

SQL
CREATE TABLE notification_preferences ( user_id BIGINT PRIMARY KEY, email_enabled BOOLEAN NOT NULL DEFAULT FALSE, sms_enabled BOOLEAN NOT NULL DEFAULT FALSE );

This is illustrative PostgreSQL DDL for a disposable database. FALSE is an example opt-in default, not a universal rule for every product. NOT NULL prevents missing flag values, while DEFAULT FALSE supplies a value if the column is omitted or DEFAULT is explicitly requested. A default does not convert an explicitly inserted NULL to FALSE. With NOT NULL, that insertion is rejected.

Use TRUE and FALSE as Boolean literals, rather than storing the strings 'true' and 'false' or inventing numeric codes. PostgreSQL accepts some textual input forms as Boolean values, but explicit Boolean literals make the intent clear and avoid relying on conversion rules. If preferences represent legally significant consent, a current Boolean flag alone is not necessarily adequate evidence: record the required consent events, timestamps, scope and policy versions separately as appropriate.

3. TRUE, FALSE and NULL are not interchangeable#

A nullable Boolean can model a question whose answer is not yet known. For example, inspection_passed = FALSE may mean a recorded failure, while NULL means there is no recorded result. Treating the latter as a failure or success without an explicit business rule can misrepresent the data.

The following read-only PostgreSQL query uses inline rows to demonstrate the three cases without creating a table.

SQL
WITH flags(id, enabled) AS ( VALUES (1, TRUE), (2, FALSE), (3, NULL::boolean) ) SELECT id, enabled, enabled IS TRUE AS is_true, enabled IS FALSE AS is_false, enabled IS NOT TRUE AS is_not_true, enabled IS UNKNOWN AS is_unknown, NOT enabled AS negated FROM flags ORDER BY id;

Observed result:

idenabledis_trueis_falseis_not_trueis_unknownnegated
1TRUETRUEFALSEFALSEFALSEFALSE
2FALSEFALSETRUETRUEFALSETRUE
3NULLFALSEFALSETRUETRUENULL

SQL predicates can evaluate to TRUE, FALSE or UNKNOWN. WHERE retains only rows for which the condition is TRUE. In PostgreSQL, WHERE enabled, WHERE enabled = TRUE and WHERE enabled IS TRUE select the same rows in this simple case. However, the expressions enabled = TRUE and enabled IS TRUE are not identical as general expressions: the former returns UNKNOWN for NULL, while the latter returns FALSE.

WHERE NOT enabled selects explicitly false values, excluding NULL. WHERE enabled IS NOT TRUE selects both false and unknown values. For an explicitly unknown result, use WHERE enabled IS NULL or PostgreSQL's Boolean predicate enabled IS UNKNOWN. Never use enabled = NULL to find missing values.

4. Counting true values correctly#

Do not use COUNT(enabled) to count enabled records. COUNT(expression) counts non-NULL results, so it includes both TRUE and FALSE.

SQL
WITH flags(id, enabled) AS ( VALUES (1, TRUE), (2, FALSE), (3, NULL::boolean) ) SELECT COUNT(*) AS total, COUNT(enabled) AS known, COUNT(*) FILTER (WHERE enabled) AS true_count, COUNT(*) FILTER (WHERE NOT enabled) AS false_count, COUNT(*) FILTER (WHERE enabled IS NULL) AS unknown_count FROM flags;
totalknowntrue_countfalse_countunknown_count
32111

COUNT(*) counts all matching rows, whereas COUNT(enabled) counts the two rows with known Boolean values. The FILTER clauses implement conditional aggregation. FILTER is supported in PostgreSQL; for engines without it, conditional CASE expressions inside aggregates provide a common alternative. Pay attention to how an aggregate behaves on an empty input set.

5. Combining Boolean conditions#

Boolean attributes can be combined using AND, OR and NOT. Unknown inputs require three-valued logic. For example, FALSE AND UNKNOWN is FALSE because one false operand is sufficient to determine the conjunction, while TRUE AND UNKNOWN remains UNKNOWN.

SQL
SELECT FALSE AND NULL::boolean AS false_and_unknown, TRUE AND NULL::boolean AS true_and_unknown, TRUE OR NULL::boolean AS true_or_unknown, FALSE OR NULL::boolean AS false_or_unknown, COALESCE(NULL::boolean,FALSE) AS fallback;
false_and_unknowntrue_and_unknowntrue_or_unknownfalse_or_unknownfallback
FALSENULLTRUENULLFALSE

COALESCE(enabled, FALSE) is appropriate only when the application intentionally treats an unknown or missing flag as false in that calculation. It does not change the stored value. In access or opt-in checks, an explicitly true condition is often a clearer fail-closed rule. A general Boolean flag is not a substitute for server-side authorization or a complete consent policy.

6. Practical example: independent notification preferences#

The following inline dataset illustrates four users with different combinations of preferences. Query for users who have at least one notification channel enabled.

SQL
WITH preferences(id, email_enabled, sms_enabled) AS ( VALUES (1, TRUE, FALSE), (2, FALSE, TRUE), (3, FALSE, FALSE), (4, TRUE, TRUE) ) SELECT id FROM preferences WHERE email_enabled OR sms_enabled ORDER BY id;

| id | |---:| | 1 | | 2 | | 4 |

Two Boolean columns are useful here because the flags are independent. Neither flag determines the other. An AND condition would instead require both channels to be enabled. If channels become extensible, such as adding push, in-app and webhook preferences for each user, a related preferences table with a channel identifier and enabled flag may be more maintainable than continually adding columns.

7. When a status column is better than Boolean flags#

Do not model every possible state of a single workflow as an independent Boolean. An order represented by is_pending, is_shipped, is_delivered and is_cancelled could contain contradictory combinations unless additional rules are carefully enforced. If these are mutually exclusive current states, a single status column is clearer.

SQL
CREATE TABLE fulfillment_orders ( order_id BIGINT PRIMARY KEY, status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending','shipped','delivered','cancelled')) );

This illustrative definition restricts the permitted current state, but it does not enforce legal transitions between states. A workflow may require additional transition validation, transaction control and a separate event history. PostgreSQL also supports enumerated types and foreign keys to lookup tables; the choice depends on how frequently allowed states change and how much metadata each state needs.

A Boolean may still be appropriate for an independent property of the order, such as gift_wrap_requested. The key question is whether the attribute has two meaningful alternatives independent of other attributes, rather than whether the system has multiple properties.

8. Storage, input validation and indexing#

PostgreSQL's Boolean type has a one-byte value representation. That does not mean a whole database row or index entry costs only one additional byte: alignment, tuple headers, null metadata and other storage details matter.

SQL
SELECT pg_typeof(TRUE)::text AS type_name, pg_column_size(TRUE) AS value_bytes, pg_input_is_valid('yes','boolean') AS yes_valid, pg_input_is_valid('maybe','boolean') AS maybe_valid;
type_namevalue_bytesyes_validmaybe_valid
boolean1TRUEFALSE

The tested PostgreSQL input parser accepts 'yes' but rejects 'maybe'. The pg_input_is_valid function is available in supported PostgreSQL versions and checks input validity without intentionally throwing a conversion error here. This is not a rule that every database or application should accept 'yes' as a Boolean: validate the actual API contract.

A Boolean column usually has low cardinality. A standalone B-tree index on a flag is not automatically useful because a common flag value may match a large fraction of the table. A rare value can still be selective. In PostgreSQL, a partial index that covers a small subset of active or pending rows, often on another useful lookup or ordering column, may be more effective. Choose indexes from observed query patterns and inspect execution plans rather than indexing every Boolean flag.

9. Portability and application design#

PostgreSQL has a native BOOLEAN type. MySQL commonly treats BOOLEAN and BOOL as synonyms for TINYINT(1); the declaration alone does not restrict all stored values to zero or one. SQL Server uses BIT for Boolean-like values. SQLite ordinarily has no separate Boolean storage class and commonly represents true and false with integers 1 and 0. Exact conversion, constraint and query syntax varies. These dialect notes are contextual, not cross-engine test results.

Bind actual Boolean values through the database driver instead of constructing SQL strings from application input. In JavaScript, the string 'false' is truthy, so blindly applying Boolean(value) to user-provided strings can invert intended behavior. Validate the input type and distinguish missing fields, explicit NULL and FALSE. For partial updates, an omitted field often means leave it unchanged, not disable the feature.

10. Interview-ready answer#

Use BOOLEAN for an attribute that represents a true-or-false proposition, such as whether a notification channel is enabled or a product is archived. In PostgreSQL, TRUE and FALSE are the Boolean values, and a nullable column can also contain NULL for an unknown result. Use NOT NULL when every row must have a known answer, with an appropriate default if omitted values have a defined meaning. Query true values with WHERE flag or flag IS TRUE, and remember that NOT flag excludes NULL. Avoid Boolean flags for mutually exclusive multi-state workflows; use a constrained status column instead. Boolean columns are compact, but indexing them depends on selectivity and query patterns.

Common interview follow-ups#

  • Is NULL the same as FALSE? No. NULL represents missing or unknown information, and negating a null Boolean with NOT yields UNKNOWN.
  • Does DEFAULT FALSE imply NOT NULL? No. Declare NOT NULL separately when required.
  • Does COUNT(flag) count only true flags? No. It counts all non-null flag values.
  • Should an order lifecycle use several Boolean columns? Generally not when the states are mutually exclusive; independent properties are a different matter.
  • Should all Boolean columns be indexed? No. Evaluate selectivity and workload requirements.

Validation and references#

All five read-only PostgreSQL queries were executed successfully using synthetic literals and inline rows. Results verified Boolean predicates, NULL behavior, conditional aggregation, logical operators, independent preferences, value size and input validity. The illustrative CREATE TABLE statements, other-engine behavior, and index recommendations were not executed or benchmarked. No educational DDL or application data changes were performed.

Truth tables and comparison tables were chosen instead of a Mermaid diagram because they directly expose the three possible predicate outcomes and are clearer for this lesson. No diagram is required.

Documentation consulted through the Supabase documentation connector:

Additional authoritative reading (not live-verified in this session):

Live web browsing was unavailable. The additional references are suggested reading rather than independently consulted sources.

Related questions

Explore other topics:Forward Deployed EngineeringPythonAI System DesignMachine Learning