Basic SQL Commands
Master essential SQL commands to manage and manipulate data in your databases.
Introduction to CRUD
SQL commands are categorized into four main operations, often referred to as CRUD:
- Create - Adding new data (CREATE and INSERT).
- Read - Retrieving data (SELECT).
- Update - Modifying existing data (UPDATE).
- Delete - Removing data (DELETE).
1. CREATE Command
The CREATE command is used to create new tables in a SQL database. Here’s an example:
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100)
);
This command creates a `users` table with three columns: `id`, `name`, and `email`.
ID | Name | |
---|---|---|
1 | John Doe | john@example.com |
2. INSERT Command
The INSERT command is used to add new data to a table. Example:
INSERT INTO users (name, email)
VALUES ('Jane Doe', 'jane@example.com');
This command inserts a new user record into the `users` table.
ID | Name | |
---|---|---|
1 | John Doe | john@example.com |
2 | Jane Doe | jane@example.com |
3. SELECT Command
The SELECT command is used to retrieve data from one or more tables. Example:
SELECT * FROM users;
This command retrieves all the records from the `users` table.
ID | Name | |
---|---|---|
1 | John Doe | john@example.com |
2 | Jane Doe | jane@example.com |
4. UPDATE Command
The UPDATE command is used to modify existing records in a table. Example:
UPDATE users
SET email = 'newemail@example.com'
WHERE id = 1;
This command updates the email of the user with an `id` of 1.
ID | Name | |
---|---|---|
1 | John Doe | newemail@example.com |
2 | Jane Doe | jane@example.com |
5. DELETE Command
The DELETE command is used to remove records from a table. Example:
DELETE FROM users
WHERE id = 1;
This command deletes the user with an `id` of 1 from the `users` table.
ID | Name | |
---|---|---|
2 | Jane Doe | jane@example.com |