Lesson

MySQL BIN() Function

10 min reading
Free Course

MySQL BIN() Function

The MySQL BIN() function converts a decimal integer into its base-2 binary string representation. Use it when debugging bitmasks, inspecting permission flags, or auditing integer status fields inside SELECT queries.

Syntax

BIN(N)
  • N: A BIGINT integer value (or numeric expression) that MySQL converts into a string of 0 and 1 characters.

BIN(N) is shorthand for CONV(N, 10, 2) and always returns a VARCHAR string rather than an integer. Because MySQL interprets N as an unsigned 64-bit BIGINT when formatting bits, negative integers produce 64-character two's-complement bit strings.

Practical Example

Suppose demo_employees stores feature permissions as a bitmask integer in access_flags. You can inspect each employee's active bit flags in binary format alongside their role.

SELECT
    employee_id,
    full_name,
    access_flags,
    BIN(access_flags) AS binary_flags
FROM demo_employees
ORDER BY employee_id;
employee_id full_name access_flags binary_flags
1 Maya Lin 5 101
2 Omar Haddad 13 1101
3 Priya Nair 0 0
4 Lucas Meyer NULL NULL

Common Mistakes & NULL Behavior

  • NULL handling: BIN(NULL) returns NULL. No error is raised, and you can pair it with COALESCE(BIN(access_flags), '0') when building reports.
  • No zero-padding: BIN(5) returns '101', not '00000101'. Wrap it with LPAD(BIN(access_flags), 8, '0') if you need fixed-width byte output.
  • String or decimal arguments: Passing '12abc' implicitly casts the leading digits (12) and returns '1100', while fractional numbers like 5.9 truncate toward zero to 5 before conversion. Passing non-numeric text like 'abc' evaluates to 0 and returns '0'.
  • Negative integers: BIN(-1) returns 64 ones (1111...1111) because MySQL converts negative BIGINT values to unsigned 64-bit representations.

Frequently Asked Questions

Does MySQL BIN() return an integer or a string?

BIN() always returns a string (VARCHAR). If you run math on the result, MySQL parses '101' as decimal one hundred one instead of binary five.

How is BIN() different from CONV()?

BIN(N) only converts base-10 integers to base-2 strings. CONV(N, from_base, to_base) supports any input and output base from 2 to 36, including hexadecimal and octal.

How do I pad BIN() output to 8 bits?

Combine LPAD() with BIN(), such as LPAD(BIN(5), 8, '0'), which produces '00000101'.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
MySQL Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum