You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
The SELECT statement is the workhorse of SQL. It's how you retrieve data from a database — and you'll use it in virtually every query you write.
SELECT column1, column2
FROM table_name;
Let's break it down:
SELECT — tells the database what columns you wantFROM — tells the database which table to look inUse * (asterisk) to select every column:
SELECT * FROM users;
Result:
id | name | email | created_at
---+----------------+---------------------+------------
1 | Alice Johnson | alice@example.com | 2024-01-15
2 | Bob Smith | bob@example.com | 2024-01-16
3 | Carol White | carol@example.com | 2024-01-17
...
Tip: In production, avoid
SELECT *— always specify the columns you need. It's faster and less fragile.
SELECT name, email FROM users;
Result:
name | email
---------------+---------------------
Alice Johnson | alice@example.com
Bob Smith | bob@example.com
Carol White | carol@example.com
You can rename columns in the output using AS:
SELECT
name AS customer_name,
email AS contact_email
FROM users;
Result:
customer_name | contact_email
---------------+---------------------
Alice Johnson | alice@example.com
Bob Smith | bob@example.com
Aliases are especially useful when column names are long, ambiguous, or when using calculated values.
SQL can do math inline:
SELECT
name,
price,
price * 1.1 AS price_with_tax
FROM products;
Result:
name | price | price_with_tax
--------------------+---------+---------------
Laptop Pro 15" | 1299.99 | 1429.989
Mechanical Keyboard | 89.99 | 98.989
USB-C Hub | 39.99 | 43.989
Combine text values (syntax varies by database):
-- SQLite / most databases
SELECT
id,
name || ' <' || email || '>' AS contact
FROM users;
-- PostgreSQL also supports ||
-- MySQL uses CONCAT()
Result:
id | contact
---+------------------------------------------
1 | Alice Johnson <alice@example.com>
2 | Bob Smith <bob@example.com>
Use DISTINCT to get unique values only:
SELECT DISTINCT category FROM products;
Result:
category
----------
Electronics
Office
Furniture
Without DISTINCT, if multiple products share a category, that category would appear multiple times.
Restrict how many rows are returned:
SELECT * FROM products LIMIT 3;
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.