EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials MySQL Tutorial MySQL BIT
Secondary Sidebar
MySQL Tutorial
  • Functions
    • MySQL Function
    • MySQL Aggregate Function
    • MySQL String functions
    • MySQL Date Functions
    • MySQL Window Functions
    • MySQL Math Functions
    • MySQL Boolean
    • Cursor in MySQL
    • Condition in MySQL
    • MySQL BETWEEN
    • Insert in MySQL
    • MySQL IFNULL()
    • MySQL TIMESTAMPDIFF()
    • MySQL COALESCE()
    • MySQL count()
    • MIN() in MySQL
    • MySQL Numeric
    • MySQL field()
    • MySQL FIND_IN_SET()
    • MySQL avg()
    • MySQL MAX() Function
    • MySQL BIN()
    • MySQL Concat
    • MySQL DECODE()
    • MySQL REGEXP_REPLACE()
    • MySQL Asynchronous
    • MySQL innodb_buffer_pool_size
    • MySQL key_buffer_size
    • MySQL TRUNCATE()
    • MySQL ROW_NUMBER()
    • NOT in MySQL
    • MySQL IN Operator
    • LIKE in MySQL
    • ANY in MySQL
    • MySQL NOT IN
    • MySQL CHECK Constraint
    • MySQL DISTINCT
    • MySQL ALL
    • MySQL Union
    • MySQL UNION ALL
    • MySQL EXISTS
    • MySQL ON DELETE CASCADE
    • MySQL REGEXP
    • MySQL Index
    • MySQL Add Index
    • MySQL REINDEX
    • MySQL UNIQUE INDEX
    • MySQL Clustered Index
    • MySQL? InnoDB Cluster
    • Table in MySQL
    • ALTER TABLE MySQL
    • MySQL Temporary Table
    • MySQL Clone Table
    • MySQL Repair Table
    • MySQL Lock Table
    • MySQL Optimize Table
    • TRUNCATE TABLE MySQL
    • MySQL Table Dump
    • MySQL Update Set
    • MySQL ALTER TABLE Add Column
    • MySQL RANK()
    • MySQL CTE
    • MySQL LAG()
    • MySQL GROUP_CONCAT()
    • MySQL EXTRACT()
    • MySQL REPLACE
    • MySQL AUTO_INCREMENT
    • MySQL SYSDATE()
    • MySQL NULLIF()
    • MySQL Substring
    • MySQL SUBSTRING_INDEX()
    • MySQL LOWERCASE
    • MySQL Row
    • MySQL NOW
    • MySQL CEIL
    • MySQL Alias
    • MySQL Trigger
    • MySQL SHOW Triggers
    • MySQL UPDATE Trigger
    • MySQL DELETE Trigger
    • MySQL AFTER UPDATE Trigger
    • MySQL Stored Procedure
    • ROLLUP in MySQL
    • MySQL? INSTR()
    • MySQL Subquery
    • MySQL Timestamp
    • MySQL? Hour()
    • MySQL MOD()
    • MySQL DATE_FORMAT()
    • ALTER Column in MySQL
    • MySQL Rename Column
    • MySQL Interval
    • MySQL CURDATE
    • MySQL BIT
    • MySQL Binlog
    • MySQL Average
    • MySQL TEXT
    • MySQL SHOW
    • MySQL Offset
    • MySQL Timezone
    • mysql_real_escape_string
    • MySQL Datetime
    • MySQL DATE_SUB()
    • MySQL FULLTEXT
    • MySQL DATE_ADD()
    • MySQL sum()
    • MySQL Merge
    • MySQL BigInt
    • MySQL ROUND
    • MySQL VARCHAR
    • MySQL Decimal
    • MySQL Limit
    • MySQL today()
    • MySQL WEEKDAY
    • MySQL Split
    • MySQL Create Function
    • MySQL BLOB
    • MySQL encode()
    • MySQL Primary Key
    • MySQL Foreign Key
    • Unique Key in MySQL
    • MySQL Drop Foreign Key
    • MySQL DROP TRIGGER
    • MYSQL Database
    • Delete Database MySQL
    • MySQL Root
    • MySQL Root Password
    • MySQL Client
    • MySQL Users
    • MySQL?User Permissions
    • MySQL add user
    • MySQL List User
    • MySQL Show Users
    • MySQL User Password
    • MySQL?Cardinality
    • MySQL Workbench
    • MySQL Backup
    • MySQL REVOKE
    • MySQL Dump
    • MySQL Cluster
    • MySQL Partitioning
    • MySQL Full Text Search
    • MySQL Admin Tool
    • MySQL Export Database
    • MySQL Export to CSV
  • Basic
    • MySQL floor
    • MySQL DESCRIBE table
    • MySQL encryption
    • Introduction to MySQL
    • Is SQL Server a Database?
    • What is MySQL
    • Is MySQL Programming Language
    • MySQL Server
    • MySQL AB
    • MySQL Community Server
    • How To Install MySQL
    • MySQL Versions
    • MySQL OpenSource
    • MySQL GUI Tools
    • MySQL Grant
    • MySQL Error 1064
    • MySQL Drop Database
    • MySQL not equal
    • MySQL SELECT INTO Variable
    • MySQL Commands
    • MySQL Operators
    • What is MySQL Schema
    • Wildcards in MySQL
    • MySQL Constraints
    • MySQL Administration
    • MySQL Data Type
    • MYSQL COMMIT
    • MySQL FORMAT
    • Timestamp to Date in MySQL
    • MySQL DATEDIFF
    • MySQL?Incremental Backup
    • MySQL JSON Data Type
    • MySQL ENUM
    • MySQL Default Port
    • Cheat Sheet MySQL
  • Queries
    • MySQL Queries
    • MySQL Query Commands
    • SELECT in MySQL
    • MySQL INSERT IGNORE
    • MySQL having
    • ORDER BY in MySQL
    • MySQL Cheat Sheet
    • MySQL ORDER BY Random
    • MySQL ORDER BY DESC
    • MySQL GROUP BY
    • MySQL GROUP BY Count
    • MySQL GROUP BY month
    • MySQL WHERE Clause
    • MySQL WITH
    • MySQL FETCH
    • MySQL DDL
    • MySQL DML
    • MySQL WHERE IN Array
    • MySQL Fetch Array
    • MySQL ISNULL
    • MySQL Index Types
    • Mysql? Export Schema
    • Amazon RDS for MySQL
    • MySQL greatest
  • Database
    • What is Data Modeling
    • What is Data Processing
    • DBMS Architecture
    • DBMS Keys
    • Careers in Database Administration
    • What is MySQL Database
    • MySQL Relational Database
    • How to Connect Database to MySQL
    • MySQL Database Repair
    • RDBMS Interview Questions
    • DBMS Interview Questions
  • Joins
    • Joins in MySQL
    • MySQL Outer Join
    • Left Outer Join in MySQL
    • MySQL Self Join
    • Natural Join in MySQL
    • MySQL DELETE JOIN
    • MySQL Update Join
    • MySQL Cross Join
  • Advanced
    • MySQL Formatter
    • MySQL TINYINT
    • MySQL Grant All Privileges
    • MySQL DROP TABLE
    • MySQL rename database
    • MySQL Flush Privileges
    • MySQL super Privilege
    • MySQL Character Set
    • MySQL Log File
    • MySQL Flush Log
    • Grant Privileges MySQL
    • MySQL WHILE LOOP
    • IF Statement in MySQL
    • MySQL CASE Statement
    • MySQL IF Function
    • MySQL IF EXISTS
    • MySQL UUID
    • Views in MySQL
    • MySQL Replication
    • MySQL Partition
    • Toad for MySQL
    • Navicat for MySQL
    • MySQL AES_Encrypt
    • MySQL Performance Tuning
    • MySQL Transaction
    • MySQL? sort_buffer_size
    • MySQL? Sync
    • MySQL? Query Cache
    • MySQL Collation
    • MySQL ODBC Driver
    • MySQL Partitioning
    • MySQL InnoDB
    • MySQL Float vs Decimal
    • MySQL Union vs Union All
  • Interview Questions
    • MySQL Interview Questions

