This module accompanies the Introduction to SQL DataCamp tutorial. Some content can also be found in Intermediate SQL.
SELECT *, field, field2 as ABC, `field b` as fieldb
DISTINCTFROM table
as t2 to create an aliasWHERE field = value
>, >=, <, <=, =, !="string value", “” (empty string), or NULLANDORORDER BY fieldname
ASC or DESCSELECT 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 sorts rows returned. It defaults to ascending, but you can manually force the order by adding ASC or DESC.
SELECT * FROM Employees ORDER BY FirstNameSELECT * FROM Employees ORDER BY FirstName DESC, LastName ASCDISTINCT includes only unique row results
SELECT DISTINCT name FROM employees 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.
SELECT * FROM employees WHERE name LIKE 'dark %'We can test for an empty string with ‘’ or “” (two single or double quotes side by side)
SELECT * FROM employees WHERE title = ''IN allows us to search for an item in a list.
SELECT * FROM employees WHERE id IN (1, 2, 3)BETWEEN can be used for two number comparisons.
SELECT * FROM employees WHERE id BETWEEN 10 and 30AND/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).
SELECT * FROM employees WHERE id IS NULLSELECT * FROM employees WHERE id IS NOT NULLThere are many online resources that can help you learn SQL.
Go to Excel.fun
Complete the following tutorials:
Go to SQLZoo
Complete the following tutorials: