SELECT statement forms a part of the Data Query Language (DQL) in SQL, which deals with fetching data.
Suppose you are putting on a science exhibition. To decide upon which exhibits (or projects) to put on display in the exhibition, you would first select a project and then put it for display.
Similarly, when you make a table in SQL, you would want to display the data in it at some point. The
SELECT statement does that for you. It selects the data by fetching it from the database and then displays it in a tabular form. This output retrieved in a tabular format is known as a result-set.
Syntax of the MySQL SELECT Statement
The syntax of the
SELECT statement is as follows:
SELECT expressions FROM table_names;
The expression can be catered to your needs, such that –
- If you want to retrieve all the columns of the table, use *.
- If you want to retrieve only a few columns, mention the column names separated by a comma.
How to Use the MySQL SELECT Statement?
Let us now explore a few examples of the
SELECT statement. We’ll consider the following ‘Students’ table.
1. Displaying All Columns
If you wish to display the Students table in the above format, you can do the following:
SELECT * FROM Students;
2. Displaying Particular Columns
If you wish to display only the
FirstName column from the Students table, you can do the following:
SELECT FirstName FROM Students;
The output will look like this:
Similarly, you can display multiple columns. If you want to output only the
DaysPresent columns from the Students table, we will select only those columns. It can be done as follows:
SELECT ID, DaysPresent FROM Students;
Your output will look like this:
As you can see, the query returns only the
ID and the
DaysPresent columns from the Student table in the result-set. If your dataset contains duplicate values and you wish to display only distinct values, you can use the DISTINCT clause.
SELECT statement is one of the most used and versatile statements in MySQL, and in the coming tutorials, we will see how we can use it for different operations.