0% found this document useful (0 votes)
2 views

Baonhh-SQL

The document provides a comprehensive guide on databases and SQL, including definitions, installation instructions for MySQL on both Mac and Windows, and detailed SQL query examples. It covers various SQL commands such as SELECT, WHERE, IN, BETWEEN, and aggregate functions, along with quizzes to test understanding. The content is structured to facilitate learning for users interested in database management and SQL programming.

Uploaded by

Thắng Quang
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Baonhh-SQL

The document provides a comprehensive guide on databases and SQL, including definitions, installation instructions for MySQL on both Mac and Windows, and detailed SQL query examples. It covers various SQL commands such as SELECT, WHERE, IN, BETWEEN, and aggregate functions, along with quizzes to test understanding. The content is structured to facilitate learning for users interested in database management and SQL programming.

Uploaded by

Thắng Quang
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

Toward Data Science

Database - SQL

Year 2023
Outline
Ø What is a Database?
Ø Installing MySQL
Ø Create Databases
Ø SQL Queries – Single table Queries
Ø Quizzes
What is a Database?

Year 2023
Definition
A collection of information/data.

Stored and organized is some format.


Phone book
Friend Graph
Easily accessed, managed and retrieved

Databases
Shopping list Relation database
Database Management System

A software or application that allow user to interact with the database.

DBMS
User Database
Instructions Execute
Non
Relational
Relational
Result Result
Relational Databases

Customers

Products

Orders
Installing MySQL

Year 2023
Installing MySQL on MAC
Step 1: Go to mysql.com.

Step 2: Click on the DOWNLOADS tab


Step 4: Click on MySQL Community
Step 3: Scroll to the bottom of the pages Server and Download the first link
and click
Installing MySQL on MAC
Step 5: Open the download file. Step 6: Re-open the download
file and follow the steps below

2
Step 5-1: If mac security prevent
opening the file, go to System Settings 1
3

Step 5-2: On Privacy & Security tab,


check on these boxex
5 4
2
Create your password
1 for the “root” user

3 6
Installing MySQL on MAC
Step 9: Click on MySQL Workbench
and Download the first link

Step 7: Go back to the Download Page

Step 8: Scroll to the bottom of the pages


and click

Step 10: Open the


downloaded file and
drag to Applications.
Then open the app.
Installing MySQL on Windows
Step 1: Go to mysql.com.
Step 4: Click on MySQL Community Server and
Go to Download Page from the recommended
Step 2: Click on the DOWNLOADS tab download section

Step 3: Scroll to the bottom of the pages


and click

Step 5: Download the first link


Installing MySQL on Windows
Step 5: Open the download file
and follow the steps bellow. 3
Create your password
for the “root” user

2
Installing MySQL on Windows
Step 6: Continue clicking on
Next/Execute with default setup

Enter your password you set


earlier for the “root” user

5
9

6 7
Create Databases

Year 2023
Create Databases
Open MySQL Workbench 1

If you don’t see any connection, click Enter your password you set
on the (+) button to create new one earlier for the “root” user
4
3

You should see the default connection


Click and enter your
password to access the server
Create Databases
Tools Bar

Navigation panels

Queries editor window


User
Interface
Create Databases
Download the pre-created 1
database script here

Click to open the


downloaded script

3
Create Databases
Click the thunder icon to
execute and create our
databases
NOTE: This button can be
used to execute SELECTED
SQL code. To execute ALL
code, UNSELECT everything

Go to Schemas tab on the


Navigation panels and
click the refresh icon to
see the created schemas
Explore the data
Go to Schemas tab on the
Navigation panel, select any
schemas and table and click
on this icon to view the data.
SQL Queries

SELECT

Year 2023
SELECT
1/ Select all data from a table 2/ Select specific colums
SELECT * FROM <schema>.<table>; SELECT <column>,<column>,<...>
FROM <table>;
SELECT * FROM sql_store.orders;
SELECT first_name, last_name
NOTE: You can use the keyword USE to FROM customers;
specify the schema you want to query from
beforehand
USE sql_store;
SELECT * FROM orders;
SELECT
3/ Select with modify values 4/ Select with Alias
SELECT SELECT <column> AS <alias>
points, FROM <table>;
points + 10,
points / 10 SELECT
FROM customers; points,
points * 110 / 100,
points * 110 / 100 AS VAT
FROM customers;
SELECT
5/ Select unique values of a column 6/ Select all the products:
SELECT state
- Name
FROM customers; - Unit price
- New price (Unit price * 1.1)
SELECT
name,
unit_price,
unit_price * 1.1 AS new_price
FROM products;
SELECT DISTINCT state
FROM customers;
SQL Queries

