← Вернуться к курсу: SQL and databases from scratch

Your first SELECT and week 1 review

Видео скоро появится

You now have the shop loaded. Now you will read real data. The most important SQL statement is SELECT, which reads data from one or more tables without changing them. Its minimal form is SELECT columns FROM table. First you choose which columns you want to see and then which table they come from. Think of it as a question: give me these columns from this table.

sql
-- Every column, every row
SELECT * FROM customers;

-- Only the columns we care about
SELECT name, city FROM customers;

The asterisk means all columns. It is handy for exploring, but in real queries it is better to name the columns you need: the result is clearer, less data travels and the query does not break if someone adds columns to the table. The order in which you write the columns is the order in which they appear. Rows, however, have no guaranteed order until you ask for one with ORDER BY, which we will see in week 2.

Aliases and calculations

In SELECT you can do operations with columns: add, subtract, multiply, divide. The result is a new calculated column that is not saved in any table; it exists only for the duration of the query. With AS you give it a readable name. Here we calculate the price with 21% VAT and the inventory value of each product.

sql
SELECT name,
       price,
       price * 1.21 AS price_with_vat,
       stock * price AS stock_value
FROM products;

-- Column aliases with spaces need double quotes
SELECT name AS "Product name", price AS "Unit price" FROM products;

Repeated values: DISTINCT

If you ask for the category of all products you will see repetitions, because several products share a category. DISTINCT removes duplicate rows from the result. It applies to the whole combination of columns you ask for: SELECT DISTINCT category, stock would only remove rows where both columns match at once. A common mistake is to believe DISTINCT applies only to the first column.

sql
SELECT category FROM products;

SELECT DISTINCT category FROM products;

SELECT COUNT(*) AS total_products FROM products;

Practice calmly: change the queries, break them on purpose and read the error message. Making a mistake with a read query costs nothing, because SELECT never modifies the data. That freedom is the best way to learn, and it is worth taking advantage of it before reaching the statements that do change the information.

A detail about logical order: although we write SELECT first, the engine understands FROM first (where from), then filters and groups, and at the end picks the columns. That is why, later on, you will not be able to use in a WHERE an alias created in the SELECT. Keep this in mind and you will avoid many errors.

Проверьте себя

Вопрос 1 из 6

What does SELECT * FROM customers do?

✎ Мои заметки

Сохранено только в этом браузере. Войдите, чтобы хранить в аккаунте.0/5000 символов

← НазадДалее →