Skip to main content

VillageSQL is a drop-in replacement for MySQL with extensions.

All examples on this page work on VillageSQL. Install Now →
SELECT reads rows out of a table. This lesson covers its smallest useful form: name a table, name some columns, get rows back. Every example queries the Sakila database. If you have not loaded it yet, load Sakila first, then open the client with mysql -u root -p sakila so that sakila is the current database.

How SELECT works

COLUMN_LIST is what you want in each row, usually column names separated by commas. TABLE_NAME is the table the rows come from. A statement ends at the semicolon. The client keeps reading until it finds one, so a line without a semicolon leaves you on a continuation prompt:

Examples

1) Select one column

Ask the film table for the title of each film and nothing else.
One row comes back for every row in the table, 1,000 of them here. SELECT filters nothing on its own. Choosing which rows you get is the job of WHERE.

2) Select several columns

Separate the column names with commas. They come back in the order you asked for, which need not be the order they sit in the table.

3) Select every column

An asterisk stands for every column in the table. The language table holds 6 rows, so this one prints a complete result.
SELECT * earns its place while you are exploring a table you do not know. Inside application code, name your columns. An asterisk sends every column over the wire whether the code reads it or not, and it changes shape underneath the code on the day somebody adds a column.

4) Compute a value

The select list does not have to name a column. Put an expression there and the result becomes a column of its own.
The heading of that third column is the expression you typed, which is accurate and ugly. A column alias gives it a name of your own.

2 things that catch people out

Keywords ignore case. SELECT, select and SeLeCt all run.
This tutorial writes keywords in upper case and everything else in lower case, as a convention. It exists so the shape of a long query reads at a glance. A misspelled column raises an error. MySQL does not guess what you meant, and it does not hand back an empty result.
field list is the server’s name for the select list, so that message locates the mistake as well as naming it. The same error ends differently when the bad name sits elsewhere in the statement, so read the tail of it before you go looking.

Summary

  • Use SELECT with a list of columns and FROM with a table to read rows.
  • List columns in whatever order you want them returned.
  • Reach for SELECT * while exploring, and name your columns in application code.
  • Put an expression in the select list to compute a value per row.
  • Expect ERROR 1054 when a column name is wrong.

See also