SQL SELECT statement with example

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

EmployeeIDFirstNameLastNameDepartmentSalary
1JohnDoeIT60000
2JaneSmithHR65000
3EmilyJohnsonIT70000
4MichaelBrownFinance75000
5SarahDavisIT72000

Example 1: Retrieve all columns for all employees

SELECT * 
FROM Employees;

This will return:

EmployeeIDFirstNameLastNameDepartmentSalary
1JohnDoeIT60000
2JaneSmithHR65000
3EmilyJohnsonIT70000
4MichaelBrownFinance75000
5SarahDavisIT72000

Example 2: Retrieve specific columns using SQL Select Statement

SELECT FirstName, LastName, Department 
FROM Employees;

This will return:

FirstNameLastNameDepartment
JohnDoeIT
JaneSmithHR
EmilyJohnsonIT
MichaelBrownFinance
SarahDavisIT

Example 3: Filter results using WHERE clause

SELECT FirstName, LastName, Department 
FROM Employees
WHERE Department = 'IT';

This will return:

FirstNameLastNameDepartment
JohnDoeIT
EmilyJohnsonIT
SarahDavisIT

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:

DepartmentAverageSalary
IT67333.33
HR75000.00

Example 5: Sort results using ORDER BY

SELECT FirstName, LastName, Salary 
FROM Employees
ORDER BY Salary DESC;

This will return:

FirstNameLastNameSalary
MichaelBrown75000
SarahDavis72000
EmilyJohnson70000
JaneSmith65000
JohnDoe60000

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.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *