Table Queries
In SQL, data is stored inside tables. A table is like an Excel sheet where:
- Columns define what type of data will be stored
- Rows store the actual records
Before we can store any data, we must first create a table.
Later, we may need to change its structure or delete it completely.
For this purpose, SQL provides Table Queries.
Adds a new column City to the table.
Change Column Data Type
Changes the type of Age column.
Remove a Coloumn
CREATE TABLE - Creating a Table
The CREATE TABLE command is used to create a new table inside a database.
Syntax
Example
CREATE TABLE table_name ( column_name data_type, column_name data_type);Example
CREATE TABLE Students ( StudentID INT, Name VARCHAR(50), Age INT);- Students → Table name
- StudentID, Name, Age → Columns
- INT, VARCHAR → Type of data stored
After this command, an empty table is created ready to store data.
ALTER TABLE - Changing Table Structure
Sometimes, after creating a table, you realize that:
- A new column is needed
- A column’s data type must be changed
- A column is no longer required
In such cases, we use ALTER TABLE.
Add a New Column
Add a New Column
ALTER TABLE StudentsADD City VARCHAR(30);Adds a new column City to the table.
Change Column Data Type
ALTER TABLE StudentsMODIFY Age VARCHAR(3);Changes the type of Age column.
Remove a Coloumn
ALTER TABLE StudentsDROP COLUMN City;Deletes the column from the table.
Always be careful altering tables may affect existing data.
DROP TABLE - Deleting a Table
The DROP TABLE command removes the table permanently.
Syntax
Example
Syntax
DROP TABLE table_name;Example
DROP TABLE Students;This deletes:
- Table structure
- All stored data
There is no undo, so use carefully.
Two Minute Drill
- Tables store data in rows and columns
- CREATE TABLE creates table structure
- ALTER TABLE modifies structure
- DROP TABLE deletes table permanently
- Structural commands must be used carefully