SQL SELECT Statement: The SELECT
statement in SQL is used to retrieve data from one or more tables in a database. It allows you to specify which columns you want to retrieve and apply various conditions, groupings, and orderings to the data.
Basic Structure of a SQL SELECT Statement
SELECT column1, column2, ...
FROM table_name
WHERE condition
GROUP BY column
HAVING condition
ORDER BY column;
- SELECT: Specifies the columns you want to retrieve.
- FROM: Specifies the table from which to retrieve the data.
- WHERE: Applies a filter to the data to only include rows that meet certain conditions.
- GROUP BY: Groups rows that have the same values in specified columns into summary rows.
- HAVING: Applies a filter to groups after they have been created by the
GROUP BY
clause. - ORDER BY: Specifies the order in which the results should be returned.
Example of SQL Select Statement
Let’s say you have a table called Employees
with the following columns: EmployeeID
, FirstName
, LastName
, Department
, and Salary
.
Table: Employees
EmployeeID | FirstName | LastName | Department | Salary |
1 | John | Doe | IT | 60000 |
2 | Jane | Smith | HR | 65000 |
3 | Emily | Johnson | IT | 70000 |
4 | Michael | Brown | Finance | 75000 |
5 | Sarah | Davis | IT | 72000 |
Example 1: Retrieve all columns for all employees
SELECT *
FROM Employees;
This will return:
EmployeeID | FirstName | LastName | Department | Salary |
1 | John | Doe | IT | 60000 |
2 | Jane | Smith | HR | 65000 |
3 | Emily | Johnson | IT | 70000 |
4 | Michael | Brown | Finance | 75000 |
5 | Sarah | Davis | IT | 72000 |
Example 2: Retrieve specific columns using SQL Select Statement
SELECT FirstName, LastName, Department
FROM Employees;
This will return:
FirstName | LastName | Department |
John | Doe | IT |
Jane | Smith | HR |
Emily | Johnson | IT |
Michael | Brown | Finance |
Sarah | Davis | IT |
Example 3: Filter results using WHERE clause
SELECT FirstName, LastName, Department
FROM Employees
WHERE Department = 'IT';
This will return:
FirstName | LastName | Department |
John | Doe | IT |
Emily | Johnson | IT |
Sarah | Davis | IT |
Example 4: Group data using GROUP BY and filter groups using HAVING
SELECT Department, AVG(Salary) as AverageSalary
FROM Employees
GROUP BY Department
HAVING AVG(Salary) > 65000;
This will return:
Department | AverageSalary |
IT | 67333.33 |
HR | 75000.00 |
Example 5: Sort results using ORDER BY
SELECT FirstName, LastName, Salary
FROM Employees
ORDER BY Salary DESC;
This will return:
FirstName | LastName | Salary |
Michael | Brown | 75000 |
Sarah | Davis | 72000 |
Emily | Johnson | 70000 |
Jane | Smith | 65000 |
John | Doe | 60000 |
Summary
The SELECT
statement is highly flexible and can be used to query and manipulate data in various ways, depending on your needs. The examples above demonstrate some of the fundamental operations that can be performed using SQL SELECT
.