course_sql

SQL 2 - Getting the right data using SELECT

This module accompanies the Introduction to SQL DataCamp tutorial. Some content can also be found in Intermediate SQL.

Outcomes

Videos

Style guide

SELECT & FROM

SELECT and FROM are used in all data retrieval queries. - Example: SELECT * FROM employees

AS renames a field or table. - Example: SELECT CategoryID AS NewFieldNAme FROM employees AS NewTableName

Some fields or tables may have a space in their name. - Wrap fields with backticks. - Example: SELECT `Category Name` FROM t1 - Wrap tables with backticks - Example: SELECT * FROM `employees table` - Generally you will want to rename a field or table with AS to make it easier to use.

ORDER BY & DISTINCT

ORDER BY sorts rows returned. It defaults to ascending, but you can manually force the order by adding ASC or DESC.

DISTINCT includes only unique row results

WHERE

WHERE filters the returned fields. We use the pattern left side = right side, typically having field name in sql = some value - Example: SELECT * FROM employees WHERE id > 2

Strings are wrapped in single quotes. Avoid putting quotes around numbers. SQLite will try to convert between numbers and text automatically, but this can cause errors that are hard to debug. - Good Example: SELECT * FROM employees WHERE name = 'main' - Bad Example: SELECT * FROM employees WHERE id > '2'

LIKE allows using the % wildcard in a WHERE. You can also use a NOT LIKE. These are only used when comparing text values.

We can test for an empty string with ‘’ or “” (two single or double quotes side by side)

IN allows us to search for an item in a list.

BETWEEN can be used for two number comparisons.

AND/OR allow us to use multiple conditions

- Example: `SELECT * FROM employees WHERE id <= 2 OR id >= 4`
- Example: `SELECT * FROM employees WHERE id <= 2 AND id >= 4`

NULL is a special value, meaning that there is no result for a field. This is different from 0 (often the default in a number field), or “” (an empty string).

When testing for NULL, you can not write field_name = NULL. Each NULL is unique. You can only test for them by writing field_name IS NULL (or IS NOT NULL).

Optional Resources

There are many online resources that can help you learn SQL.

Excel.fun

Go to Excel.fun

Complete the following tutorials:

SQL Zoo

Go to SQLZoo

Complete the following tutorials:

Problems

Morgantown Docks GHCN