SQL SELECT Statement Tutorial
Example Table
We will use the following table named employees
for our examples:
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
department VARCHAR(50),
salary DECIMAL(10, 2)
);
INSERT INTO employees (employee_id, first_name, last_name, department, salary) VALUES
(1, 'John', 'Doe', 'HR', 50000.00),
(2, 'Jane', 'Smith', 'Finance', 60000.00),
(3, 'Emily', 'Jones', 'IT', 70000.00),
(4, 'Michael', 'Brown', 'IT', 80000.00),
(5, 'Sarah', 'Davis', 'Finance', 55000.00);
Employees Table
employee_id | first_name | last_name | department | salary |
---|---|---|---|---|
1 | John | Doe | HR | 50000.00 |
2 | Jane | Smith | Finance | 60000.00 |
3 | Emily | Jones | IT | 70000.00 |
4 | Michael | Brown | IT | 80000.00 |
5 | Sarah | Davis | Finance | 55000.00 |
Using SQL SELECT Statement
The SELECT
statement is used to select data from a database. The data returned is stored in a result table, sometimes called the result set.
Example: Selecting All Columns
To select all columns from the employees
table:
SELECT * FROM employees;
Result:
Query | SELECT * FROM employees; |
---|---|
Result | Returns all columns and rows from the employees table. |
Example: Selecting Specific Columns
To select specific columns, such as first_name
and last_name
:
SELECT first_name, last_name FROM employees;
Result:
Query | SELECT first_name, last_name FROM employees; |
---|---|
Result | Returns the first_name and last_name columns from the employees table. |
Example: Using WHERE Clause
To select employees from the IT department:
SELECT * FROM employees WHERE department = 'IT';
Result:
Query | SELECT * FROM employees WHERE department = 'IT'; |
---|---|
Result | Returns all columns for employees in the IT department. |
Example: Using ORDER BY Clause
To select all employees and order the result by salary in descending order:
SELECT * FROM employees ORDER BY salary DESC;
Result:
Query | SELECT * FROM employees ORDER BY salary DESC; |
---|---|
Result | Returns all columns for employees ordered by salary in descending order. |