Your First Query: SELECT and FROM
Ask a table a question and read back the answer
SELECT (which columns do you want to see?) and FROM (which table should they come from?). Put them together and the database hands back a neat little table of answers.
- write a query with
SELECTandFROM, - pick every column with
*or just the columns you name, - end a statement correctly with a semicolon
;, - leave notes for humans using comments,
- read the result set the database gives back.
1. Our example database
Every example in this lesson uses one small table called students. You met tables, rows and columns in the last topic; here is the exact table we will keep asking questions about. It was built with these commands (you will learn to write them yourself later in the course):
CREATE TABLE students (
id INT,
name VARCHAR(50),
grade INT,
city VARCHAR(50)
);
INSERT INTO students (id, name, grade, city) VALUES
(1, 'Aisha', 5, 'Bishkek'),
(2, 'Bruno', 6, 'Osh'),
(3, 'Chen', 5, 'Bishkek'),
(4, 'Dilnoza', 7, 'Naryn');
So the students table now holds four rows:
| id | name | grade | city |
|---|---|---|---|
| 1 | Aisha | 5 | Bishkek |
| 2 | Bruno | 6 | Osh |
| 3 | Chen | 5 | Bishkek |
| 4 | Dilnoza | 7 | Naryn |
Four columns (id, name, grade, city) and four rows (one per student). Keep this picture in your head, because every query below is just a different way of asking to see parts of it.
2. The two magic words: SELECT and FROM
A basic query is like ordering at a canteen. You say what you want and where to get it from:
SELECT— the list of columns you want to see.FROM— the table those columns live in.
Here is the smallest useful query. It asks for the name column, taken from the students table:
SELECT name
FROM students;
Result:
| name |
|---|
| Aisha |
| Bruno |
| Chen |
| Dilnoza |
The database read the students table and gave back only the name column — but still all four rows. Notice something important: SELECT chooses the columns (which way to slice), not the rows. Choosing rows comes in the next topic with WHERE.
SELECT and FROM are usually written in UPPERCASE. SQL does not force this, but it makes queries far easier to read, so we always do it.
You can write a whole query on one line too — SQL ignores extra spaces and line breaks. SELECT name FROM students; means exactly the same thing.