Writing queries

Introduction to SQL

Jasmin Ludolf

Senior Data Science Content Developer, DataCamp

Aliasing

Use aliasing to rename columns

SELECT name AS first_name, year_hired
FROM employees;
| first_name | year_hired |
|------------|------------|
| Darius     | 2020       |
| Raven      | 2017       |
| Eduardo    | 2022       |
| Maggie     | 2021       |
| Amy        | 2020       |
| Meehir     | 2021       |
Introduction to SQL

Selecting distinct records

SELECT year_hired
FROM employees;
| year_hired |
|------------|
| 2020       |
| 2017       |
| 2022       |
| 2021       |
| 2020       |
| 2021       |
SELECT DISTINCT year_hired
FROM employees;
| year_hired |
|------------|
| 2020       |
| 2017       |
| 2022       |
| 2021       |
Introduction to SQL

DISTINCT with multiple fields

 

the employees table

SELECT dept_id, year_hired
FROM employees;
| dept_id | year_hired |
|---------|------------|
| 1       | 2020       |
| 2       | 2017       |
| 2       | 2022       |
| 3       | 2021       |
| 2       | 2020       |
| 3       | 2021       |
Introduction to SQL

DISTINCT with multiple fields

SELECT DISTINCT dept_id, year_hired
FROM employees;
| dept_id | year_hired |
|---------|------------|
| 1       | 2020       |
| 2       | 2017       |
| 2       | 2022       |
| 3       | 2021       |
| 2       | 2020       |
Introduction to SQL

Views

  • A view is a virtual table that is the result of a saved SQL SELECT statement
  • When accessed, views automatically update in response to updates in the underlying data

 

CREATE VIEW employee_hire_years AS
SELECT id, name, year_hired
FROM employees;
Introduction to SQL

Using views

SELECT id, name
FROM employee_hire_years;
| id    | name    |
|-------|---------|
| 54378 | Darius  |
| 94722 | Raven   |
| 45783 | Eduardo |
| 90123 | Maggie  |
| 67284 | Amy     |
| 26148 | Meehir  |
Introduction to SQL

Let's practice!

Introduction to SQL

Preparing Video For Download...