SQL Basics
Before writing powerful SQL queries, it is very important to understand how data is stored inside a database. SQL works on a structured model, and once you understand this structure, everything else becomes easy.
Understanding Tables
A table is the most important object in a relational database. All data in SQL databases is stored inside tables.
You can think of a table like a spreadsheet:
- Each table has a name
- Each table contains rows and columns
- Each table stores data about one specific subject
Rows and Columns Explained
Let’s break down the structure of a table:
| Component | Description | Example |
|---|---|---|
| Table | Collection of related data | employees |
| Column | Type of information | name, salary, department |
| Row | One complete record | One employee’s data |
Visualizing a Table
Consider the following employees table:
+----+----------+------------+--------+ | id | name | department | salary | +----+----------+------------+--------+ | 1 | Alice | HR | 60000 | | 2 | Bob | IT | 75000 | | 3 | Charlie | Finance | 70000 | +----+----------+------------+--------+
In this table:
- Each row represents one employee
- Each column represents a specific attribute
- The
idcolumn uniquely identifies each row
What is a Primary Key?
A primary key is a column (or group of columns) that uniquely identifies each row in a table.
Key characteristics of a primary key:
- It must be unique
- It cannot be NULL
- Each table should have one primary key
In the employees table, the id column is a
primary key.
Basic SQL Statement Structure
Most SQL queries follow a simple and readable structure:
SELECT column_name FROM table_name;
This structure clearly answers two questions:
- What data do you want? →
SELECT - From where? →
FROM
Example: Selecting Data from a Table
To view all columns and rows from the employees table:
SELECT * FROM employees;
Explanation:
SELECT *means select all columnsFROM employeesspecifies the table name
Why This Structure Matters
Understanding tables, rows, and columns helps you:
- Write correct SQL queries
- Design clean databases
- Avoid data duplication
- Understand joins and relationships later
Every advanced SQL concept builds on these basics, so take time to understand them well.
What’s Next?
In the next lesson, we will focus completely on the SELECT statement and learn how to retrieve specific columns and format query results.