This module accompanies the Introduction to SQL Datacamp tutorial. Some content can also be found in Intermediate SQL.
SELECT and FROM are used in all data retrieval queries
SELECT * FROM categories
“Fields with a space in their name” must be wrapped by “double” quotes.
SELECT “Category Name” FROM “categories tables”
AS renames a field or table
SELECT CategoryID AS “Primary Key” FROM categories AS c1
WHERE filters the returned fields
SELECT * FROM categories WHERE CategoryID > 2
‘Strings’ are wrapped in single quotes (don’t wrap numbers)
SELECT * FROM categories WHERE CategoryName = ‘main’
AND/OR allow us to use multiple conditions
SELECT * FROM categories WHERE CategoryID <= 2 OR CategoryID >= 4
LIKE allows using the % wildcard in a WHERE. You can also use a NOT LIKE.
SELECT * FROM CategoryName WHERE CategoryName LIKE ‘E%d’
IN allows us to search for an item in a list.
SELECT * FROM CategoryName WHERE ID IN (1, 2, 3)
BETWEEN can be used for two number comparisons.
SELECT * FROM CategoryName WHERE CategoryID BETWEEN 10 and 30
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 CategoryName WHERE field_name IS NULL
ORDER BY sorts rows returned (either ASCending / DESCending)
SELECT * FROM Employees ORDER BY FirstName DESC, LastName ASC
DISTINCT includes only unique row results
SELECT DISTINCT CategoryName FROM Categories
Using SQL SELECT allows you to retrieve data from a database. The SELECT statement is one of the fundamental and most commonly used SQL commands. Here’s a step-by-step explanation of how to use SQL SELECT:
SELECT column1, column2, … FROM table_name WHERE conditions ORDER BY column1, …;
Columns to retrieve: Specify the columns you want to retrieve
data from after the SELECT keyword. You can list multiple column names
separated by commas, or use *
to select all
columns.
Table to retrieve data from: After the FROM keyword, specify the name of the table from which you want to retrieve the data.
Filtering (Optional): You can use the WHERE clause to add conditions to filter the data. This allows you to retrieve only the rows that meet specific criteria. For example:
SELECT column1, column2 FROM table_name WHERE condition;
SELECT column1, column2 FROM table_name WHERE condition ORDER BY column1;
Examples: - To retrieve all columns from a table named “employees”:
SELECT * FROM employees;
SELECT name, age FROM employees;
SELECT name, salary FROM employees WHERE salary > 50000;
Remember to use semicolons to terminate your SQL statements, as it is a common convention in SQL to signify the end of a command.
There 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: