MySQL
SQL
Conditional Statement
Database
Null Handling

MySQL IF NOT NULL, then display 1, else display 0

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Introduction

In MySQL, returning 1 when a value is not null and 0 otherwise is a common pattern for reporting flags and conditional aggregations. The core requirement is simple, but query style affects readability and portability. MySQL provides multiple equivalent expressions, and each fits different use cases.

Core Sections

Use IF for Direct Conditional Output

The most explicit expression is IF(condition, true_value, false_value).

sql
1SELECT
2    id,
3    IF(last_login IS NOT NULL, 1, 0) AS has_logged_in
4FROM users;

This is clear for teams who read MySQL-specific syntax regularly.

Use CASE for SQL-standard Style

If you want portability across SQL dialects, CASE is often preferred.

sql
1SELECT
2    id,
3    CASE
4        WHEN last_login IS NOT NULL THEN 1
5        ELSE 0
6    END AS has_logged_in
7FROM users;

CASE is easier to extend when more states are introduced later.

Convert Boolean Expressions Numerically

In MySQL, boolean expressions evaluate to 1 or 0 in numeric context. You can leverage this directly.

sql
1SELECT
2    id,
3    (last_login IS NOT NULL) AS has_logged_in
4FROM users;

This style is concise, but some teams prefer explicit IF or CASE for readability.

Apply Pattern in Aggregations

Conditional flags are useful for grouped statistics.

sql
1SELECT
2    department_id,
3    SUM(last_login IS NOT NULL) AS users_with_login,
4    COUNT(*) AS total_users
5FROM users
6GROUP BY department_id;

This avoids nested subqueries and remains efficient for many reporting tasks.

Handle Empty Strings Separately from NULL

NULL and empty string are not the same. If business rules treat empty string as missing, include both checks.

sql
1SELECT
2    id,
3    CASE
4        WHEN email IS NOT NULL AND email <> '' THEN 1
5        ELSE 0
6    END AS has_email
7FROM users;

Clarifying this distinction prevents miscounted quality metrics.

Index and Performance Considerations

Condition expressions themselves are cheap, but large scans still depend on table size and filtering strategy. If you repeatedly compute flags on large tables, consider generated columns or precomputed reporting tables where appropriate.

sql
ALTER TABLE users
ADD COLUMN has_login TINYINT AS (last_login IS NOT NULL) STORED;

Generated columns can simplify downstream query logic.

Testing for Data Quality Pipelines

For analytics, test counts against known fixtures to catch schema drift. Changes from nullable to non-nullable fields can silently alter flag distributions.

Use Conditional Flags in Materialized Reporting

If your analytics layer repeatedly computes the same null-check flags, you can persist those values during ETL and keep downstream queries simpler. This is especially useful when dashboards refresh frequently and source tables are large.

sql
1CREATE TABLE user_flags AS
2SELECT
3    id,
4    CASE WHEN last_login IS NOT NULL THEN 1 ELSE 0 END AS has_logged_in,
5    CASE WHEN email IS NOT NULL AND email <> '' THEN 1 ELSE 0 END AS has_email
6FROM users;

Persisted flags can reduce repetitive conditional logic across many reports. They also make BI-tool usage easier because analysts can group by ready-made indicator columns.

Consistency Across Application and SQL Layers

If application code uses nullable booleans or tri-state logic, align SQL flag definitions with API semantics. Mismatched assumptions between backend code and SQL transforms are a common source of inconsistent counts. Maintain one documented rule set and include sample rows for expected outcomes.

A lightweight data contract table describing each derived flag and its null handling rules can prevent future regressions during schema migrations.

Common Pitfalls

  • Treating empty strings as equivalent to null without explicit checks.
  • Mixing SQL dialect-specific syntax in code meant to be portable.
  • Overusing nested conditionals when simple boolean casts are enough.
  • Assuming conditional flags alone solve performance issues on large scans.
  • Ignoring schema changes that alter nullability semantics.

Summary

  • Use IF or CASE to map null checks to 1 and 0.
  • Boolean expressions can be used directly for concise flags.
  • Distinguish null from empty string when business rules require it.
  • Reuse conditional flags in grouped aggregations and reports.
  • Validate flag logic with tests as schemas evolve.

Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.