SELECT Statement
The SELECT statement is used to read data from a table. It is the most common command in SQL.
Syntax
SELECT column1, column2, ... FROM table_name;
To read all columns, you can use * (asterisk).
Examples
Read all data
SELECT * FROM employees;
Output:
id | name | age | department | gender
----+--------+-----+------------+--------
1 | Alice | 28 | HR | female
2 | Bob | 32 | IT | male
3 | John | 25 | Sales | male
4 | David | 30 | Marketing | male
5 | Emma | 26 | IT | female
6 | Frank | 27 | Sales | male
7 | Grace | 31 | Finance | female
8 | Henry | 29 | Sales | male
9 | Mike | 24 | IT | male
10 | Jack | 33 | Finance | male
11 | Sarah | 28 | IT | female
12 | Leo | 26 | Sales | male
13 | Lucy | 30 | Sales | female
14 | Steve | 27 | Finance | male
15 | Olivia | 25 | IT | female
16 | Paul | 32 | Finance | male
17 | Tina | 31 | Sales | female
18 | Ryan | 29 | Marketing | male
19 | Anna | 24 | HR | female
20 | Thomas | 33 | IT | male
(20 rows)
This is the employees table you will use in most of this course. It has 20 employees.
psql prints the column names at the top, then a line of dashes, then one line for each row. At the end, it tells you how many rows the query returned: (20 rows).
Read one column
SELECT age FROM employees;
This returns only the age column, for all 20 rows.
Read specific columns
SELECT name, department FROM employees;
This returns the name and department columns. The columns appear in the order you list them.
Tip
SQL keywords like SELECT and FROM are not case-sensitive. select * from employees; works too. In this course, keywords are written in capital letters, so they are easy to spot.
Every query ends with a semicolon ;. It tells PostgreSQL where the query ends.
Now that you know the basics of SELECT, try the problems below.