WHERE

Year 2023
WHERE
1/ Select data with condition 3/ Select every customer from state ‘VA’
SELECT <column> SELECT *
FROM <table> FROM customers
WHERE <condition>; WHERE state = ‘VA’;

SELECT *
FROM customers
WHERE points > 3000;
4/ Select every customer not from state
‘VA’
SELECT *
FROM customers
WHERE state != ‘VA’;

2/ Comparison Operators
<, >, <=, >=, =, !=, <>
WHERE
5/ Get the orders placed after 2018 6/ The AND, OR, and NOT Operators
SELECT *
FROM orders
WHERE order_date >= ‘2018-01-01’;

7/ From order_items table, get order_id


#6 and total price is less than 30
SELECT *, unit_price * quantity AS total_price
FROM order_items NOT ‘<‘ is ‘>=‘
WHERE NOT ‘>’ is ‘<=‘
order_id = 6 AND unit_price * quantity < 30; NOT ‘AND’ is ‘OR’
NOT ‘OR’ is ‘AND’
NOT ‘=’ is ‘!=‘
NOT ‘<>’ is ‘=‘
SQL Queries

IN - BETWEEN

Year 2023
IN - BETWEEN
1/ Select all customer from state (use OR): 2/ Select all customer from state (use IN):
VA, GA, FL VA, GA, FL

SELECT * SELECT *
FROM customers FROM customers
WHERE WHERE
state = ‘VA’ OR state = ‘GA’ OR state = ‘FL’; state IN (‘VA’, ‘GA’, ‘FL’);
IN - BETWEEN
3/ Select all customer from state VA, GA, FL 4/ Select all customer from state VA, GA, FL
points greater than 300 but less than 2000 points BETWEEN 300 - 2000

SELECT * FROM customers


SELECT * FROM customers
WHERE
WHERE
state IN ('VA', 'GA', 'FL')
state IN ('VA', 'GA', 'FL')
AND points > 300
AND points BETWEEN 300 AND 2000;
AND points < 2000;
SQL Queries

IS NULL - ORDER BY - LIMIT

Year 2023
IS NULL - ORDER BY - LIMIT
1/ Select all customer don’t have a phone 2/ Select all customer who have a phone
number number

SELECT * SELECT *
FROM customers FROM customers
WHERE phone IS NULL; WHERE phone IS NOT NULL;
IS NULL - ORDER BY - LIMIT
3/ Order the customer by points in 4/ Get the customer have points < 1000 and
ascending order order them in descending order by points

SELECT * FROM customers


SELECT * FROM customers
WHERE points < 1000
ORDER BY points;
ORDER BY points DESC;
IS NULL - ORDER BY - LIMIT
5/ Get three customer with the highest 6/ Get four customer with the highest points
points (not including the first 3)
SELECT * FROM customers SELECT * FROM customers
ORDER BY points DESC ORDER BY points DESC
LIMIT 3; LIMIT 3, 4;
SQL Queries

LIKE - REGEXP

Year 2023
LIKE
1/ Select all customer whose last name 2/ Select all customer who have a ‘b’ in
start with ‘B’ their last name

SELECT * SELECT *
FROM customers FROM customers
WHERE last_name LIKE ‘B%’; WHERE last_name LIKE ‘%B%’;

NOTE: ‘%’ is used to represent any number


of characters
LIKE
3/ Select all customers whose last name is 4/ Get the customer whose
6 letters long and end with ‘y’ -- addresses contain ‘TRAIL’ or ‘AVENUE’
-- phone numbers end with 9---
SELECT *
SELECT *
FROM customers
FROM customers
WHERE last_name LIKE ‘_____y’;
WHERE
address LIKE ‘%trail%’ OR
address LIKE ‘%avenue%’;

NOTE: ‘_’ is used to represent one characters SELECT *


FROM customers
WHERE phone LIKE ‘%9___’;
REGEXP
1/ Get the customer whose first name are 2/ Get the customer whose last name end
ELKA or AMBUR with EY or ON

SELECT * SELECT *
FROM customers FROM customers
WHERE first_name REGEXP ‘ELKA | AMBUR’; WHERE last_name REGEXP ‘EY$|ON$’;

