0
0
MySQLquery~5 mins

String types (VARCHAR, CHAR, TEXT) in MySQL

Choose your learning style9 modes available
Introduction
String types store words, sentences, or any text data in a database. They help keep information like names, descriptions, or messages.
Storing a person's name or email address.
Saving a short code or ID with fixed length.
Keeping a long article or comment text.
Recording a product description that can vary in length.
Saving a status message or note.
Syntax
MySQL
column_name VARCHAR(length)
column_name CHAR(length)
column_name TEXT
VARCHAR stores variable-length strings up to the specified length.
CHAR stores fixed-length strings and pads with spaces if shorter.
TEXT stores large amounts of text without a fixed length.
Examples
Stores a name up to 50 characters long, using only the needed space.
MySQL
name VARCHAR(50)
Stores a code exactly 5 characters long, padding with spaces if shorter.
MySQL
code CHAR(5)
Stores a long text description without a fixed length limit.
MySQL
description TEXT
Sample Program
This creates a table with three string types: VARCHAR for product name, CHAR for fixed-length SKU, and TEXT for product details. Then it inserts two products and selects all data.
MySQL
CREATE TABLE products (
  id INT PRIMARY KEY,
  name VARCHAR(30),
  sku CHAR(8),
  details TEXT
);

INSERT INTO products VALUES
(1, 'Coffee Mug', 'MUG123  ', 'A ceramic mug for coffee.'),
(2, 'Notebook', 'NOTE456 ', 'A ruled notebook with 100 pages.');

SELECT id, name, sku, details FROM products;
OutputSuccess
Important Notes
VARCHAR is good for strings that change length often, saving space.
CHAR is faster for fixed-length strings but wastes space if data is shorter.
TEXT can store very long text but may be slower to search or index.
Summary
VARCHAR stores variable-length text efficiently.
CHAR stores fixed-length text, padding shorter values.
TEXT stores large text without length limits.