SQL SELECT Statement
The SQL SELECT statement is used to retrieve data from a database. The data returned by a SELECT query is called a result set, which is structured in rows and columns according to the specified criteria in the query.
In this tutorial, we will go through the syntax of SQL SELECT statement, detailed explanation for each part of the syntax, and then an example using MySQL 8.0 with queries and results from the Workbench.
Basic Syntax of the SQL SELECT Statement
The basic syntax of a SQL SELECT statement is as follows:
SELECT select_list [ INTO new_table ]
[ FROM table_source ] [ WHERE search_condition ]
[ GROUP BY group_by_expression ]
[ HAVING search_condition ]
[ ORDER BY order_expression [ ASC | DESC ] ]
Each part of this syntax has a specific purpose:
- SELECT: Specifies the columns to be retrieved. It can be specific columns or
*to select all columns. - INTO: Optional. Creates a new table to store the result.
- FROM: Specifies the table(s) from which to retrieve data.
- WHERE: Filters rows based on a specified condition.
- GROUP BY: Groups rows based on one or more columns.
- HAVING: Filters groups after grouping, typically used with aggregate functions.
- ORDER BY: Sorts the result set by one or more columns, in ascending (default) or descending order.
Step-by-Step Guide with MySQL
We’ll walk through each part of the SELECT syntax using a database and table in MySQL 8.0 with MySQL Workbench. The examples will focus on a sample students table with fields id, name, age, grade, and locality.
Step 1: Setting up the Database
1. Open MySQL Workbench.
2. To create a new database, run:
CREATE DATABASE school;
