In this chapter, you will learn the fundamental building blocks of SQL: how to retrieve data from a database. We'll cover everything from simple data extraction to basic arithmetic and string operations.
The asterisk (*) is a wildcard that tells the database to return all columns from the specified table. While convenient, it's important to be cautious with SELECT * on large tables to avoid performance issues.
SELECT *
FROM customers
LIMIT 10;What to expect: You'll see the first 10 rows of the customers table, including columns like customer_id, customer_unique_id, customer_zip_code_prefix, customer_city, and customer_state.
In production environments, it's best practice to only request the data you actually need. This reduces network load and improves query performance.
SELECT
customer_city,
customer_state
FROM customers
LIMIT 10;You can rename columns in your output using the AS keyword. This is especially useful for making calculations more readable or for simplifying complex column names.
SELECT
customer_city AS city,
customer_state AS state
FROM customers
LIMIT 10;Let's take a quick look at the other tables in our dataset to understand their structure.
SELECT *
FROM orders
LIMIT 5;SELECT *
FROM products
LIMIT 5;SELECT *
FROM sellers
LIMIT 5;The COUNT(*) function allows you to quickly determine how many records are in a table.
SELECT COUNT(*) AS total_customers FROM customers; -- ~99,441 rows
SELECT COUNT(*) AS total_orders FROM orders; -- ~99,441 rows
SELECT COUNT(*) AS total_products FROM products; -- ~32,951 rows
SELECT COUNT(*) AS total_sellers FROM sellers; -- ~3,095 rowsSQL isn't just for fetching data; it can also perform arithmetic. You can calculate values on the fly within your SELECT statement.
SELECT
order_id,
price,
freight_value,
price + freight_value AS total_cost
FROM order_items
LIMIT 10;You can combine multiple string columns into one using the || operator (ANSI SQL standard).
SELECT
customer_city || ', ' || customer_state AS location
FROM customers
LIMIT 10;Try these on your own to reinforce what you've learned:
- Select the first 20 rows from the
order_paymentstable. What columns does it have? - Select only the
order_idandpayment_valuecolumns fromorder_payments. Limit to 15 rows. - Show
order_itemswith a column called "item_total" that isprice + freight_value. Show only 10 rows. - How many rows are in the
order_reviewstable? - Show
seller_cityandseller_statefrom thesellerstable, aliased as "city" and "state". Limit to 10 rows.
Solutions
-- Exercise 1
SELECT * FROM order_payments LIMIT 20;
-- Exercise 2
SELECT order_id, payment_value
FROM order_payments
LIMIT 15;
-- Exercise 3
SELECT
order_id,
price,
freight_value,
price + freight_value AS item_total
FROM order_items
LIMIT 10;
-- Exercise 4
SELECT COUNT(*) AS total_reviews FROM order_reviews;
-- Exercise 5
SELECT
seller_city AS city,
seller_state AS state
FROM sellers
LIMIT 10;