Character Data Types: CHAR vs. VARCHAR, Explained

UPI Study › Courses › Database Programming › Free lessons › Lesson 3.4 Free with a free account

Character Data Types: CHAR vs. VARCHAR

Database Programming · Chapter 3: Data Definition Language and Schema DesignSection 3.4 · lesson 18 of 769 min · free with a free account

← Schemas in SQL: Definitions and Design FundamentalsNext lesson: Whole Number Data Types: INT and SMALLINT →

A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →

Earn 3 college credits for Database ProgrammingRecommended for credit by NCCRS · Computer Science 381 · self-paced · one payment, lifetime access

In this lesson

Choose fixed or variable text types, encodings, and collations.

  • Compare CHAR and VARCHAR storage, padding, and trailing-space behavior
  • Apply MySQL and SQL Server length limits, including TEXT and MAX types
  • Choose Unicode encodings such as utf8mb4 and NVARCHAR appropriately
  • Explain how collations control case and accent sensitivity in comparisons

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (999 words). Read along, or search it.

Opening Question

Names, Phones, and Country Codes

Sofia Alvarez, sales associate at Lantern Books, enters a customer's name, phone number, and country code. They are all text, but their requirements differ. A country code has a stable length. A name varies, and a phone number may begin with a zero or a plus sign. Which declaration preserves the meaning, and which settings decide whether a lowercase search finds an uppercase name?

Declarations

Fixed-Length CHAR, Variable VARCHAR

CHAR is a fixed-length character type. In MySQL, short values are padded with spaces, and trailing padding is normally removed when retrieved. VARCHAR is variable length. It stores the text plus a small length counter, retaining trailing spaces that were actually supplied. Use CHAR for genuinely fixed-length codes, and VARCHAR for bounded text whose length varies. A declared size is a policy, so check real application requirements. These are non-run MySQL declarations for a disposable profile extension. The existing course customer table remains our shared baseline. Phone numbers and postal codes are labels, even when they contain digits. Arithmetic would lose meaningful formatting and possibly leading zeros.

Storage Math

Storing Cat in CHAR and VARCHAR

Take the word cat in a single-byte MySQL storage illustration. CHAR of ten reserves ten character positions, with seven spaces of padding. VARCHAR of ten uses three bytes for cat and one byte for its length: four bytes in this example. For tiger, the comparison is ten against six. A full ten-character value needs ten against eleven, so variable length is not automatically smaller. MySQL VARCHAR uses one or two length bytes, depending on maximum byte capacity. These simplified counts exclude record overhead and physical storage-engine details.

Size Limits

MySQL and SQL Server Length Limits

In MySQL, CHAR permits up to two hundred fifty-five characters. VARCHAR lengths count characters, but the shared row limit is sixty-five thousand five hundred thirty-five bytes. Other columns and overhead consume that budget. With a four-byte character set, one character can need several bytes, so a character limit is not a byte guarantee. SQL Server CHAR and VARCHAR sizes count bytes, up to eight thousand for ordinary declarations. NVARCHAR sizes count byte-pairs, up to four thousand. SQL Server MAX forms support much larger values, up to approximately two gigabytes. Its older text and ntext types are deprecated. For MySQL strict mode, excess nonspace content produces an error rather than an accepted shortened name. Relaxed modes can truncate with warnings; excess trailing spaces have special rules.

Portability Test

SQLite Ignores the Declared Length

SQLite gives us an important portability test. A declaration that resembles another product's syntax may not enforce the same rule. This disposable table declares VARCHAR of three, then inserts six letters. Run the file before assuming the length was enforced. SQLite returns the entire value, with length six. Its VARCHAR annotation establishes text affinity, rather than a maximum string length. SQLite also does not implement MySQL's CHAR padding behavior. Use explicit constraints when a SQLite application needs a length rule.

Long Text

Choosing a MySQL TEXT Type

MySQL's TEXT family supplies byte-based capacities for longer content. Choose a family member according to expected encoded size, rather than the word text alone. TINYTEXT permits two hundred fifty-five bytes; TEXT permits sixty-five thousand five hundred thirty-five. MEDIUMTEXT and LONGTEXT allow much larger documents. An article with one hundred thousand characters can need four hundred thousand bytes, under utf8mb4. MEDIUMTEXT fits that budget; TEXT does not. Physical off-row storage depends on engine and row format. Ordinary MySQL indexes on TEXT need a prefix; full-text indexing is a separate mechanism.

Unicode

Unicode Encodings in MySQL and SQL Server

Unicode assigns codes to characters across writing systems, including many symbols and emoji. The encoding determines how those codes become stored bytes. Choose utf8mb4 for MySQL Unicode text. It uses up to four bytes per character; utf8mb3 excludes supplementary characters. MySQL NVARCHAR uses utf8mb3, its national character set. Prefer explicitly choosing utf8mb4. SQL Server NVARCHAR uses UTF sixteen under supplementary-character-aware collations. Some characters require two byte-pairs, so two bytes per character is not a universal rule. Prefix SQL Server Unicode literals with N. Modern SQL Server also supports Unicode VARCHAR through UTF eight collations; check the column's actual collation.

