SQL Tutorial



SELECT STATEMENT


SELECT Statement in SQL

The SELECT statement is one of the most important commands in SQL. It is used to query the database and retrieve records from one or more tables. You can retrieve all columns or specify which columns to retrieve.

Basic SELECT Syntax

To select data from a table, use the following basic syntax:

SELECT column1, column2, ... FROM table_name;

Example: SELECT name, age FROM Employees; will retrieve the name and age columns from the Employees table.

Selecting All Columns

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

SELECT * FROM Employees;

This command retrieves all columns from the Employees table. However, using * can be inefficient if you only need a few columns.

Using WHERE Clause

The WHERE clause is used to filter records based on specific conditions.

SELECT name, age FROM Employees WHERE age > 30;

This will select only the name and age columns for employees who are older than 30.

Sorting Results with ORDER BY

You can sort your results using the ORDER BY clause. By default, it sorts in ascending order. To sort in descending order, add DESC.

SELECT name, age FROM Employees ORDER BY age DESC;

This example sorts the result by the age column in descending order (oldest first).

Limiting the Number of Records

The LIMIT clause is used to limit the number of rows returned in the result.

SELECT name, age FROM Employees LIMIT 5;

This command returns only the first 5 records from the Employees table.

Using DISTINCT for Unique Values

The DISTINCT keyword is used to return only unique (non-duplicate) values.

SELECT DISTINCT department FROM Employees;

This will return a list of all unique departments in the Employees table, removing any duplicates.

Tip

Try to be specific when selecting columns to avoid unnecessary data retrieval. For example, instead of selecting all columns with SELECT *, try selecting only the columns you need, like SELECT name, age.


🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review