SELECT Statement

he SELECT statement is one of the most fundamental commands in SQL. It is used to retrieve data from a database. By using SELECT, you can specify exactly which data you want to view and how it should be presented.

Basic Syntax

The basic syntax of a SELECT statement is:

SELECT column1, column2, ...
FROM table_name;
  • SELECT – specifies the columns you want to retrieve.
  • FROM – specifies the table from which to retrieve the data.

Example:

SELECT first_name, last_name
FROM employees;

This query retrieves the first_name and last_name columns from the employees table.

Selecting All Columns

To retrieve all columns from a table, use the asterisk (*):

SELECT *
FROM employees;

This will return every column in the employees table.

Using WHERE Clause

The WHERE clause allows you to filter records based on specific conditions.

Example:

SELECT first_name, last_name
FROM employees
WHERE department = 'Sales';

This query retrieves only the employees who work in the Sales department.

Using DISTINCT

The DISTINCT keyword ensures that the query returns unique values only.

Example:

SELECT DISTINCT department
FROM employees;

This query lists all the unique departments in the employees table.

Using ORDER BY

The ORDER BY clause sorts the result set by one or more columns.

Example:

SELECT first_name, last_name
FROM employees
ORDER BY last_name ASC;

This query retrieves employees’ names sorted alphabetically by last_name.

Using LIMIT

The LIMIT clause restricts the number of rows returned.

Example:

SELECT first_name, last_name
FROM employees
LIMIT 5;

This query retrieves only the first five rows from the employees table.

Summary

  • SELECT is used to fetch data from a database.
  • Columns can be specified individually or with * for all columns.
  • Filters can be applied using WHERE.
  • Unique values can be retrieved using DISTINCT.
  • Results can be sorted using ORDER BY.
  • Limit the number of results using LIMIT.
Home » SQL Foundations Program (SQL-101) > Basic Queries > SELECT Statement