SQL Tutorial

SQL Clauses / Operators

SQL-Injection

SQL Functions

SQL Queries

PL/SQL

MySQL

SQL Server

Misc

MySQL | BIN() Function

The BIN() function in MySQL is used to convert a decimal number to its binary representation. It returns a string representation of the binary value of a given number.

Syntax:

BIN(decimal_number)

Example:

Let's go over a simple example to understand how the BIN() function works.

SELECT BIN(5);   -- This will return '101'

Here, the decimal number 5 is converted to its binary representation, which is 101.

Usage with tables:

Imagine you have a table named numbers with a column decimal_value that stores decimal numbers, and you want to find out the binary representation of each number.

SELECT decimal_value, BIN(decimal_value) AS binary_representation 
FROM numbers;

This query will retrieve the original decimal values and their binary representations from the numbers table.

Points to Note:

  1. If you pass a negative number to the BIN() function, it will return a binary representation of the absolute value of the number.
  2. If you pass a non-integer decimal (like 5.7), the BIN() function will truncate the decimal portion and only convert the integer part.

Remember that the BIN() function provides a straightforward method to convert decimal numbers to binary in MySQL. However, it's always good to verify your results, especially if you're working with a broad range of values or using this function as part of a more complex query.

  1. How to Use BIN() Function in MySQL:

    • Convert a decimal number to its binary representation.
    SELECT BIN(25) AS binary_representation;
    
  2. Binary Representation of Numbers with BIN() in MySQL:

    SELECT id, BIN(id) AS binary_representation
    FROM your_table;
    
  3. Converting Decimal to Binary in MySQL using BIN():

    SELECT decimal_column, BIN(decimal_column) AS binary_representation
    FROM your_table;
    
  4. Using BIN() with Other Functions in MySQL:

    SELECT id, CONCAT('Binary: ', BIN(id)) AS binary_string
    FROM your_table;
    
  5. Handling NULL Values with BIN() in MySQL:

    SELECT id, IFNULL(BIN(id), 'N/A') AS binary_representation
    FROM your_table;
    
  6. MySQL BIN() Function in SELECT Statement:

    • Use it directly in the SELECT statement.
    SELECT BIN(42 + 15) AS result;
    
  7. Examples of Bitwise Operations with BIN() in MySQL:

    • Applying bitwise operations on binary representations.
    SELECT BIN(10 & 5) AS bitwise_and,
           BIN(10 | 5) AS bitwise_or,
           BIN(10 ^ 5) AS bitwise_xor;
    
  8. MySQL BIN() Function for Binary Literals:

    • Use BIN() to represent binary literals in queries.
    SELECT BIN(0b1101) AS binary_literal;
    
  9. BIN() Function and Indexing in MySQL:

    • Be cautious when using BIN() in indexed columns, as it may affect performance.
    CREATE INDEX idx_binary_column ON your_table(BIN(binary_column));