liveBook · Manning

Fixed-length string

As explained in 100 SQL Server Mistakes and How to Avoid Them

A fixed-length string is a character data type whose storage allocation is determined by its declared length and may include padding.

A fixed-length string reserves storage according to its declared length. CHAR and NCHAR pad shorter values with whitespace, so assuming VARCHAR(10) and CHAR(10) always use the same storage is incorrect. section 3.2

Mistake #7: always choosing variable-length strings.

  • Use a fixed-length string when values in a column consistently have the same length; use a variable-length string when their lengths vary. section 3.6
  • A ZIP code known to be exactly 10 characters is a candidate for CHAR(10), while city and state names require lengths that accommodate varying values. section 3.2
  • Account for padding and SQL Server row-storage metadata when estimating space rather than comparing declared lengths alone. section 3.2

Converting DepartmentCode

When every department code has two characters, convert the column with: ALTER TABLE dbo.Employees ALTER COLUMN DepartmentCode NCHAR(2);

How 100 SQL Server Mistakes and How to Avoid Them covers it

How deep it goes
Explains padding, row metadata, and storage pages, then stops short of a complete storage-sizing procedure.
Examples
Uses ZIP codes, address names, the value Hello!, and an Employees.DepartmentCode alteration to illustrate datatype choices.
What it assumes
Assumes basic familiarity with SQL Server columns and string types while explaining padding and row storage directly.
What you can do after
Configure columns with fixed-length or variable-length string types according to the consistency of their stored values.
How it connects
Connects fixed-length strings with variable-length strings, CHAR, NCHAR, VARCHAR, storage overhead, and SQL Server data types.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 SQL Server Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.