SQL Basics
SELECT & FROM - The Foundational Words of SQL
Two essential words to every SQL query: SELECT and FROM. So a typical query looks like this:
[name] is an optional (indicated by []) temporary name for the table.
Let's break it down:
Example 1: Find the names and prices of all of our products
Example 2: Return all the rows in the Discount table
You can also specify more than one table in your FROM clause. But in order to do that, we will need to learn about the WHERE clause.
WHERE (AND, IN, OR, NOT, IS NULL)
Example 3: Look up the names of all members who joined in June or July
Example 4: Find all the orders that have a discount applied to them.
Return all the order_id that contain the "July Promo" code and are only from members.
You can use WHERE besides data filtering. You can use the WHERE clause to join two tables using Boolean expressions.
Return the name of all products ordered and when they were sold.
Our practice questions will not require you to do this but it's an important tool to keep in mind.
LIMIT, ORDER BY
LIMIT allows you to limit the number of rows displayed in your query.
ORDER BY allows you to order the query by specific column(s)
Example 5: Return the name of the first member who joined us!
Example 6: Sort the Order Table by prod_id and THEN sold_date in ascending order.
Return the prod_id of the last 10 orders.
Aggregates (COUNT, DISTINCT, SUM, AVG, MIN, MAX)
An aggregate in SQL is a function that performs a calculation on multiple values and returns a single output. There are many different aggregates that perform a variety of calculations. Here are some of the basic, but very important, aggregates:
Example 7: How many orders from non-members do we have?
Example 8: Find all the unique members who purchased a product on June 10th.
DISTINCT is a special aggregate because you can use it WITHIN another aggregate.
Example 9: Find the number of members who purchased AT LEAST one item in July
Example 10: Find the total revenue we made in July
Example 11: Return the prices of our cheapest and most expensive product
When the last time a member purchased an item from our store?
Subqueries - Creating Tables from Queries
Subqueries are essentially queries inside queries, temporary tables that we create using SQL queries. These can be very filtering tool.
Example 12: Find the names of all members who are have not purchased our UC Urvine Crop Top (aka Product ID 1)
Example 13: What were the most expensive item(s) our members purchased from our store?
Let's break down this query:
Name the first two members that purchased our Women's Biker Shorts (Product ID: 3).