Module lessons (2/4)
SELECT … FROM
The simplest query in SQL is called SELECT and extracts rows from a
table. It is the language's "Hello, world", and you will use it in nearly
every query you write for the rest of your life. The minimal syntax is:
SELECT <colonne>
FROM <tabella>;Read in English: "take these columns, from the given table". The SQL engine scans the table row by row and for each one returns only the requested columns.
All columns, or just some
SELECT *returns all the columns of the table. It is handy for exploring a new dataset, but in "real" code it is avoided: if tomorrow you add a column to the table, the query will silently return more data.SELECT col1, col2returns only the listed columns, in the order you write them. Changing the order changes the output.
-- Tutto, comodo per esplorare:
SELECT * FROM employees;
-- Solo le colonne che servono, nell'ordine deciso da te:
SELECT last_name, first_name, salary
FROM employees;Whitespace, indentation, semicolons
SQL is forgiving with formatting: these three queries are identical to the engine:
SELECT first_name, last_name FROM employees;
SELECT first_name,last_name FROM employees;
SELECT
first_name,
last_name
FROM employees;The third form is the one you will see most often in professional code: one column per line makes the diff more readable when you add or remove fields.
Try it
Extract the first name (first_name) and last name (last_name) of all employees, in that order.
Show hint
You need to list the two columns you want between SELECT and FROM, separated by a comma.
Solution available after 3 attempts
Review exercise
Extract email, last_name and salary of the employees (in this exact column order).
Show hint
The column order in the result follows the order in which you list them after SELECT.
Solution available after 3 attempts