Tables in MySQL
Introduction
In the previous lesson, you created and selected a database. Now it’s time to store actual data inside it.
This is where tables come in.
What is a Table?
A table is a structured format used to store data inside a database.
It is made up of rows and columns:
- Columns define what kind of data is stored
- Rows represent individual records
For example, a table for users might store names and email addresses.
Example of a Table
+----+--------+-------------------+ | id | name | email | +----+--------+-------------------+ | 1 | Rohan | rohan@email.com | +----+--------+-------------------+
Each row is a single user, and each column stores a specific piece of information.
Understanding Columns and Data Types
When creating a table, you need to define columns along with their data types.
Some common data types:
- INT: used for numbers
- VARCHAR: used for short text
- TEXT: used for longer text
Data types help MySQL understand what kind of data will be stored in each column.
Creating Your First Table
Before creating a table, make sure you have selected your database:
USE myapp;
Now create a table:
CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100), email VARCHAR(100) );
What This Command Does
- Creates a table named
users - Adds an
idcolumn that automatically increases for each record - Sets
idas the primary key (unique identifier) - Adds
nameandemailcolumns
Viewing Tables
To see all tables inside your database:
SHOW TABLES;
Common Mistakes
- Forgetting to select the database before creating a table
- Missing commas between column definitions
- Using incorrect data types
These small errors are common when starting out, so take your time while writing queries.
Summary
A table is where data is stored inside a database.
It consists of rows and columns.
You define columns using data types when creating a table.
You also learned how to create and view tables in MySQL.