…
…
SQL and Database Fundamentals · Lesson 3 / 41 · SELECT and filtering
PreviewIn this lesson you will
You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
The student affairs manager has to send the president's office a student list: student number, first and last name in one column, year, and the GPA on a 100-point scale. The list will be printed on paper, so the column headings have to be readable too.
In the previous two lessons you wrote your first queries and got to know the seven tables of the case database. You used SELECT * to see all the columns of a table. In real work, nobody says "give me every column". The manager wants a list with five columns, and two of them do not exist in any table: "Full Name" is a combination of two columns, and the 100-point score is the result of a calculation. In this lesson you will learn how to pick columns from a table, how to build new columns from them, and how to name the result columns. When the lesson ends, the manager's list will look like this:
| number | full_name | year | gpa_100 |
|---|---|---|---|
| 202303001 | Anika Park | 4 | 91.25 |
| 202405001 | Anika Rivera | 3 | 97 |
| 202604001 | Felix Abara | 1 | NULL |
(3 of 120 rows)
In this lesson you will:
A SELECT query has two basic parts: the column list after SELECT and the table after FROM. The column list decides two things: which columns appear in the result and in which order they appear. You do not have to follow the order of the table. Even if first_name comes before last_name in the table, you can ask for the last name first. You separate the column names with commas; there is no comma after the last column.
Example 1: Selected columns, in the order you asked for. Student number, last name, first name, and year:
SELECT student_no, last_name, first_name, year FROM student;
| student_no | last_name | first_name | year |
|---|---|---|---|
| 202303001 | Park | Anika | 4 |
| 202405001 | Rivera | Anika | 3 |
| 202604001 | Abara | Felix | 1 |
| 202304001 | Popescu | Isabella | 4 |
| 202506001 | Ortiz | Felix | 2 |
(5 of 120 rows)
The student table has thirteen columns; the result has only the four you asked for, in the order you wrote them. The number of rows did not change: all 120 students came back, and you simply took fewer columns from each row. Choosing rows is the topic of the next lesson.
SELECT * is handy for a quick look, but when you write a report it is better to list the columns one by one. There are three reasons. First, unneeded columns make the result crowded; the manager cannot find what they are looking for in a list with thirteen columns. Second, moving unneeded data around slows down a query on large tables. Third, if a new column is added to the table later, a report that uses * suddenly starts to look different; the columns you named stay where they are.
What is the heading of the first column in the result of this query?
SELECT last_name, first_name FROM student;
By default, the heading of a result column is the name of the column in the table: student_no. Names with underscores and no spaces work well in a database, but they are hard to read on a printed list. You give a result column the name you want with AS: SELECT student_no AS number FROM student;. Doing this is called giving an alias.
An alias only changes the heading in the result. The column in the table is still called student_no; in the next query you write student_no again. The word AS is optional: student_no number does the same job. Still, writing AS is a good habit; whoever reads the query sees right away that a name is being given there, and you avoid creating an alias by accident when you forget a comma between two columns.
An alias has one more rule. If the name contains only lowercase letters, digits, and underscores, you do not need quotes: AS number, AS full_name. If the name has a space or capital letters, you put it in double quotes: AS "Full Name", AS "Student No". PostgreSQL turns names written without quotes into lowercase; if you write AS Number, the heading becomes number.
Example 2: Aliases.
SELECT student_no AS number, first_name || ' ' || last_name AS "Full Name" FROM student;
| number | Full Name |
|---|---|
| 202303001 | Anika Park |
| 202405001 | Anika Rivera |
| 202604001 | Felix Abara |
(3 of 120 rows)
We will get to the || operator in the second column in a moment; for now, look at the headings. student_no shows up as number in the result, and the second column has the heading Full Name, with a space and capital letters. A query is ready in the cell below. Run it as it is first, then try the two tasks:
1. Give the first_name column the name given_name.
2. Make the heading of the last_name column Last Name. The heading has a space and capital letters: which quotes do you need?
Try it now· not graded; doesn't affect progress
SQL has two kinds of quotes, and they do different jobs. Single quotes are for text values: 'Anika', ' '. Double quotes are for names: columns, tables, and aliases. In everyday writing the two kinds of quotes are interchangeable, so this rule is confusing at first.
What happens when this query runs?
SELECT first_name AS 'Student name' FROM student;
The words at or near in the error message show where the problem is: right next to the single-quoted part. Keep this pattern in mind; you will go through reading SQL error messages in detail in lesson 9.
You can write not only existing columns but also expressions in the SELECT list. An expression is a calculation built from columns and numbers with the four operators: addition (+), subtraction (-), multiplication (*), and division (/). The database calculates the expression separately for every row and shows the result in a new column. This is called a calculated column. In lesson 1, SELECT 2026 - 1970 in the date box was an expression too; now the expression will contain columns instead of fixed numbers.
The case has a clear use for this. At the university, a course grade is 40% of the midterm plus 60% of the final exam. The enrollment table has midterm and final_exam columns but no course grade column; it is calculated each time.
Example 3: Weighted course grade.
SELECT student_id, midterm, final_exam, 0.4 * midterm + 0.6 * final_exam AS course_grade FROM enrollment;
| student_id | midterm | final_exam | course_grade |
|---|---|---|---|
| 1 | 96 | 73 | 82.2 |
| 1 | 90 | 87 | 88.2 |
| 1 | 72 | NULL | NULL |
(3 of 781 rows)
In each row the two products were calculated separately and added: 0.4 × 96 = 38.4 and 0.6 × 73 = 43.8; the total is 82.2. In the third row the final exam is empty (NULL). The final exams of this term have not been entered yet, and every calculation with NULL gives NULL: 60% of an unknown number is also unknown. You will see how NULL spreads through a calculation in detail in lesson 7.
Operator precedence. SQL follows the rule from math: multiplication and division are done before addition and subtraction. In the expression 0.4 * midterm + 0.6 * final_exam, the two products were done first and then the addition, which is what we wanted. But you will not always be this lucky. Imagine you want the plain average of the midterm and the final: you add the two grades and take half. If you write midterm + final_exam * 0.5, final_exam * 0.5 is calculated first and then the midterm is added. If you want a different order, you use parentheses: (midterm + final_exam) * 0.5 adds first and then takes half.
Example 4: With and without parentheses.
SELECT midterm, final_exam, midterm + final_exam * 0.5 AS wrong, (midterm + final_exam) * 0.5 AS correct FROM enrollment;
| midterm | final_exam | wrong | correct |
|---|---|---|---|
| 96 | 73 | 132.5 | 84.5 |
| 90 | 87 | 133.5 | 88.5 |
(2 of 781 rows)
132.5 cannot be a grade; it is over 100. The expression without parentheses calculated 96 + 36.5. The expression with parentheses gave (96 + 73) × 0.5 = 84.5. The query ran without an error in both cases. The database does not know what you meant; it only calculates what you wrote. That is why it is a good habit to look at the first few values of a calculated column and ask: "does this number make sense?"
For a record with midterm = 80 and final_exam = 60, which result does each expression give?
For each row, pick its match from the list, then check.
0.4 * midterm + 0.6 * final_exammidterm + final_exam * 0.5(midterm + final_exam) * 0.5final_exam - midtermmidterm * 2Example 3 is ready in the cell below. Run it, then try these:
1. Change the weights to 30% midterm, 70% final.
2. Change the name of the column to average_grade.
3. Find a row where the final exam is NULL: what do you see in the course grade?
Try it now· not graded; doesn't affect progress
The most important thing to know about calculated columns is this: the table does not change. When you write 0.4 * midterm + 0.6 * final_exam, no new column is added to the enrollment table and no value is updated. The calculation is done again every time the query runs, and the result only appears on the screen. If you close the cell and write SELECT * FROM enrollment;, you will not find a column called course_grade.
This is not a shortcoming, it is a convenience. You can produce as many different reports as you want from the same data. The GPA is stored in the table on a 4-point scale; the manager wants the 100-point equivalent. Since a GPA of 4.00 corresponds to 100, multiplying every GPA by 25 is enough. You can show the 4-point GPA in one query and the 100-point GPA in another; the value in the table stays the same in both.
Example 5: The president's office list. Now you have all the parts of the list the manager asked for:
SELECT student_no AS number, first_name || ' ' || last_name AS full_name, year, gpa * 25 AS gpa_100 FROM student;
| number | full_name | year | gpa_100 |
|---|---|---|---|
| 202303001 | Anika Park | 4 | 91.25 |
| 202405001 | Anika Rivera | 3 | 97 |
| 202604001 | Felix Abara | 1 | NULL |
(3 of 120 rows)
Anika Park's GPA is 3.65; 3.65 × 25 = 91.25. Felix Abara is in year 1 and has no grades yet, so both his GPA and its 100-point equivalent are NULL. We did not give year an alias, because its name is already readable. An alias is not required for every column; you give one when the heading is unclear or when the column is calculated.
Put the lines of the query in order: it builds the president's office list with the number, Full Name, and 100-point score.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
In Example 2 and Example 5 we wrote first_name || ' ' || last_name. The two vertical bars (||) put texts next to each other; this is called text concatenation. The ' ' in the middle is a text made of a single space, written inside single quotes. Concatenation lines up the parts in the order you write them and puts nothing in between on its own; if you want a space, a comma, or a parenthesis, you write it as a part too, in single quotes.
What is the column heading in the result of this query, and what appears in Anika Park's row?
SELECT first_name || last_name FROM student;
The ?column? heading is something you will often see with calculated columns. When you take a column from a table as it is, the heading is the name of the column; when you write an expression, PostgreSQL has no name it can use. In a one-column result this may look unimportant, but if three calculated columns arrive side by side with the heading ?column?, nobody can tell which is which. The rule is simple: give every calculated column a name.
Example 6: Course label. For the course catalog: the code and name of each course, the difference between ECTS and credits, and a label in the "Name (Code)" format:
SELECT code, name, ects - credits AS diff, name || ' (' || code || ')' AS label FROM course;
| code | name | diff | label |
|---|---|---|---|
| CPR101 | Algorithms and Programming I | 2 | Algorithms and Programming I (CPR101) |
| CPR102 | Algorithms and Programming II | 2 | Algorithms and Programming II (CPR102) |
(2 of 33 rows)
The label was made of four parts: the course name, ' (' (a space and an opening parenthesis), the code, and ')'. A number calculation and a text concatenation can sit side by side in the same query. This query is ready in the cell below. Run it, then try two tasks:
1. Change the label to the format CPR101 - Algorithms and Programming I: first the code, then a hyphen with spaces, then the name.
2. Rewrite the query for the instructor table: from the title, first_name, and last_name columns, build a single column called instructor_name in the format Associate Professor Diego Costa.
Try it now· not graded; doesn't affect progress
There is more you can do with text: change it to uppercase, take a part of it, trim spaces. You will see these in lesson 26 with the text functions.
The same rules apply in every table. A small café's menu table has five items: the item name (item), the selling price (price, in $), and what the item costs the café (cost, in $). The café owner wants to see how much profit each item makes and what the new prices would be if she raised prices by 10%. Profit is the cost subtracted from the price; the price with a 10% increase is 1.1 times the price.
Example 7: Profit and raised price.
SELECT item, price, cost, price - cost AS profit, price * 1.1 AS raised FROM menu;
| item | price | cost | profit | raised |
|---|---|---|---|---|
| Tea | 1.25 | 0.30 | 0.95 | 1.375 |
| Espresso | 3.00 | 0.90 | 2.10 | 3.300 |
| Latte | 4.25 | 1.60 | 2.65 | 4.675 |
| Cookie | 2.00 | 0.75 | 1.25 | 2.200 |
| Toastie | 4.75 | 2.25 | 2.50 | 5.225 |
(5 rows)
The most profitable item is the Latte: $2.65 of its $4.25 price is profit. The toastie has a higher price, but its cost is also higher, so its profit is $2.50. The raised price column was not written into the table; if the owner decides to raise prices, updating the prices in the table is a separate job, and you will learn it in lesson 35.
The Latte's price is 4.25 and its cost is 1.60. What does this expression give for the Latte?
SELECT price - cost * 2 FROM menu;
A calculated column does not know the rules of the table. Each student's year for next year:
SELECT first_name, last_name, year, year + 1 AS next_year FROM student;
| first_name | last_name | year | next_year |
|---|---|---|---|
| Anika | Park | 4 | 5 |
| Anika | Rivera | 3 | 4 |
| Felix | Abara | 1 | 2 |
(3 of 120 rows)
In the table, the year has to be between 1 and 4, but because the calculated column is not written into the table, this rule does not apply to it: it came out as 5 for Anika Park. Yet there is no year 5 for a student in year 4; graduation comes next. You will learn to label numbers by condition ("graduated", "continuing") with CASE in lesson 8.
In a music app's artist table, the artist's name and genre are in separate columns. The app's screen will show a single line in the "Name · genre" format:
Writing the alias with single quotes. For a column with the heading "Student name", this is written:
OutputSELECT first_name AS 'Student name' FROM student;
ERROR: syntax error at or near "'Student name'"In SQL, single quotes are for text values; after AS a name is expected. The correct form is AS "Student name": names are written with double quotes. If there is no space or capital letter, you do not need quotes at all: AS student_name. The opposite is a mistake too: if you write the space in a concatenation with double quotes (first_name || " " || last_name), PostgreSQL looks for a column named " " and cannot find it.
*.AS gives a result column an alias and does not change its name in the table; names with spaces or capital letters go in double quotes, text values in single quotes.+ - * / and a joined text with ||; multiplication and division come first, parentheses change the order, the table does not change, and an unnamed column becomes ?column?.Next lesson: You have selected columns; with WHERE you will select only the rows you want.
Exercises and quiz are for members
This lesson has 7 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
SELECT name, genre, name || ' · ' || genre AS label FROM artist;
| name | genre | label |
|---|---|---|
| Salt Pier | pop | Salt Pier · pop |
| Prairie Strings | folk | Prairie Strings · folk |
| Broken Compass | rock | Broken Compass · rock |
(3 of 8 rows)
The separator ' · ' is a single piece of text: a space, a dot, and a space again. You can write any separator you like; the only rule is to put it inside single quotes.