INSERT Statement for Adding Data
What you'll learn: How to add new rows of data to a database table using the INSERT statement with explicit column names and values.
The Core Idea
The INSERT statement is SQL's way of adding new records (rows) to a table. Think of it like filling out a form: you specify which fields (columns) you're filling in and what values go into each field. By explicitly naming the columns, you make your code clearer and avoid errors if the table structure changes later.
Basic Syntax
INSERT INTO table_name (column1, column2, column3)
VALUES (value1, value2, value3);
You list the table name, then the columns you want to populate in parentheses, followed by the keyword VALUES and the corresponding values in the same order.
Practical Example
Suppose you have a students table with columns: id, name, age, and email.
INSERT INTO students (id, name, age, email)
VALUES (101, 'Alice Johnson', 20, 'alice@example.com');
This creates one new row with Alice's information. Notice the column names match the values one-to-one.
Why Specify Columns Explicitly?
You could omit the column list and just write VALUES (...), but explicitly naming columns:
- Makes your intent crystal clear
- Protects against column reordering in the table
- Lets you insert data into only some columns (others get default or NULL values)
INSERT INTO students (name, email)
VALUES ('Bob Smith', 'bob@example.com');
Here id and age would use their defaults or remain NULL.
Key Takeaway: The INSERT statement adds new rows to a table by explicitly specifying column names and their corresponding values, making your data additions clear, safe, and flexible.