SQL SELECT Statement

In the previous chapter we've learned how to insert data in a database table. Now it's time to select the data from existing tables using the SQL query.

The SELECT statement is used to select or retrieve the data from one or more tables. You can use this statement to retrieve all the rows from a table in one go, as well as to retrieve only those rows that satisfy a certain condition or a combination of conditions.

Syntax

The basic syntax for selecting the data from a table can be given with:

SELECT column1_name, column2_name, columnN_name FROM table_name;

Here, column1_name, column2_name, ... are the names of the columns or fields of a database table whose values you want to fetch. However, if you want to fetch the values of all the columns available in a table, you can just use the following syntax:

SELECT * FROM table_name;

Let's put these statements into real use. Suppose we've a table named employees in our database that contains the following records:

+--------+--------------+------------+--------+---------+
| emp_id | emp_name     | hire_date  | salary | dept_id |
+--------+--------------+------------+--------+---------+
|      1 | Ethan Hunt   | 2001-05-01 |   5000 |       4 |
|      2 | Tony Montana | 2002-07-15 |   6500 |       1 |
|      3 | Sarah Connor | 2005-10-18 |   8000 |       5 |
|      4 | Rick Deckard | 2007-01-03 |   7200 |       3 |
|      5 | Martin Blank | 2008-06-24 |   5600 |    NULL |
+--------+--------------+------------+--------+---------+