SQL SELECT Statement
The SELECT
statement is the most commonly used SQL command. It is used to select or retrieve data from one or more tables in the database. The SELECT
statement can be used to fetch all rows from a table at one time or to fetch only the rows that satisfy certain criteria.
Syntax
The basic syntax of the SELECT
statement for selecting data from a table is as follows.
SELECT clumn1_name, column2_name, columnN_name
FROM table_name;
In the above, column1_name, column2_name, ... are the names of the columns of a table whose values you want to retrieve.
If you want to retrieve all the columns in a table, use the following syntax:
SELECT * FROM table_name;
Demo Table
Let us suppose that we have a table named "Student" in our database that contains the following records:
student_id | name | age | city | dept_id |
---|---|---|---|---|
1 | John | 23 | Chicago | 3 |
2 | Mary | 22 | Boston | 4 |
3 | Wiliam | 21 | Los Angeles | 2 |
4 | Jennifer | 23 | Phoenix | 1 |
5 | Susan | 20 | Seattle | 2 |
Select All from a Table
The following SQL statement will fetch all the columns from the "Student" table:
SELECT * FROM student
The output of the above statement will look like the following:
+------------+----------+-----+-------------+---------+ | student_id | name | age | city | dept_id | +------------+----------+-----+-------------+---------+ | 1 | John | 23 | Chicago | 3 | | 2 | Mary | 22 | Boston | 4 | | 3 | Wiliam | 21 | Los Angeles | 2 | | 4 | Jennifer | 23 | Phoenix | 1 | | 5 | Susan | 20 | Seattle | 2 | +------------+----------+-----+-------------+---------+
Note: The asterisk
*
is a wildcard charter that represents everything. In the above example, the asterisk*
used with theSELECT
statement is a shorthand substitute for all the columns of the "Student" table.
Select Columns from a Table
SQL also gives the possibility to select data from specific columns. If you don't need all the data of a table, you can retrieve just what you need, like the following example:
SELECT student_id, name, city
FROM student
The above statement will output the following result set:
+------------+----------+-------------+ | student_id | name | city | +------------+----------+-------------+ | 1 | John | Chicago | | 2 | Mary | Boston | | 3 | Wiliam | Los Angeles | | 4 | Jennifer | Phoenix | | 5 | Susan | Seattle | +------------+----------+-------------+
The above output shows no "age", "dept_id" columns in the retrieved result set.