Lesson 3: Understanding SQL Data Types

Welcome to Lesson 3. In the previous lesson, we learned how to fetch data using SELECT. But before we can fetch data, we need to store it.

Imagine you are packing for a trip. You wouldn't wrap your shoes in a paper bag, and you wouldn't pour soup into a suitcase. You need the right container for the right item.

In SQL, Data Types are those containers.

1. Why Do We Need Data Types?

When we create a table, we must tell the database exactly what kind of data goes into each column. This helps the database:

  • Save Space: Numbers take up less space than text.
  • Prevent Errors: It stops users from entering "Hello" into a "Salary" column.
  • Sort Correctly: It knows that 10 is smaller than 2 (which isn't always true in text mode!).

2. The 3 Main Categories of Data Types

While there are many types, 90% of the time you will use these three categories:

Category Type Name Description
Numbers INTEGER Whole numbers (e.g., 1, 500, -99). used for IDs, Age, Counts.
Decimals DECIMAL(p,s) Exact numbers with decimals (e.g., 10.50). Used for Money and Prices.
Text VARCHAR(n)
Variable length text. The most common type for Names, Emails, Cities.
Date DATE Stores Year, Month, Day (YYYY-MM-DD). Used for DOB, Join Date.

3. The Most Popular Interview Question: CHAR vs VARCHAR

Both CHAR and VARCHAR store text. So, what is the difference?

CHAR (Fixed Length)

If you write CHAR(10), the database always reserves 10 spaces of memory, even if you only type "A". It fills the rest with empty spaces.

  • Use for: Data that is always the same length (e.g., Pincodes, Gender 'M'/'F').

VARCHAR (Variable Length)

If you write VARCHAR(10) and type "A", the database only uses 1 space.

  • Use for: Data that varies in length (e.g., Names, Emails, Addresses).
💡 Pro Tip: Always use VARCHAR unless you are 100% sure the length will never change. It saves memory!

4. Your Turn: Create a Table with Types

Let's build a Students table using the types we just learned.

  • ID: Number (INT)
  • Name: Text (VARCHAR)
  • GPA: Decimal (DECIMAL)
  • Dob: Date (DATE)

Step 1: Open OracleSQL or SQL Fiddle.

Step 2: Copy and Run this code to create the table and insert data:

CREATE TABLE students (
  student_id INT,
  first_name VARCHAR(50),
  gpa DECIMAL(3,2),
  dob DATE
);

INSERT INTO students VALUES (1, 'Rahul', 3.8, '2000-05-15');
INSERT INTO students VALUES (2, 'Priya', 9.2, '2001-08-20');

Step 3: Now verify your data types worked by running this:

SELECT * FROM students;

Summary: Today we learned that every column needs a datatype. We learned to use INT for numbers, VARCHAR for text, and DATE for time.

Next Lesson: In Lesson 4, we will learn about Constraints — the rules that keep our data clean.

Return to Course Syllabus

Comments

Popular posts from this blog

Lesson 1: What is a Database?

Lesson 2: Introduction to SQL

Lesson 4: SQL Constraints (Rules for Your Data).