Course
BIT
MySQL Tutorial
This SQL tutorial is structured for beginners to guide them from the foundational concepts to advanced data manipulation and querying techniques in SQL. By the end of this tutorial, you will have developed a robust understanding of SQL, equipping you with the knowledge to efficiently manage and analyze data across various database systems. This guide sets the stage for your growth into a skilled data professional, ready to tackle complex data challenges and contribute to the field of data analysis and database management.
BIT
A bit represents the basic unit of data in programming languages. It can store only two values, represented as 0 or 1.
The MySQL BIT Data Type
The MySQL BIT data type is used to store binary values within a specified range. The range is determined by the number of bits you allocate to the BIT column.
If we try to insert an integer value instead of BIT values, MySQL automatically converts them into BIT values. We have to ensure that the integer value we are adding must be within the range for conversion to BIT values.
For instance, if you have a BIT(3) column, it can store values from 000 to 111 in binary, which corresponds to 0 to 7 in integer format. If you try to insert the integer 8 into this BIT(3) column, you'll get an error because 8 in binary is 1000, which is outside the valid range of the column.
Syntax
Following is the syntax of the MySQL BIT datatype −
BIT(n)
Here, the range of n value is from 1 to 64. If you don't provide the "n" value, the default is 1, resulting in a single-bit BIT column. Hence, the following queries will give the same output −
Column_name BIT(1);andColumn_name BIT;
Bit Value Literal
- To specify bit value literals, you can use the b'val or 0bval notations, where val is a binary value containing only 0s and 1s. The leading 'b' is case-insensitive.
- b01B11
- Note that the 0b notation is case-sensitive, so 0B'1000' is an invalid bit literal value.
- 0B'1000'
Example
Let us create a table named STUDENTS and use the BIT data type for the AGE column as shown below −
CREATE TABLE STUDENTS( ID int auto_increment, NAME varchar(40), AGE BIT(3), primary key (ID));
Following is the output obtained −
Query OK, 0 rows affected (0.01 sec)
Now, we are inserting the values "5" and "3" into the AGE column of the STUDENTS table −
INSERT INTO STUDENTS (NAME, AGE) VALUES ('Varun', 5), ('Akash', 3);
Output of the above query is as shown below −
Query OK, 2 rows affected (0.01 sec)Records: 2 Duplicates: 0 Warnings: 0
We can use the following query to display the inserted values in the AGE column of the STUDENTS table −
SELECT * from STUDENTS;
We can see in the output below that the values "5" and "3" are stored in binary format −
Now, let us insert another value "10". In binary format, "10" is represented as "1010". However, we defined the AGE column to have a range of only three bits. Therefore, the following query will generate an error because the value 10 is greater than 7 −
INSERT INTO STUDENTS (NAME, AGE) VALUES ('Priya', 10);
The output indicates that the data is too long for the AGE column.
ERROR 1406 (22001): Data too long for column 'AGE' at row 1
To insert bit value literals into the "AGE" column, you can use the B'val notation. Here, we are inserting "110" which is equivalent to the integer value "6" as shown below −
INSERT INTO STUDENTS (NAME, AGE) VALUES('Priya', B'110');
The result obtained is as follows −
Query OK, 1 row affected (0.01 sec)
Let us display all the records in the "STUDENTS" table using the following query −
SELECT * from STUDENTS;
We can see in the output below that the value "6" has been inserted in binary format as "0x06" −
Verification
To verify and display the inserted values in the "AGE" column in binary/bit format, you can use the MySQL BIN() function −
SELECT ID, NAME, BIN(AGE) FROM STUDENTS;
The output shows the values in binary format −
In the above output, we can see that the leading zeros are removed. If we want to display them, we can use the LPAD function as shown below −
SELECT ID, NAME, LPAD(BIN(AGE), 5, "0") FROM STUDENTS;
Following is the output obtained −
BIT Datatype Using a Client Program
We can also create column of the BIT datatype using the client program.
Syntax
PHPNodeJSJavaPython
To create a column of BIT datatype through a PHP program, we need to execute the "CREATE TABLE" statement using the mysqli function query() as follows −
$sql = 'CREATE TABLE students(ID int auto_increment, NAME varchar(40), AGE BIT(3), primary key (ID) )';$mysqli->query($sql);
Example
Following are the programs −
PHPNodeJSJavaPython
$dbhost = 'localhost';$dbuser = 'root';$dbpass = 'password';$dbname = 'TUTORIALS';$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);if ($mysqli->connect_errno) { printf("Connect failed: %s", $mysqli->connect_error); exit();}//printf('Connected successfully.');
//creating a table student where age is bit data types$sql = 'CREATE TABLE students(ID int auto_increment, NAME varchar(40), AGE BIT(3), primary key (ID) )';$result = $mysqli->query($sql);if ($result) { printf("Table created successfully...!\n");}// insert data into created table $q = " INSERT INTO students (NAME, AGE) VALUES ('Varun', 5), ('Akash', 3)";if ($res = $mysqli->query($q)) { printf("Data inserted successfully...!\n");}//now display the table records $s = "SELECT * FROM students";if ($r = $mysqli->query($s)) { printf("Table Records: \n"); while ($row = $r->fetch_assoc()) { printf(" ID: %d, Age: %d", $row["ID"], $row["AGE"]); printf("\n"); }} else { printf('Failed');}$mysqli->close();
Output
The output obtained is as follows −
Table created successfully...!Data inserted successfully...!Table Records:ID: 1, Age: 5ID: 2, Age: 3