If I declare a bunch of fields that are not always necessary, is memory allocated for each record created or does it not allocate memory until the field is initialized?
Example: If I declare a table with an id field and a char(8) field, is memory allocated for the string each time an id is generated and entered into the table, or is it only allocated if the string is assigned a value?
Short answer: It takes memory (or hard space) every time.
If a field is char(8), it will ALWAYS allocate 8 bytes (plus a leading 2 bytes for the database heading). If it is an empty varchar(34), the minimum space it will take is 2.
The database will allocate a set memory for fields whose type size doesn't change, such as numeric fields and char(n)
. But for fields of type varchar(n)
(variable-length), for example, they will be as large as the data that is contained in them.
In your example, a field type of char(8)
will allocate memory for all 8 chars. If you make the field type varchar (or nvarchar), then it will only allocate as much space as assigned to it.
Can read more about mysql string types here .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.