Employees table and the
Departments table.
These tables are linked by the dept_id field, which serves as a foreign key (FK) in the
Employees table referencing
the primary key (PK) in the Departments table.
Employees Table| emp_id | first_name | last_name | dept_id (FK) | salary | hire_date |
|---|---|---|---|---|---|
| 101 | Alice | Smith | 1 | 70,000 | 2024-01-15 |
| 102 | Bob | Johnson | 2 | 65,000 | 2024-03-20 |
| 103 | Charlie | Williams | 1 | 85,000 | 2023-07-10 |
Departments Table| dept_id (PK) | dept_name | location |
|---|---|---|
| 1 | Engineering | New York |
| 2 | Sales | San Francisco |
The core of beginner SQL is the SELECT statement, which allows you to ask the database
for information.
SELECT *)*) and all rows from a table using the
FROM clause. SELECT * FROM Employees;
*, list the column names you want,
separated by commas. SELECT
FirstName, Salary
FROM
Employees;
WHERE Clause)The WHERE clause is your primary tool for filtering records based on specific criteria.
SELECT
FirstName, LastName, Salary
WHERE
Salary > 70000;
AND, OR, NOT)Use logical operators to narrow down your search even further.
SELECT
FirstName, DepartmentID, Salary
FROM
Employees
WHERE
DepartmentID = 1
AND Salary < 80000;
IN) and Ranges (BETWEEN) SELECT
FirstName, DepartmentID
FROM
Employees
WHERE
DepartmentID IN (1, 2);
LIKE)The LIKE operator uses wildcards (%) to search for patterns.
SELECT
FirstName, LastName
FROM
Employees
WHERE
LastName LIKE 'S%';
ORDER BY clause sorts the result set in ascending ASC or descending
DESC order. SELECT
FirstName, Salary
FROM
Employees
ORDER BY
Salary DESC;
CREATE Table Employees (
emp_id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
dept_id INT,
salary DECIMAL(10, 2),
hire_date DATE
);
Insert statements add new records INSERT INTO
Employees
(EmployeeID, FirstName, LastName, DepartmentID, Salary, HireDate)
VALUES
(104, 'David', 'Lee', 2, 60000, '2024-05-01');
Update statements modify existing records, UPDATE
Employees
SET
Salary = 75000
WHERE
EmployeeID = 101;
Delete statements to remove existing records, DELETE
Employees
SET
Salary = 75000
WHERE
EmployeeID = 101;