Related Courses

MS SQL Certification Courses

Oracle Certification Courses

PL/SQL Certification Courses

MySQL BIT

By Priya PedamkarPriya Pedamkar

MySQL BIT

Introduction to MySQL BIT

BIT is a data type used in MySQL. This type stores bit values within range of 1-64. It is generally defined in the create table or defining statements and denoted as ‘BIT(n)’, where ‘n’ is the number of bit values that can be stored. This ‘n’ value keeps the range from 1-64 and if not defined in the statement, it is defaulted to 1 bit value. This bit value will be storing binary values. We know in MySQL, we need to call a binary value as ‘BIN()’ to be displayed as a binary value. We will discuss further on this data type below.

Syntax:

The BIT data type is defined as below:

BIT (n);

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Here, the keyword BIT defines it to store binary values as bits and the bit value is mentioned in variable ‘n’. When called upon, to be displayed as a binary value, the BIT data type will have syntax as below. And if otherwise, the corresponding decimal value will be returned.

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (86,650 ratings)

BIN ( BIT (n))

Let’s have look at the usage and examples of BIT data type.

How Does BIT Data Type work in MySQL?

BIT (n) is defined with a defining statement like ‘create table’ etc. Please note that, if the value ‘n’ is not specified, the BIT value is defaulted to ‘1’ bit. We can create a table to understand the BIT data type. Our table is to store the attendance of students in a class for 5 working days. The table holds data for student name, attendance as BIT value in binary with ‘1’ denoting presence & ‘0’ denoting absence and the class to which student belongs. The create table statement is as below:

