On this page
- Where does Boolean logic come from?
- What are truth values?
- What are the Boolean operators?
- What is a truth table?
- Which Boolean laws should you know?
- In what order are Boolean operators evaluated?
- What is short-circuit evaluation?
- How does Boolean logic work in SQL?
- What is the difference between bitwise and logical operators?
- Where do IT teams use Boolean logic every day?
- What are the most common Boolean logic mistakes?
- Sources
Boolean logic is a way of reasoning in which every value is either true or false, and every result is built from a few operators, mainly AND, OR and NOT. It is the rule set behind if statements, SQL WHERE clauses, search filters, firewall rules, alert conditions and the logic gates inside every processor.
This guide covers the theory (operators, truth tables, De Morgan's laws) and the places where it causes real bugs: short-circuiting, truthy values, NULL in SQL, bitmasks and the query languages of common IT tools.
Where does Boolean logic come from?
George Boole, an English mathematician, published The Mathematical Analysis of Logic in 1847 and An Investigation of the Laws of Thought in 1854. He treated logic as algebra: letters stand for classes or propositions, 1 for the universe and 0 for the empty class, and for a proposition x = 1 means true and x = 0 false. His central rule, x² = x, says that selecting the same thing twice changes nothing; today we write A AND A = A. Boole's algebra had restrictions that modern Boolean algebra dropped, but the name stuck (Stanford Encyclopedia of Philosophy).
The jump to computing came in 1937, when Claude Shannon, then a master's student at MIT, wrote A Symbolic Analysis of Relay and Switching Circuits. He showed that relay and switch networks can be described and simplified with Boolean algebra: two switches in series pass current only if both are closed (AND), two in parallel if either is (OR). A paper based on the thesis appeared in 1938, and MIT's library record lists the degree in 1940 (DSpace@MIT). Digital circuit design has rested on that idea ever since.
What are truth values?
There are exactly two: true and false, written 1 and 0 by logicians, true and false by most languages (True and False in Python) and high or low voltage by hardware. A Boolean expression is anything that evaluates to one of them, such as port == 22. Two complications come later: many languages let any value act as a truth value, and SQL adds a third value, UNKNOWN.
What are the Boolean operators?
Three operators can express any Boolean function:
- AND (A ∧ B) is true only when both inputs are true:
&&in C, Java and JavaScript,andin Python,ANDin SQL. - OR (A ∨ B) is true when at least one input is true, including when both are:
||,or,OR. - NOT (¬A) flips a single value:
!,not,NOT.
Four derived operators have their own names:
- XOR (A ⊕ B) is true when exactly one input is true. Few languages have a logical XOR keyword (MySQL is an exception); for two Booleans,
a != bdoes the job. - NAND Is NOT (A AND B), and NOR is NOT (A OR B).
- XNOR Is true when both inputs are equal, the same as
a == bfor Booleans.
NAND and NOR are each functionally complete: any Boolean function can be built from NAND alone, or from NOR alone, which matters in hardware.
What is a truth table?
A truth table lists every combination of inputs with the output. With n inputs there are 2ⁿ rows. Using 1 for true and 0 for false:
| A | NOT A |
|---|---|
| 0 | 1 |
| 1 | 0 |
| A | B | A AND B | A OR B | A XOR B |
|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 |
| 0 | 1 | 0 | 1 | 1 |
| 1 | 0 | 0 | 1 | 1 |
| 1 | 1 | 1 | 1 | 0 |
| A | B | A NAND B | A NOR B | A XNOR B |
|---|---|---|---|---|
| 0 | 0 | 1 | 1 | 1 |
| 0 | 1 | 1 | 0 | 0 |
| 1 | 0 | 1 | 0 | 0 |
| 1 | 1 | 0 | 0 | 1 |
Truth tables are also a debugging tool. When a condition with three or four inputs misbehaves, printing all 8 or 16 rows usually finds the problem faster than rereading it:
from itertools import product
for is_admin, is_owner, locked in product([False, True], repeat=3):
can_edit = (is_admin or is_owner) and not locked
print(is_admin, is_owner, locked, can_edit)
Which Boolean laws should you know?
These identities let you simplify or rewrite a condition without changing its meaning:
| Law | AND form | OR form |
|---|---|---|
| Identity | A AND 1 = A | A OR 0 = A |
| Annulment | A AND 0 = 0 | A OR 1 = 1 |
| Idempotence | A AND A = A | A OR A = A |
| Complement | A AND NOT A = 0 | A OR NOT A = 1 |
| Commutative | A AND B = B AND A | A OR B = B OR A |
| Distributive | A AND (B OR C) = (A AND B) OR (A AND C) | A OR (B AND C) = (A OR B) AND (A OR C) |
| Absorption | A AND (A OR B) = A | A OR (A AND B) = A |
| De Morgan | NOT (A AND B) = NOT A OR NOT B | NOT (A OR B) = NOT A AND NOT B |
In code:
- Annulment.
debug or Trueis always true, which is how leftover test code disables a check for good. - Complement.
x > 5 or x <= 5is always true in Python, but not in SQL, because of NULL. - Distributive.
(is_admin and region == "eu") or (is_admin and region == "us")factors tois_admin and region in ("eu", "us"). - Absorption.
user.active or (user.active and user.verified)reduces touser.active. A clause that can never change the result usually means the author intended something else.
De Morgan's laws in code
De Morgan's laws, named after Boole's contemporary Augustus De Morgan, say that to negate a compound condition you negate each part and swap AND with OR. You need them whenever you invert a condition for an early return or a filter:
# keep rows that are neither archived nor deleted
if not (row.archived or row.deleted):
keep(row)
# the same test after applying De Morgan's law
if not row.archived and not row.deleted:
keep(row)
The usual slip is to negate the parts but keep the operator: not row.archived or not row.deleted keeps every row except those that are both archived and deleted.
In what order are Boolean operators evaluated?
The standard convention is NOT first, then AND, then OR, just as multiplication binds tighter than addition: a OR b AND c means a OR (b AND c). Python, JavaScript, C, Java and SQL follow it, but the details around it differ:
- Python Ranks comparisons above
not,andandor, and bitwise&,^and|above comparisons. Sox > 1 & y < 2becomes the chained comparisonx > (1 & y) < 2. With pandas or NumPy masks, write(x > 1) & (y < 2). - C, Java and JavaScript Rank
==above&, soflags & MASK == 0meansflags & (MASK == 0). Write(flags & MASK) == 0. - JavaScript Refuses to mix
??with&&or||without parentheses;a || b ?? cis a SyntaxError. - Bash Gives
&&and||equal precedence and evaluates them left to right, soa || b && cruns as(a || b) && c. - Elasticsearch query strings Do not apply the usual precedence to
AND,ORandNOTat all (Elastic documentation).
The practical rule: when a condition mixes AND and OR, add parentheses even where precedence makes them redundant.
What is short-circuit evaluation?
Most languages stop evaluating a Boolean expression once the result is certain. In A && B, a false A makes the result false, so B never runs; in A || B, a true A skips B. That makes AND a guard:
if (user && user.roles.includes("admin")) {
showAdminMenu();
}
if items and items[0].startswith("#"):
handle_comment(items)
Two details catch people out. First, in Python and JavaScript these operators return one of their operands, not necessarily a Boolean: Python defines x or y as x if x is true, otherwise y (Python documentation), and JavaScript's || behaves the same way (MDN). That is why name or "anonymous" works as a default. Second, in Java and C#, & and | applied to Booleans always evaluate both sides.
SQL makes no such promise. PostgreSQL's documentation states that the evaluation order of subexpressions is not defined and that the planner may reorganize AND and OR conditions in any way Boolean algebra permits. WHERE x > 0 AND y / x > 1.5 can still fail with a division by zero; the documented fix is a CASE expression, or avoiding the division with x > 0 AND y > 1.5 * x (PostgreSQL documentation).
Truthy and falsy values
Python and JavaScript let any value stand in for a Boolean, with different rules:
| Value | Python | JavaScript |
|---|---|---|
0 or an empty string |
false | false |
None, null, undefined |
false | false |
Empty list [] |
false | true |
Empty dict or object {} |
false | true |
NaN |
true | false |
The string "0" or "false" |
true | true |
Python treats False, None, numeric zero and empty strings and containers as false. JavaScript treats false, 0, -0, 0n, "", null, undefined and NaN as falsy, while every object, even an empty array, is truthy. The trap is using || or or for defaults when zero or an empty string is a legitimate value:
opts.timeout || 30 // 30 when timeout is 0, "" or null
opts.timeout ?? 30 // 30 only when timeout is null or undefined
retries = retries or 3 # a deliberate 0 becomes 3
if retries is None: # only a missing value gets the default
retries = 3
Environment variables are always strings, so if os.environ.get("DEBUG"): is true for DEBUG=false and DEBUG=0. Parse them explicitly.
How does Boolean logic work in SQL?
SQL uses three-valued logic. A comparison involving NULL, such as price > NULL, is neither true nor false but UNKNOWN, represented as a NULL Boolean. AND and OR then follow this table, as given in the PostgreSQL documentation:
| a | b | a AND b | a OR b |
|---|---|---|---|
| TRUE | TRUE | TRUE | TRUE |
| TRUE | FALSE | FALSE | TRUE |
| TRUE | NULL | NULL | TRUE |
| FALSE | FALSE | FALSE | FALSE |
| FALSE | NULL | FALSE | NULL |
| NULL | NULL | NULL | NULL |
NOT NULL is also NULL. Read NULL as "unknown" and the table makes sense: FALSE AND unknown is FALSE whatever the unknown is, TRUE OR unknown is TRUE, and the rest stays unknown.
A WHERE clause keeps a row only when its condition is TRUE, so FALSE and NULL rows are both dropped. As a result, the complement law fails: WHERE status = 'open' OR status <> 'open' skips every row whose status is NULL. Use IS NULL, IS NOT NULL or IS DISTINCT FROM wherever NULLs can appear.
Why does NOT IN return no rows?
CREATE TABLE customers (id int);
INSERT INTO customers VALUES (1), (2), (3);
CREATE TABLE blocked (customer_id int);
INSERT INTO blocked VALUES (2), (NULL);
SELECT id FROM customers
WHERE id NOT IN (SELECT customer_id FROM blocked);
-- no rows
For id = 1, the test expands to 1 <> 2 AND 1 <> NULL, which is TRUE AND NULL, which is NULL. Every row ends up NULL or FALSE, so nothing comes back. PostgreSQL's documentation states that when no right-hand value is equal and at least one is NULL, NOT IN yields null, not true (PostgreSQL documentation). NOT EXISTS avoids the problem:
SELECT id FROM customers c
WHERE NOT EXISTS (
SELECT 1 FROM blocked b WHERE b.customer_id = c.id
);
-- 1 and 3
This is standard SQL behavior, so it applies to PostgreSQL, MySQL, DuckDB and the other engines in the databases category.
What is the difference between bitwise and logical operators?
Logical operators work on whole truth values. Bitwise operators apply the same logic to every bit of an integer at once: & is AND, | is OR, ^ is XOR and ~ is NOT.
6 & 3 # 2 0b110 AND 0b011 = 0b010
6 | 3 # 7 0b110 OR 0b011 = 0b111
6 ^ 3 # 5 0b110 XOR 0b011 = 0b101
~6 # -7 every bit flipped (two's complement)
6 and 3 # 3 logical: 6 is truthy, so the second operand is returned
In JavaScript 6 && 3 is also 3, and true ^ false returns the number 1, not true. Bitwise operators never short-circuit. Four mask operations cover most uses:
- Test A bit:
value & MASKis non-zero when the bit is set. - Set It:
value | MASK. - Clear It:
value & ~MASK. - Toggle It:
value ^ MASK.
Where do IT teams use Boolean logic every day?
Search queries and log tools
In Elasticsearch and OpenSearch, a query_string query accepts AND, OR and NOT, plus + for terms that must match and - for terms that must not:
service:checkout AND (status:500 OR status:503) AND NOT env:staging
The JSON query DSL expresses the same filter as a bool query, where filter and must act as AND, must_not as NOT and should as OR:
{
"query": {
"bool": {
"filter": [
{ "term": { "service": "checkout" } },
{ "terms": { "status": [500, 503] } }
],
"must_not": [
{ "term": { "env": "staging" } }
]
}
}
}
Watch should: once a bool query has a must or filter clause, minimum_should_match defaults to 0 and should clauses only affect scoring. Set "minimum_should_match": 1 when you mean OR (Elastic documentation).
Command-line tools use the same logic. grep -e timeout -e refused app.log matches either word (OR), piping into a second grep narrows results (AND), and grep -v excludes lines (NOT). In Grafana Loki, chained line filters combine with AND, and a regex alternation gives OR:
{app="checkout"} |= "error" != "healthcheck"
{app="checkout"} |~ "timeout|refused"
Firewall rules and ACLs
A firewall rule is an AND of its match conditions, and a rule set is checked from the top, where the first matching rule decides. In iptables:
# protocol is TCP AND destination port is 22 AND source is in 10.0.0.0/8
iptables -A INPUT -p tcp --dport 22 -s 10.0.0.0/8 -j ACCEPT
# OR inside one rule: port 80 or port 443
iptables -A INPUT -p tcp -m multiport --dports 80,443 -j ACCEPT
# NOT: port 22 from anywhere outside 10.0.0.0/8
iptables -A INPUT -p tcp --dport 22 ! -s 10.0.0.0/8 -j DROP
nftables writes the in-rule OR as a set, such as tcp dport { 80, 443 } accept. Router ACLs follow the same first-match pattern and usually end with an implicit deny.
Subnet masks
A host finds its network address by ANDing its IP address with the subnet mask, bit by bit. For 192.168.10.77/26 the mask is 255.255.255.192, and only the last octet changes:
77 = 01001101
192 = 11000000
AND = 01000000 = 64
The network address is 192.168.10.64. OR-ing it with the inverted mask (0.0.0.63) gives the broadcast address, 192.168.10.127. Two hosts share a subnet when (ip1 & mask) == (ip2 & mask). Python's standard library does the arithmetic:
import ipaddress
ipaddress.ip_interface("192.168.10.77/26").network # IPv4Network('192.168.10.64/26')
Permission bitmasks
Unix file permissions are nine bits (read, write and execute for owner, group and others) plus the setuid, setgid and sticky bits. Mode 640 in octal is 110 100 000 in binary, which ls -l shows as rw-r-----. Checking and changing permissions is mask work:
import os, stat
mode = stat.S_IMODE(os.stat("deploy.sh").st_mode)
if mode & stat.S_IWOTH: # test: world-writable?
os.chmod("deploy.sh", mode & ~stat.S_IWOTH) # clear only that bit
The umask works the same way: a new file gets the requested mode AND NOT the umask, so 0o666 & ~0o022 gives 0o644.
Feature-flag conditions
Feature-flag targeting is Boolean logic with a UI on top. In GrowthBook, targeting conditions use a MongoDB-style JSON syntax: conditions in the same object are joined with AND, and $or, $nor and $not cover the rest (GrowthBook documentation).
{
"$or": [
{ "plan": "enterprise", "country": "DE" },
{ "employee": true }
]
}
That rule reads "(enterprise AND Germany) OR employee". PostHog uses the same shape: every filter in a condition set must pass, and passing any one set is enough. An OR of AND groups, called disjunctive normal form, is easy to read and test, so it is a good target when you untangle a long flag condition.
Alert rules
PromQL has three set operators: and (intersection), or (union) and unless (left side minus anything matched on the right). Its comparison operators filter series rather than return true or false, unless you add the bool modifier (Prometheus documentation). A common disk alert for Prometheus combines both:
node_filesystem_avail_bytes / node_filesystem_size_bytes < 0.10
and on (instance, device, mountpoint)
node_filesystem_readonly == 0
Read it as "less than 10% free AND not mounted read-only". Comparisons bind tighter than and, so no parentheses are needed, and on (...) lists the labels that must match on both sides. Grafana alert rules can run the same query; Grafana vs Datadog compares the wider stacks.
Logic gates in hardware
At the bottom of the stack, Boolean operators are transistor circuits. In CMOS, the technology behind nearly all modern processors, a two-input NAND or NOR gate takes four transistors, and AND and OR are usually a NAND or NOR followed by an inverter. Arithmetic is built from the same parts: a half adder produces the sum bit with XOR and the carry bit with AND. The classic 7400 chip contains nothing but four two-input NAND gates.
What are the most common Boolean logic mistakes?
- Mixing AND and OR without parentheses.
is_admin or is_owner and not lockedlets a locked admin through. - Negating only half a condition. Inverting each part without swapping AND and OR changes the test. Apply De Morgan's laws, then check the truth table.
- Using
||ororfor defaults when 0,falseor an empty string are valid values. - Comparing with NULL using
=or<>, and usingNOT INon a subquery that can return NULL. - Assuming SQL short-circuits. Use
CASEwhen one condition must protect another. - Swapping bitwise and logical operators.
&and|never short-circuit, and in C, Java and JavaScript&binds more loosely than==. - Trusting strings as Booleans.
"false"and"0"are truthy, which matters for environment variables and query parameters. - Using
a && b || cas if-then-else in a shell script. Ifbfails,cruns too. Write a realif.
Sources
- George Boole, Stanford Encyclopedia of Philosophyplato.stanford.edu
- A symbolic analysis of relay and switching circuits, Claude E. Shannon, MIT thesis record, DSpace@MITdspace.mit.edu
- Expressions: Boolean operations, The Python Language Referencedocs.python.org
- Logical OR, MDN Web Docsdeveloper.mozilla.org
- PostgreSQL documentation: Logical operators, Subquery expressions and Expression evaluation rulespostgresql.org
- Operators, Prometheus documentationprometheus.io
- Elasticsearch reference: Query string query and Boolean queryelastic.co
- Targeting, GrowthBook documentationdocs.growthbook.io
Frequently asked questions
What is Boolean logic in simple terms?
It is a set of rules for values that can only be true or false. You join conditions with AND (both must hold), OR (at least one must hold) and NOT (the opposite), and the result is again true or false. Every if statement, search filter and SQL WHERE clause depends on it.
Who invented Boolean logic?
The English mathematician George Boole, who set out an algebra of logic in The Mathematical Analysis of Logic (1847) and An Investigation of the Laws of Thought (1854). In 1937 Claude Shannon applied it to relay and switching circuits in his MIT master's thesis, which made it the basis of digital electronics.
What are the basic Boolean operators?
AND, OR and NOT. They are enough to express any logical condition. XOR, NAND, NOR and XNOR are combinations of them that get their own names because they appear so often in code and circuits.
How do AND, OR and NOT change a search query?
AND narrows the results because every term has to match. OR widens them because any term may match. NOT, often written as a minus sign, removes results that contain a term. When you combine them, group terms with parentheses, since not every search tool applies the usual precedence.
Is Boolean logic the same as binary?
No. Binary is a base-2 number system, while Boolean logic is a system of reasoning with two truth values. They meet in hardware and in bitwise operators, which treat each bit of a binary number as its own true or false value.
Why does SQL use three-valued logic?
NULL means a value is missing or unknown, so a comparison with NULL cannot honestly be called true or false. SQL returns UNKNOWN instead, and because a WHERE clause only keeps rows where the condition is TRUE, rows with NULL in a compared column quietly drop out of the results.
What is the difference between & and && in programming?
&& is logical AND: it works on truth values and skips the right-hand side when the left-hand side is false. & is bitwise AND on integers, applied to every bit, and it always evaluates both sides. Java and C# also accept & on booleans, without the short-circuit.
Tools in this article
PostgreSQLOpen source object-relational database with extensions
MySQLWidely used open-source relational database, now developed by Oracle
DuckDBIn-process analytical SQL database with no server to manage
ElasticsearchDistributed search and analytics engine for full-text, vector and hybrid search, logs and ES|QL queriesOpenSearchApache 2.0 search, analytics and observability suite.
Grafana LokiLog aggregation that indexes labels, not log contents.
GrowthBookFeature flags, experimentation and product analytics
PostHogOpen-source product platform: analytics, session replay, feature flags, experiments and error tracking
Facts link to their official sources. Product details can change after publication: report an error or read the editorial methodology.




