In SQL, the SELECT statement is used to retrieve data from one or more tables in a database. It allows you to specify the columns you want to retrieve, apply filters, and sort the data based on certain conditions. Let’s explore how to use the SELECT statement to retrieve data from a table.
Syntax of SELECT statement
The basic syntax of the SELECT statement is as follows:
SELECT column1, column2, ...
FROM table_name
WHERE condition
ORDER BY column ASC/DESC;
- SELECT: Specifies the columns you want to retrieve from the table.
- FROM: Specifies the table from which you want to retrieve data.
- WHERE: Specifies the conditions to filter the rows.
- ORDER BY: Specifies the column(s) to sort the result set. ASC for ascending order, DESC for descending order.
Example
Let’s consider a table named employees
with the following columns: employee_id
, first_name
, last_name
, email
, salary
, hire_date
.
Here’s an example of a SELECT statement that retrieves the first_name
, last_name
, and salary
columns from the employees
table:
SELECT first_name, last_name, salary
FROM employees;
To filter the result set, you can add a WHERE clause. For example, to retrieve only the employees with a salary greater than 5000:
SELECT first_name, last_name, salary
FROM employees
WHERE salary > 5000;
You can also use the ORDER BY clause to sort the result set based on a specific column. For example, to sort the employees by their salary in descending order:
SELECT first_name, last_name, salary
FROM employees
ORDER BY salary DESC;
Remember to replace table_name
with the actual name of the table you want to query.