Working with BOOLEAN Values in SQL, Explained

UPI Study › Courses › Database Programming › Free lessons › Lesson 4.3 Free with a free account

Working with BOOLEAN Values in SQL

Database Programming · Chapter 4: SQL Data Types in DepthSection 4.3 · lesson 22 of 768 min · free with a free account

← Floating-Point Data Types: REAL, FLOAT, and DOUBLENext lesson: Date and Time Data Types: DATE, TIME, and TIMESTAMP →

A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →

Earn 3 college credits for Database ProgrammingRecommended for credit by NCCRS · Computer Science 381 · self-paced · one payment, lifetime access

In this lesson

How MySQL, SQL Server, and SQLite store and enforce true-or-false flags.

  • Compare how MySQL, SQL Server, and SQLite represent boolean values
  • Define a two-state flag column with NOT NULL, a CHECK constraint, and a deliberate default
  • Write portable filters that compare flags explicitly with 1 and 0
  • Evaluate when Y and N letter flags suit reports better than numeric flags

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (1,012 words). Read along, or search it.

Opening Question

A Boolean Flag Holding the Number Two

Amina Diallo, the database administrator at Lantern Books, finds an active-account flag containing the number two. The column is named boolean. Surely that name guarantees a clean yes-or-no value? Run this disposable SQLite test. It inserts two, then uses the column itself as the filter condition. The row survives, yet equality with true produces zero. Nonzero truth and equality with one are different tests. A boolean fact has two possible values, true and false. A database column needs the right representation and constraints to preserve that meaning. For accounts, email consent, and shipping status, a flag should answer one clearly named question. Its type name alone may not enforce the intended answers.

Dialect Comparison

TINYINT, BIT, and SQLite Numeric Affinity

Different engines implement flags differently. MySQL's bool and boolean names are aliases for tinyint one, a one-byte integer type. That signed integer can hold negative one hundred twenty-eight through positive one hundred twenty-seven. The parenthesized one does not restrict values to zero and one. Use an enforced check constraint to restrict that domain. Modern MySQL enforces these checks, starting with version eight point zero sixteen. SQL Server uses bit, which stores zero, one, or null when allowed. Converting a nonzero number to bit produces one. Its storage is packed: up to eight bit columns share one byte. It is misleading to budget each flag as an independently stored bit. SQLite has no separate boolean storage class. Its boolean declaration gives numeric affinity; an explicit check and not-null rule provide our two-state domain.

Literals

Writing True, False, One, and Zero

A literal is a fixed value written directly into a statement. For flags, the portable numeric literals are one and zero. SQLite and MySQL also recognize the unquoted words true and false, as numeric aliases. Run the literal query here. Each expression is a value, rather than a column being looked up. It returns one, zero, and the integer type. The words make code readable, but they do not create a new storage class. SQL Server does not accept bare true and false as boolean literals. Write one and zero in its insert statements and predicates. SQL Server can convert the quoted strings true and false to bit. MySQL strict mode does not generally accept those strings as integer flags.

Schema Design

NOT NULL, CHECK, and Default Flag Values

Now give Amina a deliberate schema. This disposable extension records two independent facts for the course's customer identifiers. Not null disallows missing values; each check restricts the stored number to zero or one. These rules solve different problems. Run the insert that supplies only Asha's customer identifier. Neither flag is mentioned in the incoming row. The defaults supply active as one and email consent as zero. A default applies when a value is omitted, rather than validating whatever arrives. Choosing a default is a business decision. Silence about email consent should not accidentally be treated as a positive response. An optional flag could also contain null, meaning unknown or missing. Keep that third state only when it has an explicit meaning.

Filtering

Combining Flags With Explicit Comparisons

A filter should say which stored values qualify. Here Asha and Chen are active, but only Asha has also opted into email. And requires both comparisons to be true. An account being active does not automatically grant permission for every kind of communication. Run the combined condition, with the flag values shown in this temporary set of rows. Only Asha qualifies. Ben satisfies the email condition but fails the active condition; Chen does the reverse. For inactive accounts, compare with zero. Writing explicit comparisons is a useful portable habit across SQLite, MySQL, and SQL Server. A bare flag condition works in SQLite and MySQL, where nonzero values count as true. SQL Server requires a predicate such as active equals one.

Constraint Test

Rejecting Stray Numbers and Missing Values

Test the domain, rather than trusting its declaration. This example first stores the two allowed values. The second insert attempts a stray number and a missing value. SQLite's insert or ignore lets this demonstration continue after constraint rejection. Run the file, and inspect the values that remain. This ignore syntax is specific to SQLite and should not be copied as portable error handling. Only zero and one remain. The check excludes two; not null excludes the missing value. A check alone does not necessarily reject null, because an unknown check result can pass. Pair the check with not null for a mandatory flag. Also distinguish MySQL's bit type from its boolean alias. Bit represents raw bit values; boolean with an enforced domain is clearer for this yes-or-no design.

