Skip to content

Commit 712c833

Browse files
committed
3-state boolean columns emphasis on NOT NULL constraint
1 parent b077bc2 commit 712c833

File tree

1 file changed

+15
-4
lines changed

1 file changed

+15
-4
lines changed

README.adoc

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1167,19 +1167,30 @@ And you'll have to consider the fact that most non-trivial apps share a database
11671167

11681168
=== 3-state Boolean [[three-state-boolean]]
11691169

1170-
With SQL databases, if a boolean column is not given a default value, it will have three possible values: `true`, `false` and `NULL`.
1170+
With SQL databases, if a boolean column is nullable, it will have three possible values: `true`, `false` and `NULL`.
11711171
Boolean operators https://en.wikipedia.org/wiki/Three-valued_logic[work in unexpected ways] with `NULL`.
11721172

11731173
For example in SQL queries, `true AND NULL` is `NULL` (not false), `true AND NULL OR false` is `NULL` (not false). This can make SQL queries return unexpected results.
11741174

1175-
To avoid such situations, boolean columns should always have a default value and a `NOT NULL` constraint.
1175+
To avoid such situations, boolean columns should always have a `NOT NULL` constraint.
1176+
1177+
Note that when adding a boolean column to an existing table, a default value should be put in place. Otherwise the `NOT NULL` constraint will break for existing rows.
11761178

11771179
[source,ruby]
11781180
----
1179-
# bad - boolean without a default value
1181+
# bad - boolean column on a new table without a `NOT NULL` constraint
1182+
create_table :users do |t|
1183+
t.boolean :active
1184+
end
1185+
1186+
# bad - adding a boolean without a `NOT NULL` constraint or without a default value
11801187
add_column :users, :active, :boolean
1188+
add_column :users, :active, :boolean, null: false
11811189
1182-
# good - boolean with a default value (`false` or `true`) and with restricted `NULL`
1190+
# good - boolean with a `NOT NULL` constraint, and a default value (`false` or `true`) for existing tables
1191+
create_table :users do |t|
1192+
t.boolean :active, null: false
1193+
end
11831194
add_column :users, :active, :boolean, default: true, null: false
11841195
add_column :users, :admin, :boolean, default: false, null: false
11851196
----

0 commit comments

Comments
 (0)