I have recently delved into the exciting world of SQL. I am still trying to wrap my head around the concepts. I have been following tutorials online. Many of these tutorials contain SQL for making a table like this.
CREATE TABLE `users` (
`id` tinyint(4) NOT NULL AUTO_INCREMENT,
`username` varchar(10) NOT NULL,
`password` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
After seeing lines like id tinyint(4)
I wondered what the parameter passed to the data type. I thought "does that mean id can be any integer between -128 and 127 (no more than 4 characters)?"
So I consulted the docs. This is what MySQL docs have to say about number type attributes.
The display width does not constrain the range of values that can be
stored in the column. Nor does it prevent values wider than the column
display width from being displayed correctly. For example, a column
specified as SMALLINT(3) has the usual SMALLINT range of -32768 to
32767, and values outside the range permitted by three digits are
displayed in full using more than three digits
When used in conjunction with the optional (nonstandard) attribute
ZEROFILL, the default padding of spaces is replaced with zeros. For
example, for a column declared as INT(4) ZEROFILL, a value of 5 is
retrieved as 0005.
So if I'm reading this right, declaring things like INT(255)
are useless unless you are using zerofill. Ok makes sense you declare a datatype the database allocates enough space for that database.
So why do people write code like this? Does it serve a purpose? Am I completely misunderstanding?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…