A SELECT statement is used to retrieve data from one or more tables in a database. It retrieves a set of records or rows that match a specified condition or set of conditions.
The basic structure of a SELECT statement is as follows:
SELECT [column(s)/expression(s)]
FROM [table(s)/view(s)]
WHERE [condition(s)]
GROUP BY [column(s)]
HAVING [condition(s)]
ORDER BY [column(s)] [ASC/DESC];
Let’s break down each component of the statement:
- ‘SELECT‘: This is the keyword used to specify the columns or expressions that you want to retrieve from the table. If you want to retrieve all columns, you can use a ‘*‘ instead of specifying individual column names.
- ‘FROM‘: This is the keyword used to specify the table or view from which you want to retrieve the data. You can also specify multiple tables or views by separating them with commas.
- ‘WHERE‘: This is the keyword used to specify the condition or set of conditions that must be met to retrieve the data. You can use comparison operators like ‘=‘, ‘!=‘, ‘<‘, ‘>‘, ‘<=‘, ‘>=‘, logical operators like ‘AND‘, ‘OR‘, and wildcard characters like ‘
- ‘GROUP BY‘: This is the keyword used to group the results by one or more columns. This is typically used with aggregate functions like ‘SUM‘, ‘AVG‘, ‘MIN‘, ‘MAX‘, or ‘COUNT‘ to summarize data.
- ‘HAVING‘: This is the keyword used to filter the results based on aggregated column values. This is similar to the ‘WHERE‘ clause but applies to groups of rows rather than individual rows.
- ‘ORDER BY‘: This is the keyword used to sort the results by one or more columns. You can specify ‘ASC‘ (ascending) or ‘DESC‘ (descending) for each column to control the order of the results.
Here is an example of a simple SELECT statement that retrieves all columns from a table called ‘employees‘:
SELECT *
FROM employees;
And here is an example of a more complex SELECT statement that retrieves only the ‘department_id‘ and the sum of the ‘salary‘ for each department with a sum of at least 1 million, grouped by ‘department_id‘, and ordered by the sum of salaries in descending order:
SELECT department_id, SUM(salary)
FROM employees
GROUP BY department_id
HAVING SUM(salary) > 1000000
ORDER BY SUM(salary) DESC;