Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The best data type to store 0, 1, null values

Tags:

php

mysql

I have three values: 0, 1, NULL. Now I want to know, what data type is fine for that column?

But the way, NULL is default of that column (in the database) and I achieve 0 and 1 form parameter (get method) of URL. Something like this:

www.example.com/?q=param=0

And then

$var = isset($_GET['param']) ? $_GET['param'] : null;

And then

INSERT INTO table(col) values ($var);
like image 556
stack Avatar asked Dec 25 '15 01:12

stack


People also ask

Which data type stores the values 0 or 1 only?

The bool data type The assignment statements use the words true or false and not the strings “true” and “false”. Bool data are stored in memory as int values. False is stored as 0 and true is stored as 1.

Which of the following data type can store only 0 1 and?

Boolean (true/false) data; Access stores the numeric value zero (0) for false, and -1 for true. 1 byte.

Which data type will accept NULL value?

A NULL value can be inserted into columns of any data type. A NULL value will evaluate NULL in any expression.

Which data type stores the values 0 or 1 only example Yes No?

The BIT data type, which can only store integers 0 and 1 apart from NULL, is commonly used as a workaround to store Boolean values, but workarounds need to be used such as UPDATE t SET flag = IIF(col IS NOT NULL, 1, 0) WHERE flag = 0 to convert between the integer and boolean expression.


2 Answers

UPDATE

Since MySQL (8.0.16) and MariaDB (10.2.1) both implemented the CHECK constraint, I would now go with

bool_val TINYINT UNSIGNED CHECK(bool_val <= 1)

db<>fiddle

or

bool_val TINYINT CHECK(bool_val IN(0,1))

db<>fiddle

Original answer

I would use Bit-Value Type - BIT

BIT(1) NULL DEFAULT NULL

BIT(1) needs 1 Byte of storage, wich is the same as TINYINT(1) does. The difference is that BIT(1) only accepts the values 0 and 1 (or b'0' and b'1') while TINYINT(1) UNSIGNED accepts values from 0 up to 255. The length defined in the brackets for TINYINT does not take any affect to values that can be stored. It is only an information for clients, how to display the values (e.g. if you use ZEROFILL).

like image 143
Paul Spiegel Avatar answered Oct 24 '22 00:10

Paul Spiegel


It's 2019! This was marked correct years ago. Please see Paul Spiegel's answer directly below this one for a more modern answer. #

TINYINT(1) UNSIGNED NULL

tinyint's are perfect for booleans

like image 9
joeycrash135 Avatar answered Oct 23 '22 23:10

joeycrash135