Table Column Types for Character Strings

This section describes 4 types of table columns to store character strings: CHAR, VARCHAR, NCHAR and NCHAR VARYING.

There are 4 types of table columns to store character strings: CHAR, VARCHAR, NCHAR and NCHAR VARYING.

"CHARACTER(length) or CHAR(length)" - Character string with fixed length.

"CHARACTER VARYING(length) or VARCHAR(length)" - Character string with varying length.

"NATIONAL CHARACTER(length) or NCHAR(length)" - National character string with fixed length.

"NATIONAL CHARACTER VARYING(length) or NCHAR VARYING(length)" - National character string with varying length.

Examples of character string column types, CharStringColumns.sql:

-- CharStringColumns.sql
-- Copyright (c) 2015, HerongYang.com, All Rights Reserved.
--
CREATE TABLE CharString (
   Line VARCHAR(2),
   A CHAR(8),
   B VARCHAR(8), 
   C NCHAR(8),
   D NCHAR VARYING(8)
   );
INSERT INTO CharString VALUES (
   '1',
   'AAA',
   'BBB', 
   'CCC',
   'DDD'
   );
INSERT INTO CharString VALUES (
   '2',
   'AAAAAA',
   'BBBBBB', 
   'CCCCCC',
   'DDDDDD'
   );
INSERT INTO CharString VALUES (
   '3',
   'AAAAAAAAA',
   'BBBBBBBBB', 
   'CCCCCCCCC',
   'DDDDDDDDD'
   );
SELECT * FROM CharString;
DROP TABLE CharString;

Run CharStringColumns.sql on MySQL 5.7 server, you will get:

C:\herong>set "MySQL=\Program Files\MySQL\MySQL Server 5.7"
C:\herong>"%MySQL%\bin\mysql" --user=root --password=TopSecret test 
   < CharStringColumns.sql

ERROR 1406 (22001) at line 25: Data too long for column 'A' at row 1

Note that MySQL 5.7 is rejecting character string literals that are longer than their column sizes.

But run CharStringColumns.sql on MySQL 5.6, 5.0, and 4.0 servers, you will get:

Line    A       B       C       D
1       AAA     BBB     CCC     DDD
2       AAAAAA  BBBBBB  CCCCCC  DDDDDD
3       AAAAAAAA        BBBBBBBB        CCCCCCCC        DDDDDDDD

Note that character string data is truncated when the column size is reached.

Last update: 2015.

Table of Contents

 About This Book

 Introduction of SQL

 MySQL Introduction and Installation

 Introduction of MySQL Programs

 Perl Programs and MySQL Servers

 PHP Programs and MySQL Servers

 Java Programs and MySQL Servers

 Datatypes and Data Literals

 Operations and Expressions

 Character Strings and Bit Strings

 Commonly Used Functions

Table Column Types for Different Types of Values

Table Column Types for Character Strings

 Table Column Types for Bit Strings

 Table Column Types for Exact Numbers

 Table Column Types for Approximate Numbers

 Table Column Types for Date and Time Values

 Using DDL to Create Tables and Indexes

 Using DML to Insert, Update and Delete Records

 Using SELECT to Query Database

 Transaction Management and Isolation Levels

 Locks Used in MySQL

 Defining and Calling Stored Procedures

 Variables, Loops and Cursors Used in Stored Procedures

 Outdated Tutorials

 References

 PDF Printing Version