SQL DATA TYPES - COMPLETE GUIDE
1. What is a Data Type?
A data type defines what kind of data (text, numbers, dates, etc.) a column can store in a table.
Example:
CREATE TABLE Students (
ID INT, -- Stores whole numbers
Name VARCHAR(50), -- Stores text (up to 50 characters)
Age INT, -- Stores whole numbers
Email VARCHAR(100), -- Stores text (up to 100 characters)
Registration_Date DATE -- Stores date values
);
---------------------------------
2. Common SQL Data Types
2.1 String (Text) Data Types:
- CHAR(n): Fixed-length text. Example: CHAR(5) stores "abc " (always 5 characters, adds spaces if short)
- VARCHAR(n): Variable-length text. Example: VARCHAR(5) stores "abc" (only 3 characters, no extra spac
- TEXT: Stores large amounts of text (e.g., descriptions, comments).
2.2 Numeric Data Types:
- INT: Whole numbers (e.g., 23, 100, -45).
- BIGINT: Larger whole numbers (e.g., 9999999999999).
- DECIMAL(p,s) / NUMERIC(p,s): Stores exact decimal values (e.g., DECIMAL(5,2) 99.99).
- FLOAT / DOUBLE: Stores large decimal numbers, used in scientific calculations.
2.3 Date and Time Data Types:
- DATE: Stores only date (YYYY-MM-DD 2024-03-13).
- TIME: Stores only time (HH:MI:SS 14:30:00).
- DATETIME: Stores both date and time (YYYY-MM-DD HH:MI:SS 2024-03-13 14:30:00).
- TIMESTAMP: Stores date-time in UTC (used for tracking changes).
2.4 Boolean Data Type:
- BOOLEAN or BIT: Stores TRUE (1) or FALSE (0). Used for flags (e.g., IsActive column).
---------------------------------
3. Choosing the Right Data Type
| Type of Data | Best Data Type | Example |
|--------------------|--------------------|---------|
| Names | VARCHAR(50) | "Priya" |
| Mobile Number | CHAR(10) | "9876543210" |
| Email | VARCHAR(100) | "
[email protected]" |
| Age | INT | 25 |
| Salary | DECIMAL(10,2) | 50000.75 |
| Registration Date | DATE | 2024-03-13 |
| Order Timestamp | DATETIME | 2024-03-13 10:30:00 |
| Product Quantity | INT | 100 |
| Description | TEXT | "This is a product description" |
| Active User | BOOLEAN | 1 (True), 0 (False) |
---------------------------------
4. Practical Example - Creating a Table
CREATE TABLE Customers (
CustomerID INT PRIMARY KEY, -- Unique ID for each customer
FirstName VARCHAR(50), -- Customer's first name
LastName VARCHAR(50), -- Customer's last name
Email VARCHAR(100) UNIQUE, -- Email must be unique
Phone CHAR(10), -- Exactly 10-digit phone numbers
BirthDate DATE, -- Date of birth
AccountBalance DECIMAL(10,2), -- Balance with 2 decimal places
IsPremiumMember BOOLEAN -- True (1) or False (0)
);
---------------------------------
5. What's Next?
Now that you understand data types, do you want to:
1. Learn how to insert data (INSERT statement)?
2. Learn how to update and delete records (UPDATE and DELETE)?
3. Learn constraints like PRIMARY KEY, FOREIGN KEY, and UNIQUE?