MySQL BIN() Function
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: ABIGINTinteger value (or numeric expression) that MySQL converts into a string of0and1characters.
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)returnsNULL. No error is raised, and you can pair it withCOALESCE(BIN(access_flags), '0')when building reports. - No zero-padding:
BIN(5)returns'101', not'00000101'. Wrap it withLPAD(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 like5.9truncate toward zero to5before conversion. Passing non-numeric text like'abc'evaluates to0and returns'0'. - Negative integers:
BIN(-1)returns 64 ones (1111...1111) because MySQL converts negativeBIGINTvalues 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'.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.