NOTE: ‘|’ is used to represent alternation.


NOTE: ‘$’ is used to match the end of a string.
‘|’ = OR
REGEXP
3/ Get the customer whose last name start 4/ Get the customer whose last name
with MY or contains SE contain B followed by R or U

SELECT * SELECT *
FROM customers FROM customers
WHERE last_name REGEXP ‘^MY|SE’; WHERE last_name REGEXP ‘B[RU]’;

NOTE: ‘^’ is used to match the beginning of a string. NOTE: ‘[]’ is used to match any characters in it.
REGEXP

REGEX
basic
syntaxs
SQL Queries

AGGREGATE FUNCTIONS - OVER

Year 2023
AGGREGATE FUNCTIONS - OVER
1/ Calculate the average points of all 2/ Find out the total quantity of every
customers products in stock

SELECT AVG(points) AS average_point SELECT SUM(quantity_in_stock) AS total_quantity


FROM customers; FROM products;

NOTE: Aggregate functions take in and What if we want to aggregate only on some
apply on all value of the selected column. specifics group??
AGGREGATE FUNCTIONS - OVER
3/ Calculate the average points of all 4/ Calculate the cumulative sum points of
customers by state. all customers by state

SELECT state, AVG(points) SELECT points, state, SUM(points)


OVER(PARTITION BY state) OVER(PARTITION BY state
AS average_state_point ORDER BY points)
FROM customers; AS average_state_point
FROM customers;

NOTE: OVER dictate the window which the


aggregate function will act on
AGGREGATE FUNCTIONS
AGGREGATE FUNCTIONS
SQL Queries

GROUP BY- HAVING

Year 2023
GROUP BY- HAVING
1/ Calculate the average points of all 2/ Select the state that have total points of
customers by state. all customers in that state > 3000.

SELECT state, AVG(points) AS average_state_point SELECT state, SUM(points) AS total_state_point


FROM customers FROM customers
GROUP BY state; GROUP BY state
HAVING total_state_point > 3000;

NOTE: GROUP BY reduce the number of NOTE: HAVING is WHERE but act on the
row into one representing that group aggregated group values
SQL Queries

QUIZZES

Year 2023
QUIZZES
Use the learned SQL functions to solve these SQL questions below.
1/ Retrieve the first name and last name of customers whose points are greater than 1000.
2/ Retrieve the product name and unit price of products with a quantity in stock between 50 and 100.
3/ Retrieve the order ID and order date of orders placed between ‘2018-01-01' and ‘2018-12-31’.
4/ Retrieve the first name and last name of customers whose phone number is null.
5/ Retrieve the customer ID and points of customers whose first name starts with ‘I’.
6/ Retrieve the order ID and order date of the latest 5 orders, ordered by order date in descending
order.
7/ Retrieve the product name and unit price of the top 3 most expensive products.
8/ Retrieve the first name and last name of customers whose birth year is a leap year.
9/ Retrieve the customer ID and the count of orders placed by each customer, ordered by the count in
descending order.
10/ Retrieve the product name and quantity in stock of products whose quantity is a multiple of 10.
11/ Retrieve the product name and unit price of products that have a name starting with a vowel
(AIUEO).
12/ Retrieve the customer ID and the total points for customers whose points are above the average
points.
13/ Retrieve the order ID and order date of the 5th to 10th orders, ordered by order date.
QUIZZES
Use the learned SQL functions to solve these SQL questions below.
14/ Retrieve the customer ID and the total points for customers born in the same month, ordered by
total points in descending order.
15/ Retrieve the product name and unit price of products whose unit price is a whole number.
16/ Retrieve the customer ID and the count of orders placed by each customer, where the count is
greater than 3.
17/ Retrieve the product name and unit price of products whose unit price is greater than the average
unit price.
18/ Retrieve the order ID and order date of the oldest order for each customer.
19/ Retrieve the order ID and order date of orders placed in the last 7 days.
20/ Retrieve the customer ID and points of customers whose first name contains the letter 'a' and last
name contains the letter 'b’.
21/ Retrieve the customer ID and the count of orders placed by each customer, ordered by the count in
ascending order.
22/ Retrieve the product name and quantity in stock of products whose quantity is a power of 2.
23/ Retrieve the order ID and order date of orders that were placed on weekends (Saturday or Sunday).

You might also like