MySQL Data Types Explained
# CHAPTER 5
MySQL Data Types Explained
1. Introduction
If you try to pour a gallon of water into a shot glass, it will spill everywhere. If you build a massive swimming pool just to hold a shot of water, it is an incredible waste of space. Database columns work exactly the same way. When creating a table, you must tell MySQL exactly what kind of data (and how much of it) a column is allowed to hold. In this chapter, we will master Data Types, the security guards that guarantee data integrity and optimize server storage.2. Learning Objectives
By the end of this chapter, you will be able to:- Explain why strict Data Types are necessary.
-
Differentiate between various Numeric types (
INT,DECIMAL).
-
Differentiate between String types (
VARCHAR,TEXT).
-
Store temporal data using
DATEandDATETIME.
-
Restrict inputs using
ENUMandBOOLEAN.
3. Why Data Types Matter
Imagine you have anage column, and you do not restrict the data type.
-
User 1 enters:
25
-
User 2 enters:
Twenty-five
-
User 3 enters:
Old enough
If you try to run a mathematical query later: SELECT users WHERE age > 18, the database will crash because it cannot do math on the text "Old enough".
By forcing the age column to be an INT (Integer), MySQL will block User 2 and User 3 from ever saving their data. Data Types guarantee that your data remains clean and mathematically predictable.
4. Numeric Data Types
Used for math, counting, and ID numbers.-
INT(Integer): Stores whole numbers (no decimals) from roughly -2 billion to +2 billion.
-
*Best for:* IDs (
userid), age, counters (number of likes).
-
TINYINT: A super small integer from -128 to 127.
- *Best for:* Boolean flags (0 or 1), or tiny categories.
-
DECIMAL(M, D): Stores exact decimal values. M is the total number of digits, D is the number of digits after the decimal point.DECIMAL(10, 2)means 10 total digits, 2 after the dot (e.g.,12345678.99).
- *Best for:* Financial data (Money, Prices). *Never use FLOAT or DOUBLE for money, as they introduce microscopic rounding errors!*
5. String (Text) Data Types
Used for names, emails, and paragraphs.-
VARCHAR(length): Variable-length character string. Thelengthspecifies the maximum number of characters allowed. If you specifyVARCHAR(50), and a user types a 51-character name, MySQL will throw an error.
- *Best for:* First names, emails, passwords, short titles.
-
CHAR(length): Fixed-length character string. If you specifyCHAR(2)and type "A", it pads the rest with blank spaces.
- *Best for:* 2-letter Country Codes (US, UK), or fixed-length hashes.
-
TEXT: Stores massive strings up to 65,535 characters long.
- *Best for:* Blog post bodies, long user comments, product descriptions.
6. Date and Time Data Types
Used for tracking when events happen.-
DATE: Stores a date in the formatYYYY-MM-DD(e.g.,2024-12-25).
- *Best for:* Birthdays, expiration dates.
-
TIME: Stores a time in the formatHH:MM:SS.
-
DATETIME: Combines both intoYYYY-MM-DD HH:MM:SS.
-
*Best for:* Tracking exact timestamps (e.g.,
accountcreatedat,lastlogin).
7. ENUM and BOOLEAN
Used for strict, limited choices.-
BOOLEAN(orBOOL): In MySQL,BOOLEANis actually just a synonym forTINYINT(1). It stores either1(True) or0(False).
-
*Best for:*
isactive,isadmin,haspaid.
-
ENUM('value1', 'value2'): A string object that can have only one value, chosen from the list of values you define.
-
*Best for:*
shirtsize ENUM('S', 'M', 'L', 'XL')ororder_status ENUM('Pending', 'Shipped', 'Delivered').
8. Mini Project: A Complete User Table
Let's build a highly optimized table utilizing everything we just learned.9. Common Mistakes
-
Using
VARCHAR(255)for everything: Beginners often useVARCHAR(255)for every text column because they are lazy. While it works, it makes the database engine work harder during sorting and indexing. Always restrictVARCHARto the realistic maximum you expect.
-
Using
INTfor Phone Numbers: Do not useINTto store phone numbers (555-1234). Integers do not allow dashes, and if a phone number starts with a0(e.g.,0123456789), theINTdata type will automatically delete the leading zero! Always useVARCHARfor phone numbers.
10. Best Practices
-
Think about Storage Constraints: Every column you create consumes hard drive space. Using an
INT(4 bytes) to store a person's age is a waste of space when aTINYINT(1 byte) can hold numbers up to 127. In a table with a billion rows, choosing the right data type saves gigabytes of space.
11. Exercises
- 1. What data type should you use to store a user's account balance, and why shouldn't you use a standard floating-point number?
-
2.
Write the SQL syntax to create a column named
statusthat only accepts the words 'Active', 'Suspended', or 'Banned'.
12. MCQ Quiz with Answers
If you attempt to insert the text string "Thirty" into a column defined as an INT, what will MySQL do?
Why is the VARCHAR data type preferred over INT for storing phone numbers or zip codes?
13. Interview Questions
-
Q: Explain the difference between
VARCHARandCHARdata types in MySQL, and provide a use-case whereCHARwould be superior.
-
Q: Describe the behavior of the
ENUMdata type. In what scenario would anENUMbe a poor architectural choice? (Hint: Think about lists of options that change frequently).
14. FAQs
Q: What happens if I insert a 100-character string into aVARCHAR(50) column?
A: In modern MySQL configurations (Strict Mode), the database will immediately throw a "Data too long" error and reject the entry. In older versions, it would silently truncate (cut off) the final 50 characters and save the first half!