Selecting Columns
This is the command you will write more than all the others put together, and the only one in the course that changes nothing. A select asks a question and gets a resultset back; the table is exactly as it was afterwards.
1The syntax
select <col1>, <col2>, … from <table name>;
Two parts. select says which columns you want; from says which table to take them out of.
Every example in this chapter runs against the full students table — twelve rows, six columns:
2One column
One column came back, and still twelve rows. That is the point to hold on to: choosing columns does not reduce the number of rows. Every student is still represented; you are just looking at a narrower slice of each one.
3Several columns
Separate the names with commas:
select city, name from students; would put the city first. The table itself is unaffected either way.4All the columns, with *
You could name all six columns every time. It is exact, and it is tedious. * means every column:
With * the columns come out in the table's own order, because you have not given one.
select * is perfect while you are exploring a table. In a real query it is worth naming what you want: the resultset is narrower and easier to read, and it will not silently change shape if somebody adds a column to the table next month.5Two mistakes
A misspelt column name:
field list is MySQL's name for the part between select and from, so the error is telling you both what is wrong and where to look.
And a misspelt table name:
Two different error numbers for two different mistakes — 1054 for a column, 1146 for a table. Reading which one you got saves you looking in the wrong place.
6Recap
Those columns, in that order, for every row.
Every column, in the table's own order.
Choosing columns never changes how many rows come back.
select only reads. The table is the same afterwards.
A table has 12 rows and 6 columns. How many rows does select name from students; return?
What does * mean in select * from students;?
select nam from students; gives ERROR 1054: Unknown column 'nam' in 'field list'. What is wrong?