Chuyển đến nội dung chính
eLearner.app
Mô-đun 1 · Bài học 2 trong tổng số 42/57 trong khóa học~10 min
Bài học theo mô-đun (2/4)

CHỌN … TỪ

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:

SQL
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, col2 returns only the listed columns, in the order you write them. Changing the order changes the output.
SQL
-- 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:

SQL
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

tập thể dục#sql.m1.l2.e1
Nỗ lực: 0Đang tải…

Extract the first name (first_name) and last name (last_name) of all employees, in that order.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

You need to list the two columns you want between SELECT and FROM, separated by a comma.

Giải pháp khả dụng sau 3 lần thử

Review exercise

tập thể dục#sql.m1.l2.e2
Nỗ lực: 0Đang tải…

Extract email, last_name and salary of the employees (in this exact column order).

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

The column order in the result follows the order in which you list them after SELECT.

Giải pháp khả dụng sau 3 lần thử