MySQL provides a variety of data types to store different kinds of data. These are categorized into three main groups:
1. Numeric Data Types:
- INT, BIGINT, SMALLINT, TINYINT: For whole numbers.
- DECIMAL, FLOAT, DOUBLE: For real numbers with decimal points.
- BIT: For binary values.
- Example:
CREATE TABLE numeric_example (
id INT,
amount DECIMAL(10, 2)
);
1. String Data Types:
- CHAR, VARCHAR: For fixed and variable-length strings.
- TEXT: For large text.
- BLOB: For binary large objects like images.
- Example:
CREATE TABLE string_example (
name VARCHAR(100),
description TEXT
);
1. Date and Time Data Types:
- DATE, DATETIME, TIMESTAMP: For date and time values.
- YEAR: For storing a year.
- Example:
CREATE TABLE datetime_example (
created_at DATETIME,
year_of_joining YEAR
);
Interview Questions:
- Q1: What is the difference between CHAR and VARCHAR?
A1: CHAR has a fixed length, while VARCHAR has a variable length. VARCHAR is more storage-efficient for varying-length data.
- Q2: When should you use DECIMAL instead of FLOAT?
A2: Use DECIMAL for precise calculations (e.g., financial data) and FLOAT for approximate values where precision is less critical.