Collations

Case and Accent Sensitivity Rules

A character set specifies the repertoire and encoding. A collation specifies comparison and sorting rules, including case and accent sensitivity. In MySQL collation names, ci means case-insensitive, and ai means accent-insensitive. Their sensitive counterparts are cs and as. The name also identifies a character set and rules version. A binary character collation compares character codes; binary strings compare bytes. MySQL settings inherit through server, database, table, and column, with a more specific choice overriding an inherited default. SQL Server combines encoding-related choices and comparison rules in its collation system. Mixed collations can cause errors, although MySQL can resolve some combinations automatically.

Live Comparison

BINARY Versus NOCASE in SQLite

Watch comparison rules change a real result. This SQLite query compares the same two spellings under two built-in collations. BINARY distinguishes Pune from lowercase pune. NOCASE folds ASCII letters, so the case difference can compare equal. The first result is false, shown as zero; the second is true, shown as one. The stored text did not change. SQLite's built-in NOCASE is not a general Unicode case-folding system. Do not equate it with MySQL's Unicode-aware collations.

Quick Check

Size Annotation Meets NOCASE

Sofia tests a fresh SQLite table with both a type annotation and a comparison rule. The value contains five letters. The final query searches using lowercase text. Consider both the declared size and the collation before predicting its count. Pause, and decide. One matching record. SQLite accepts the five-letter value despite the size annotation, and NOCASE matches the ASCII case variation. Run the file to confirm both rules working together. The comparison finds a row; it does not count the letters inside that row. Five confuses characters with records. Zero assumes either enforced VARCHAR length or a case-sensitive comparison, neither of which applies to this SQLite definition.

Key Takeaways

Size, Encoding, and Comparison Choices

Sofia's country code fits a fixed-length policy; names need room to vary. Phone numbers stay text so their formatting survives. Size text to actual requirements, with headroom. Oversized declarations can affect row budgets, indexes, and temporary work, even when stored values are short. Choose Unicode encoding and comparison rules separately. Then test limits and comparisons on the database product that will actually store the data.

About Database Programming at UPI Study

Database Programming (Computer Science 381) is a self-paced online course of 76 video lessons in 12 chapters, from database applications, SQL setup, schema planning and normalization to keys and constraints, data types, filtering and sorting, joins, subqueries, views, indexes, ROLLUP and PIVOT, regular expressions and database security. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: Database Fundamentals vs Database Programming

Why take it here

Why students take Database Programming with UPI Study

Write the SQL behind every appDatabase Programming teaches SQL in MySQL and SQL Server side by side: designing and normalizing tables, keys and constraints, data types, inserting, updating and deleting rows, filtering, grouping, joins, subqueries, views, indexes, transactions, and protecting data from SQL injection. It suits computer science and information technology degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Database Programming carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Character Data Types: CHAR vs. VARCHAR

What is the difference between CHAR and VARCHAR?
CHAR is fixed-length and VARCHAR is variable-length. CHAR(10) reserves ten positions and pads shorter values with spaces, which suits codes that have a consistent length, such as a two-letter country code. VARCHAR(10) stores the value plus a small length prefix, which suits names and other text of varying length. Trailing-space handling and length limits differ between MySQL and SQL Server.
Does VARCHAR always use less storage than CHAR?
No, VARCHAR saves space for short values but can use more for values that fill the declared length. In a simplified single-byte MySQL example, storing cat takes ten bytes in CHAR(10) but four in VARCHAR(10): three for the text and one for its length. A full ten-character value takes ten bytes in CHAR(10) but eleven in VARCHAR(10). These counts ignore row overhead and storage-engine details.
What is the difference between VARCHAR and NVARCHAR in SQL Server?
In SQL Server, NVARCHAR stores Unicode text in two-byte units, while VARCHAR stores text in its collation's code page, or as UTF-8 under a UTF-8 collation. VARCHAR(n) counts bytes up to 8,000, NVARCHAR(n) counts byte-pairs up to 4,000, and the MAX forms hold about 2 GB. Some characters need two byte-pairs. Prefix Unicode literals with N, as in N'Pune'.
What controls whether a text comparison is case-sensitive?
Mainly the collation, which sets the comparison and sorting rules for text, including case and accent sensitivity. In MySQL collation names, ci means case-insensitive and ai means accent-insensitive, while cs and as mark the sensitive versions. In SQLite, the default BINARY collation treats 'Pune' and 'pune' as different, while NOCASE treats them as equal, although NOCASE folds just the ASCII letters. SQLite's LIKE, however, ignores ASCII case by default, whatever the collation.

About the Database Programming course

How many college credits is Database Programming?
Database Programming (Computer Science 381) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Database Programming cost and what is included?
$250, paid once, with lifetime access: all 76 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Database Programming take?
It is self-paced with no deadlines. The 76 lessons total about 11 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Database Programming.

76 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Updated

Database Programming
3 credits · NCCRS
Enroll →