SQLSQL
BeginnerLesson 1 of 15

SELECT & FROM – Querying Data – SQL

Choosing columns, renaming, calculating, and removing duplicates.

A relational database stores data in tables made of rows (records) and columns (attributes). With SELECT you choose columns, with FROM the table. A semicolon ends the statement. Keywords are not case-sensitive; uppercase is customary.

SELECT * FROM kunden;                 -- all columns, all rows
SELECT name, stadt FROM kunden;       -- only certain columns
SELECT name AS kundenname FROM kunden; -- alias for the result column

In the column list you can compute expressions. You concatenate text with || (PostgreSQL, SQLite) or CONCAT() (MySQL, also works in PostgreSQL). Text literals go in single quotes; double quotes are reserved for identifiers.

SELECT name, preis, preis * 1.19 AS brutto FROM produkte;
SELECT 'Hello ' || name AS gruss FROM kunden;    -- MySQL: CONCAT('Hello ', name)
SELECT DISTINCT stadt FROM kunden;               -- remove duplicate values
SELECT DISTINCT kategorie FROM produkte;

A SELECT without FROM is allowed in PostgreSQL, MySQL, and SQLite (not in Oracle) and is handy for trying out expressions:

SELECT 1 + 1 AS summe, 'Hello' AS text, 7 % 3 AS rest;
WarningSELECT * is handy for exploring, but does not belong in production code: it loads unnecessary columns, prevents index-only scans, and breaks when the schema changes. Name the columns explicitly.
TipFormat SQL across multiple lines: one keyword per line (SELECT, FROM, WHERE …). This makes diffs and debugging much easier.