jonlucc
jonlucc

Reputation: 37

How is database memory allocated?

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?

Upvotes: 2

Views: 1443

Answers (2)

JonathanEyre
JonathanEyre

Reputation: 63

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.

Upvotes: 2

Nick Rolando
Nick Rolando

Reputation: 26167

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.

Upvotes: 2

Related Questions