SQL Basics - A Beginner's Guide
1. Creating a Table
Use the CREATE TABLE command to define a new table.
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(50),
age INT,
department VARCHAR(50),
salary DECIMAL(10,2)
);
2. Inserting Data
Add records using INSERT INTO.
INSERT INTO employees (id, name, age, department, salary)
VALUES
(1, 'Alice', 28, 'HR', 50000.00),
(2, 'Bob', 34, 'IT', 70000.00),
(3, 'Charlie', 25, 'Finance', 60000.00);
Table After Insertion:
| ID | Name | Age | Department | Salary |
|---|---|---|---|---|
| 1 | Alice | 28 | HR | 50000.00 |
| 2 | Bob | 34 | IT | 70000.00 |
| 3 | Charlie | 25 | Finance | 60000.00 |
3. Retrieving Data
Use SELECT * FROM to view all records.
SELECT * FROM employees;
4. Updating Data
Modify a record using UPDATE.
UPDATE employees SET salary = 75000 WHERE id = 2;
Table After Update:
| ID | Name | Age | Department | Salary |
|---|---|---|---|---|
| 1 | Alice | 28 | HR | 50000.00 |
| 2 | Bob | 34 | IT | 75000.00 |
| 3 | Charlie | 25 | Finance | 60000.00 |
5. Deleting a Record
Remove an employee using DELETE.
DELETE FROM employees WHERE id = 1;
Table After Deletion:
| ID | Name | Age | Department | Salary |
|---|---|---|---|---|
| 2 | Bob | 34 | IT | 75000.00 |
| 3 | Charlie | 25 | Finance | 60000.00 |
6. Counting Records
Find the total number of employees.
SELECT COUNT(*) FROM employees;
Output:
2
7. Sorting Data
Sort employees by salary in descending order.
SELECT * FROM employees ORDER BY salary DESC;
8. Deleting the Table
Use DROP TABLE to remove a table.
DROP TABLE employees;
0 Comments