A2-04-01.MySQL DATA TYPES-Pramatic Uses of MySQL BIT Data Type

时间:2022-04-10 00:16:51

转载自:http://www.mysqltutorial.org/mysql-bit/

Pramatic Uses of MySQL BIT Data Type

 

Summary: this tutorial introduces you to MySQL BIT data type that allows you to store bit values.

Introduction to MySQL BIT data type

MySQL provides the BIT type that allows you to store bit values. The BIT(m) can store up to m-bit values, which m can range from 1 to 64.

The default value of m is 1 if you omit it. So the following statements are the same:

and

To specify a bit value literal, you use b'val' or 0bval notation, which val is a binary value that contains only 0 and 1.

The leading b can be written as B, for example:

are the valid bit literals.

However, the leading 0b is case-sensitive, therefore, you cannot use 0B. The following is an invalid bit literal value:

By default the character set of a bit-value literal is the binary string as follows:

 

MySQL BIT examples

The following statement creates a new table named working_calendar that has the days column is BIT(7):

The values in days column indicate the working day or day off i.e., 1: working day and 0: day off.

Suppose the Saturday and Friday of the first week of 2017 are not the working days, you can insert a rowinto the working_calendar table as follows:

The following query retrieves data from the working_calendar table:

A2-04-01.MySQL DATA TYPES-Pramatic Uses of MySQL BIT Data Type

As you see, the bit value in the  days column is converted into an integer. To represent it as bit values, you use the BIN function:

A2-04-01.MySQL DATA TYPES-Pramatic Uses of MySQL BIT Data Type

If you insert a value to a BIT(m) column that is less than m bits long, MySQL will pad zeros on the left of the bit value.

Suppose the first day of the second week is off, you can insert 01111100 into the  days column. However, the 111100 value will also work because MySQL will pad one zero on the left.

To view the data you use the same query as above:

A2-04-01.MySQL DATA TYPES-Pramatic Uses of MySQL BIT Data Type

As you can see, MySQL removed the leading zeros prior returning the result. To display it correctly, you can use the LPAD function:

A2-04-01.MySQL DATA TYPES-Pramatic Uses of MySQL BIT Data Type

It is working fine now.

In this tutorial, you have learned how to use the MySQL BIT type to store bit values.