SQL Lesson 9: Queries with Expressions
Learn to use mathematical expressions, string functions, and aliases to transform data in your queries.
SQL Lesson 9: Queries with Expressions
In addition to querying and referencing raw column data with SQL, you can also use expressionsto write more complex logic on column values in a query. These expressions can use mathematical and string functions along with basic arithmetic to transform values when the query is executed, as shown in this physics example.
Each database has its own supported set of mathematical, string, and date functions that can be used in a query, which you can find in their own respective docs.
The use of expressions can save time and extra post-processing of the result data, but can also make the query harder to read, so we recommend that when expressions are used in the SELECT part of the query, that they are also given a descriptive alias using the AS keyword.
In addition to expressions, regular columns and even tables can also have aliases to make them easier to reference in the output and as a part of simplifying more complex queries.
Common SQL Expressions:
- Arithmetic: +, -, *, / (e.g.,
price * 1.08for tax) - Mathematical: ABS(), ROUND(), SQRT(), etc.
- String: UPPER(), LOWER(), LENGTH(), SUBSTR()
- Modulo: % (e.g.,
year % 2 = 0for even years) - Aliases: AS keyword for readable column names
Exercise
You are going to have to use expressions to transform the BoxOffice data into something easier to understand for the tasks below.
Table: movies (Read-only)
Table: boxoffice (Read-only)
Query results
Exercise 9 — Tasks
- List all movies and their combined sales in millions of dollarsHint: They are currently saved in the database in dollars
- List all movies and their ratings in percent
- List all movies that were released on even number years
Solve all tasks to continue to the next lesson.