Query:

CREATE TABLE attendance (
STUDENT_NAME CHAR(50),
ATTENDANCE BIT(5),
CLASS INT
);

So the table name is attendance with three columns. Name of the student is stored as char data type, class in the INT data type and the attendance is stored as a BIT data type. The attendance filed will have 5 values representing the 5 working days.

Let’s insert values into these fields.

Query:

INSERT INTO attendance (STUDENT_NAME, ATTENDANCE, CLASS)
VALUES ('ALAN',b'11111',5),
('EMIL',b'11000',5),
('ANNA',b'00111',5),
('JOHN',b'11101',5);

A BIT value is inserted as a bit literal. Bit value literals are defined using b’val’ or ‘0bval’  notations.

The table has now four rows with data for 4 different student attendance.

We will retrieve the data with the SELECT query.

Query:

select * from attendance;

The simple SELECT query to retrieve complete data from table attendance.

Output:

MySQL BIT Example 1

The output retrieved is not showing correct data or data in our desired manner. We had input the attendance for 5 days from Monday to Friday for each student. But while retrieving, in the SELECT query, we have not specified how the bit value is to be displayed. Thus the value is displayed as a decimal value corresponding to the binary input shared.

Now, let’s try retrieving the data as binary values itself. For that, we need to specifically call the column attendance as BIN().

Query:

SELECT STUDENT_NAME, BIN(ATTENDANCE), CLASS FROM attendance;

The BIN() function will display the binary values input as bit value literals in the binary format itself.

Output:

MySQL BIT Example 2

We now get the attendance of each student as ‘1’ and ‘0 ‘, thus making it easier to identify the days when each of them were present or absent. But Anna’s attendance is having a slight issue here. She was absent on Monday and Tuesday. So that was marked as ‘0’ for both days. Since the bit value literal started with zeros, it omitted the preceding zeros while displaying the output. This can cause confusion as the data is available only for 3 days out of a total 5 days.

To avoid this situation, we can use the LPAD function along with the BIN function.

Query:

SELECT STUDENT_NAME, LPAD(BIN(ATTENDANCE),5,'0') as ATTENDANCE, CLASS FROM attendance;

Output:

MySQL BIT Example 3

Now all attendance look similar as the count of days is constantly 5 days.

These were several methods of retrieving a BIT data type in MySQL. In our variable definition statement, we had specified the number of bits in the variable attendance as 5, by the part of the query – attendance BIT(5). As discussed, this count can range from 1-64 and the default count is 1 when no digit is specified within ().

We can see some examples of different lengths in the BIT value.

Query:

CREATE TABLE sampleBITs (
sample1 BIT(10),
sample2 BIT,
sample3 BIT(50));

A table with 3 variables sample1, sample2 and sample3 are created. Sample2 has no length specified, which means the length is 1. We can insert the values into this table.

Query:

INSERT INTO sampleBITs (sample1, sample2, sample3)
VALUES (b'1010101010', 0b1, B'10001100011000110001111111000110001100011100110001');
select * from sampleBITs;

Output:

MySQL BIT Example 4

Note that, here we have inserted values using all 3 valid bit value laterals.

Now, the table can be retrieved as below.

Query:

SELECT
LPAD(BIN(sample1),10,'0') as sample1,
LPAD(BIN(sample2),1,'0') as sample2,
LPAD(BIN(sample3),50,'0') as sample3
FROM sampleBITs;

Output:

MySQL BIT Example 5

We have used LPAD and BIN functions to retrieve the data in a proper format.

NOTE: Bit literals can be specified as b’val’ or 0bval. The b’val’ can also be denoted as B’val’, as the literal is not case sensitive in this format. But the leading 0b is case sensitive and cannot be replaced with 0B. A bit-value literal is always binary value by default, in both notations.

Conclusion

So as we discussed, the BIT data type is used to store bit values and is defined as BIT(n) where ‘n’ specifies the count of bits within the variable. The value of ‘n’ can be within ‘1’ to ‘64’. To input data into the bit variable, we can use bit value literals and the same can be retrieved as decimal, binary or any other data conversion functions.

Recommended Articles

This is a guide to MySQL BIT. Here we discuss the Introduction to MySQL BIT and the practical examples and different subquery expressions. You can also go through our suggested articles to learn more –

  1. Introduction to MySQL Operators
  2. Top 23 MySQL String functions
  3. MySQL vs SQLite | Top 14 Comparisons
  4. Guide to MySQL Timestamp
Popular Course in this category
MySQL Training Program (12 Courses, 10 Projects)
  12 Online Courses |  10 Hands-on Projects |  92+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

MS SQL Training (16 Courses, 11+ Projects)4.9
Oracle Training (14 Courses, 8+ Projects)4.8
PL SQL Training (4 Courses, 2+ Projects)4.7
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more