Exploring The Database and Schema
Exploring The Database and Schema
Worked Exercises
SELECT *
FROM orders
SELECT *
FROM orders;
1. Write a query to recall all columns and the first 7 rows from orders table to
preview what the table looks like.
SELECT *
FROM orders
LIMIT 7;
A database table consists of rows and columns which are often called records
and fields.
We can reduce the number of records (rows) by using the LIMIT clause.
SELECT *
FROM orders
LIMIT 5;
We can reduce the number of fields (columns) by listing them in the SELECT
clause, separated by commas.
ALIAS or Rename
The headers of a table can be renamed if desired.
This task is possible by using SELECT Clause with AS
3. Write a query to pull the order_id, sales, and multiply sales by 5% to estimate
sales tax.
SELECT order_id
sales,
sales * 0.05 AS sales_tax
FROM orders;
4. Your manager has requested you find the profit margin on all orders from the
orders table.
a. Write a query that includes order_id, sales, profit, and profit margin
(profit divided by sales).
b. Alias the calculated fields as profit_margin.
c. Only display 5 rows.
SELECT order_id
sales,
profit,
profit/sales AS profit_margin
FROM orders
LIMIT 5;
ROUND ( )
ROUND () helps to round numerical values to a specified number of decimal
places.
Syntax:
ROUND (value, decimal_places)
SELECT order_id,
sales,
quantity,
Round (sales/quantity, 2) AS price_per_unit
FROM orders
LIMIT 8;
CONCATENATION
It is possible to concatenate, or combine, multiple fields together as one field.
Concatenate Operator (| |) is used to join two strings into one.
6. Every ErikomStores location is named after the city where it is located. For
example, store in Los Angeles, California is called “ErikomStore Los Angeles”.
a. Write a query that includes order_id, state, and region
b. Create a new column called local_store that concatenate the word
“ErikomStore” with city.
c. Limit your results in 4 rows.
SELECT order_id,
state,
region,
ErikomStore ||’, ‘|| city AS local_store
FROM orders
LIMIT 4;