Suppose to have a table containing a varchar field like this:
CREATE TABLE IF NOT EXISTS `users` (
`name` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Does MySQL database size depend on varchar length? I mean: when I insert a user into table, does database size increase of 150 bytes, independently from actual entry content? Or does it depend from effective data size (if I insert "abc" as user name, database increases of 3 bytes only)? Is there a best practice when deciding varchar lenght?
No, not entirely.
Most common relational databases use a concept called 'pages', which are blocks of a certain size of storage. Within these pages the rows are then stored. A varchar
field, by its very definition, only takes up the storage actually required for the string, but may or may not need a new page to contain its row. Also, as rows are deleted, added and modified gaps will appear in pages until the table is optimized or reused. This is all normal and fine as it is how the DBMS itself internally manages to stay performant in most situations.
To sum up: there is a loose relationship between field sizes and database sizes, but it's normal for the database to be notably larger than the sum of its data at any given point in time. However a varchar(150)
with 10 character of data will not use more than about 11 bytes (depending on encoding, and including trailing zero) on its own in most engines.
As for best practice: yes, a varchar
should be sized to 'reasonably be able to contain the largest possible string for its domain'. A varchar(1024)
does not make sense for a FirstName
field, and a varchar(16)
will not work for City
. Use common sense, it doesn't matter for storage.