Aliasing and arithmetic

Intermediate SQL

Jasmin Ludolf

Data Science Content Developer, DataCamp

Arithmetic

+, -, *, and /

SELECT (4 + 3);
|7|

 

SELECT (4 * 3);
|12|
SELECT (4 - 3);
|1|
SELECT (4 / 3);
|1|
Intermediate SQL

Arithmetic

SELECT (4 / 3);
|1|
SELECT (4.0 / 3.0);
|1.333...|
Intermediate SQL

Aggregate functions vs. arithmetic

Aggregate functions An example of a table of data with a red box around a single column, also known as field in SQL.

Arithmetic An example of a table of data with a red box around a single record, also known as row.

Intermediate SQL

Aliasing with arithmetic

SELECT (gross - budget)
FROM films;
|?column?|
|--------|
|null    |
|2900000 |
|null    |
...
SELECT (gross - budget) AS profit
FROM films;
|profit  |
|--------|
|null    |
|2900000 |
|null    |
...
Intermediate SQL

Aliasing with functions

SELECT MAX(budget), MAX(duration)
FROM films;
|max        |max|
|-----------|---|
|12215500000|334|
SELECT MAX(budget) AS max_budget,
       MAX(duration) AS max_duration
FROM films;
|max_budget |max_duration|
|-----------|------------|
|12215500000|334         |
Intermediate SQL

Order of execution

  • Step 1: FROM
  • Step 2: WHERE
  • Step 3: SELECT (aliases are defined here)
  • Step 4: LIMIT

 

  • Aliases defined in the SELECT clause cannot be used in the WHERE clause due to order of execution
SELECT budget AS max_budget
FROM films
WHERE max_budget IS NOT NULL;
column "max_budget" does not exist
LINE 5: WHERE max_budget IS NOT NULL;
              ^
Intermediate SQL

Let's practice!

Intermediate SQL

Preparing Video For Download...