The SELECT
statement is one of the most commonly used SQL commands and is essential for retrieving data from a database. This tutorial will guide you through the basics of using the SELECT
statement to query data from a single table.
The SELECT
statement is used to select data from a database. The data returned is stored in a result table, sometimes called the result set.
The basic syntax of the SELECT
statement is as follows:
sql1SELECT column1, column2, ... 2FROM table_name;
column1, column2, ...
are the fields (columns) of the table you want to fetch data from.table_name
is the name of the table from which you want to retrieve the data.To select all columns from a table, you can use the asterisk (*) wildcard character.
sql1SELECT * FROM table_name;
This will return every column from every row in the table.
To retrieve only the necessary data, specify the column names you want to select:
sql1SELECT column1, column2 FROM table_name;
This will return only the data from column1
and column2
.
Aliases can be used to give a table or a column a temporary name. This is useful for improving readability or when you have multiple columns with the same name from different tables.
sql1SELECT column_name AS alias_name FROM table_name;
For example:
sql1SELECT first_name AS FirstName, last_name AS LastName FROM employees;
The SELECT
statement can be combined with a WHERE
clause to filter the results based on a condition.
sql1SELECT column1, column2 FROM table_name WHERE condition;
For example:
sql1SELECT FirstName, LastName FROM employees WHERE Department = 'Sales';
You can sort the result set by one or more columns using the ORDER BY
clause. The default sorting order is ascending (ASC). To sort in descending order, use the DESC
keyword.
sql1SELECT column1, column2 FROM table_name ORDER BY column1 ASC, column2 DESC;
For example:
sql1SELECT FirstName, LastName FROM employees ORDER BY LastName ASC;
To limit the number of rows returned by a query, you can use the LIMIT
clause.
sql1SELECT column1, column2 FROM table_name LIMIT number;
For example, to get only the first 10 rows:
sql1SELECT * FROM employees LIMIT 10;
You can combine column values into a single column using the concatenation operator (||
in some databases like PostgreSQL or CONCAT()
function in others like MySQL).
sql1SELECT CONCAT(column1, ' ', column2) AS full_name FROM table_name;
For example:
sql1SELECT CONCAT(FirstName, ' ', LastName) AS FullName FROM employees;
To get distinct values from a column, use the DISTINCT
keyword.
sql1SELECT DISTINCT column1 FROM table_name;
For example:
sql1SELECT DISTINCT Department FROM employees;
The SELECT
statement is a powerful tool in SQL for retrieving data from a database. By specifying columns, using aliases, filtering with conditions, sorting, limiting, concatenating values, and selecting distinct entries, you can manipulate the result set to meet your requirements.