Your first SELECT
027 min
SELECT is the most used command in SQL. It reads data from the database and never changes it.
The pattern
SELECT columns FROM table;SELECT— what you want to see (columns);FROM— where it comes from (table);;— the command ends here.
All columns: *
The asterisk means “every column”. Handy for a quick look at what a table holds:
In real projects, be careful with
SELECT *: if a column is added to the table later, the result changes, and data you do not need gets loaded too. Naming the columns you need is a good habit.
Only the columns you need
Columns are separated by commas and come out in exactly the order you wrote them:
Case and spacing
SQL keywords can be written in any case: SELECT, select, Select — all the same. They are usually written in capitals so the query is easier to read.
A long query can be split over several lines — the database treats everything up to ; as one command:
Renaming a column: AS
You can change the heading of a column in the result. This is called an alias:
If an alias contains a space or special characters, put it in quotes:
In PostgreSQL use double quotes: AS "Student name". Single quotes ('…') are only for text values.
A calculated column
SELECT can contain expressions, not just columns. For example, teachers’ yearly salary:
From the subjects table, show the name (name) and number of credits (credits) of every subject.
From the teachers table, show the teachers’ last name (last_name) and position (position).
Remember
SELECT columns FROM table;is the basic pattern for reading data.*means every column, but at work it is better to name the ones you need.ASgives a column of the result a new name.