Alternative Design

Y and N Letter Flags

Sometimes the result goes directly into a human-readable export. A single letter, Y or N, can make that interface clearer. The character column still needs a check, plus not null if the answer is required. Readability does not replace validation. Run this version, which omits the flag during insertion and lets the default provide its value. The stored answer is uppercase Y. The same design idea works in MySQL and SQL Server, although some insert syntax differs. Case rules depend on collation. SQLite's default comparison distinguishes uppercase and lowercase here, while common server collations may treat them as equal. Choose one documented spelling and normalize input appropriately. Numeric flags remain compact and convenient; letters trade some compactness for readability in reports.

Quick Check

Counting Rows With an OR Condition

A cleanup report now needs accounts that are inactive, or have email consent turned off. For these four new flag pairs, how many rows satisfy the displayed condition? Pause and predict. Two rows qualify, which is the third choice. Either zero-valued flag is enough for this or condition. Run the count: two pairs have email turned off. One is also inactive, but a matching row is counted only once. One would fit a filter that selected only one of those groups. Zero would incorrectly require both groups to be absent.

Key Takeaways

One Clear Question per Flag

Define each flag as one clear yes-or-no question. Add an enforced domain, and decide separately whether unknown values are allowed. Use explicit comparisons with one and zero for portable numeric tests. Choose defaults deliberately, rather than letting omitted data acquire an accidental meaning. Amina can now trust the stored flag because the schema enforces the rule. For readable letter exports, keep the same discipline with Y and N.

About Database Programming at UPI Study

Database Programming (Computer Science 381) is a self-paced online course of 76 video lessons in 12 chapters, from database applications, SQL setup, schema planning and normalization to keys and constraints, data types, filtering and sorting, joins, subqueries, views, indexes, ROLLUP and PIVOT, regular expressions and database security. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: Database Fundamentals vs Database Programming

Why take it here

Why students take Database Programming with UPI Study

Write the SQL behind every appDatabase Programming teaches SQL in MySQL and SQL Server side by side: designing and normalizing tables, keys and constraints, data types, inserting, updating and deleting rows, filtering, grouping, joins, subqueries, views, indexes, transactions, and protecting data from SQL injection. It suits computer science and information technology degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Database Programming carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Working with BOOLEAN Values in SQL

Does MySQL have a real BOOLEAN data type?
No, in MySQL BOOL and BOOLEAN are aliases for TINYINT(1), a one-byte signed integer that holds -128 through 127. The (1) is a display width and does not limit values to 0 and 1, so a boolean column can store 2. To enforce a true-or-false domain, add NOT NULL and CHECK (active IN (0, 1)); MySQL enforces CHECK constraints starting with version 8.0.16. TRUE and FALSE are aliases for 1 and 0.
How do you store a boolean value in SQL Server?
SQL Server stores boolean-style values in the BIT type, which holds 1, 0, or NULL when the column allows it. Converting any nonzero number to BIT gives 1, and the strings 'TRUE' and 'FALSE' convert to 1 and 0. Bare TRUE and FALSE keywords are not accepted as literals, so filters need a predicate such as WHERE active = 1. Up to eight BIT columns in a table share one byte of storage.
Why should a boolean column have both NOT NULL and a CHECK constraint?
A mandatory flag needs both because each rule blocks a different bad value. CHECK (flag IN (0, 1)) rejects stray numbers like 2, but a CHECK whose result is unknown passes, so it does not reject NULL by itself. NOT NULL rejects the missing value. A DEFAULT is a separate decision: it fills in a value only when an insert omits the column, and choosing it, such as email consent 0, is a business rule.
What is a common mistake when filtering on boolean flags?
A common mistake is assuming a bare flag condition works everywhere and means the same as equality with 1. In SQLite and MySQL, WHERE active treats any nonzero value as true, so a stray 2 passes, while active = TRUE matches only 1. SQL Server rejects a bare flag and needs a predicate such as active = 1. Explicit comparisons like active = 1 AND email_opt_in = 1 behave the same in all three systems.

About the Database Programming course

How many college credits is Database Programming?
Database Programming (Computer Science 381) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Database Programming cost and what is included?
$250, paid once, with lifetime access: all 76 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Database Programming take?
It is self-paced with no deadlines. The 76 lessons total about 11 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Database Programming.

76 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Updated

Database Programming
3 credits · NCCRS
Enroll →