Informatics Practices · Ch 7 — Introduction to Structured Query Language (SQL)
SELECT Statement
SELECT Statement
Creating tables and filling them with records is only half the story — the real power of a database shows when you start asking it questions. The SELECT statement is SQL's instrument for retrieving data from the tables of a database, and whatever it retrieves is displayed back in tabular form, as rows and columns, just like the data itself is stored.
The general form of the statement is:
SELECT attribute1, attribute2, ...
FROM table_name
WHERE condition;
Each part has a definite job:
- The SELECT clause lists the attributes (column names) whose values you want to see —
attribute1, attribute2, ...are columns of the table being queried. - The FROM clause names the table from which the data is to be retrieved. It is always written along with the SELECT clause; a SELECT never appears without a FROM telling it where to look.
- The WHERE clause is optional. When present, it states a condition, and only the rows that satisfy that condition are retrieved.
A useful way to read any query: WHERE decides which rows qualify, and the column list after SELECT decides which columns of those rows are shown.
Consider retrieving just the name and date of birth of one particular student from the STUDENT table — the student is pinned down by roll number, and only two columns are asked for:
SELECT SName, SDateofBirth
FROM STUDENT
WHERE RollNumber = 1;
MySQL responds with a small result table containing exactly what was requested:
+--------------+--------------+
| SName | SDateofBirth |
+--------------+--------------+
| Atharv Ahuja | 2003-05-15 |
+--------------+--------------+
1 row in set (0.03 sec)
``` …