5. SELECT
SELECT select_list
FROM table_name;
• select_list: specify one or more columns from which you
want to select data after the SELECT keyword. If the
select_list has multiple columns, you need to separate them
by a comma (,).
• table_name: specify the name of the table from which you
want to select data after the FROM keyword.
6. SELECT
CREATE DATABASE IF NOT EXISTS test1;
USE test1;
ALTER TABLE buyersDROP FOREIGN KEY buyers_fk;
DROP TABLE IF EXISTS buyer_category;
DROP TABLE IF EXISTS buyers;
CREATE TABLE buyer_category (
buyer_cat_id INT AUTO_INCREMENT,
category VARCHAR(15) NOT NULL,
description VARCHAR(500),
CONSTRAINT buyer_cat_pk
PRIMARY KEY (buyer_cat_id));
7. SELECT
#CASCADE actionCREATE TABLE buyers (
buyer_id INT AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
phone VARCHAR(15) NOT NULL UNIQUE,
address VARCHAR(255) NOT NULL,
rating TINYINT,
buyer_cat_id INT,
CONSTRAINT buysers_pk
PRIMARY KEY (buyer_id),
CONSTRAINT uc_name UNIQUE (name),
CONSTRAINT buyers_fk
FOREIGN KEY (buyer_cat_id)
REFERENCES buyer_category(buyer_cat_id)
ON UPDATE CASCADE
ON DELETE CASCADE);
9. Exercise 1
• Use test1.
• Add 2 more rows to buyers_category and 10
rows to buyers.
10. SELECT
#Selecting the data of one column from one table.
SELECT name FROM buyers;
#Selecting the data of two columns from one table.
SELECT name, phone FROM buyers;
#Selecting all columns from one table.
SELECT * FROM buyers;
#Selecting a value without the FROM part.
SELECT 10+10;
SELECT NOW();
SELECT CURRENT_DATE();
SELECT CONCAT('Lenny', ' ', 'Roggers');
11. Exercise 2
• Select the following data from the following
columns
Column / Data Table
1 description buyer_category
2 Your name -
3 Name
Phone
address
buyers
4 ALL buyer_category
5 ALL
Current Date
buyers
12. SELECT
SELECT select_list
FROM dual;
SELECT NOW() FROM dual;
• Sometimes, you still need to use the FROM clause but you
don’t want to reference any actual table. In this case, you can
use the dual table in the FROM clause.
SELECT expression AS column_alias;
SELECT expression column_alias;
SELECT select_list_with_aliases
FROM table_name;
SELECT NOW() FROM dual;
• Sometimes, you still need to use the FROM clause but you
don’t want to reference any actual table. In this case, you can
use the dual table in the FROM clause.
13. SELECT
SELECT expression AS column_alias;
SELECT expression column_alias;
SELECT select_list_with_aliases
FROM table_name;
SELECT NOW() AS current_date_time;
SELECT name AS buyer_name, phone AS buyer_phone
FROM buyers;
• To assign an alias to a column, you place the AS keyword
after the expression followed by a column alias.
• However, The AS keyword is with an expression optional.
15. MySQL
Operators and
Precedence
Operator Description
INTERVAL Date/Time Intervals
BINARY, COLLATE Binary Strings, Character Collation
! NOT
- (unary minus), ~ (unary bit inversion) Negation, bit inversion
^ *, /, DIV, %, MOD Product-related operators
-, + Summation-related operators
<<, >> Bitwise left shit, Bitwise right shift
& Bitwise AND
| Bitwise OR
= (comparison), <=>, >=, >, <=, <, <>, !=,
IS, LIKE, REGEXP, IN, MEMBER OF
Comparison Operators
BETWEEN, CASE, WHEN, THEN, ELSE Between clause, conditional selection
NOT NOT
AND, && AND
XOR XOR
OR, || OR
= (assignment), := Assignment
16. MySQL
Operators
Name Description
& Bitwise AND
> Greater than operator
>> Right shift
>= Greater than or equal operator
< Less than operator
<>, != Not equal operator
<< Left shift
<= Less than or equal operator
<=> NULL-safe equal to operator
%, MOD Modulo operator
* Multiplication operator
+ Addition operator
- Minus operator
- Change the sign of the argument
->
Return value from JSON column after evaluating path;
equivalent to JSON_EXTRACT().
->>
Return value from JSON column after evaluating path and
unquoting the result; equivalent to
JSON_UNQUOTE(JSON_EXTRACT()).
17. MySQL
Operators
Name Description
/ Division operator
:= Assign a value
=
Assign a value (as part of a SET statement, or as
part of the SET clause in an UPDATE statement)
= Equal operator
^ Bitwise XOR
AND, && Logical AND
BETWEEN ... AND ... Whether a value is within a range of values
BINARY Cast a string to a binary string
CASE Case operator
DIV Integer division
IN() Whether a value is within a set of values
IS Test a value against a boolean
IS NOT Test a value against a boolean
IS NOT NULL NOT NULL value test
IS NULL NULL value test
LIKE Simple pattern matching
18. MySQL
Operators
Name Description
MEMBER OF()
Returns true (1) if first operand matches any
element of JSON array passed as second operand,
otherwise returns false (0)
NOT, ! Negates value
NOT BETWEEN ...
AND ... Whether a value is not within a range of values
NOT IN() Whether a value is not within a set of values
NOT LIKE Negation of simple pattern matching
NOT REGEXP Negation of REGEXP
OR, || Logical OR
REGEXP Whether string matches regular expression
RLIKE Whether string matches regular expression
SOUNDS LIKE Compare sounds
XOR Logical XOR
| Bitwise OR
~ Bitwise inversion
20. SELECT and
WHERE
SELECT
select_list
FROM
table_name
WHERE
search_condition;
• search_condition: any combination of one or more expressions. You may
use logical operators such as, but not limited to, AND, OR and NOT.
• In MySQL, a predicate is a Boolean expression that evaluates to TRUE,
FALSE, or UNKNOWN. The output of a SELECT statement includes any row
that satisfies the search_condition.
• The WHERE clause is used also in the UPDATE or DELETE statement to
specify which rows to update or delete.
• When executing a SELECT statement with a WHERE clause, MySQL
evaluates the WHERE clause after the FROM clause and before the
SELECT and ORDER BY clauses.
21. MySQL
Logical and
Comparison
Operators
Name Description
AND, && Logical AND
NOT, ! Negates value
OR, || Logical OR
XOR Logical XOR
> Greater than operator
>= Greater than or equal operator
< Less than operator
<>, != Not equal operator
<= Less than or equal operator
<=> NULL-safe equal to operator
= Equal operator
22. SELECT and
WHERE
#Filter based on a numeric column.
SELECT name
FROM buyers
WHERE buyer_cat_id = 1;
#Filter based on a string/date column.
SELECT *
FROM buyers
WHERE name = 'GGD’;
SELECT name, phone
FROM buyers
WHERE name <> 'GGD';
23. Combining
Multiple
Logical
Expressions
with Logical
Operators
#AND
SELECT name, phone
FROM buyers
WHERE buyer_cat_id = 3 AND rating > 5;
SELECT name, phone
FROM buyers
WHERE buyer_cat_id = 3 && rating > 5;
#OR
SELECT name, phone
FROM buyers
WHERE name = 'GGD’ OR rating > 5;
SELECT name, phone
FROM buyers
WHERE name = 'GGD’ || rating > 5;
25. Combining
Multiple
Logical
Expressions
with Logical
Operators
• The AND and OR operators are logical operators that
combine two or more Boolean expressions and returns 1, 0,
or NULL.
• In practice, you’ll use the AND, OR, and NOT operators in
the WHERE clause of the SELECT, UPDATE, DELETE
statements to form a condition. Also, you can use these
operators in the conditions of the JOIN clauses.
• Short-circuit evaluation: When evaluating an expression
that contains a logical operator, MySQL stops evaluating the
remaining parts of the expression as soon as it can
determine the result.
• MySQL evaluates the OR operator after the AND operator if
an expression contains both AND and OR operators.
27. <=> Operator
• NULL-safe equal. This operator performs an equality
comparison like the = operator, but returns 1 rather than
NULL if both operands are NULL, and 0 rather than NULL if
one operand is NULL.
• The <=> operator is equivalent to the standard SQL IS NOT
DISTINCT FROM operator.
SELECT 1 <=> 1, NULL <=> NULL, 1 <=> NULL;
SELECT 1 = 1, NULL = NULL, 1 = NULL;
28. Exercise 3
• Download customers.sql
(customermodels schema)
from Canvas and
understand the schema by
studying the given ERD
(database diagram):
29. Exercise 3
• use customermodels and extract the following
data:
1. All data of the customers in Las Vegas.
2. All data of the customers not in Las Vegas.
3. Name, phone, and address data of the customers
who have a credit limit greater than 10,000.
4. Order number and Order Date of all the on-hold
orders.
5. Name and phone of the customers neither in Las
Vegas nor Melbourne.
6. All data of the orders that were placed before 2005.
7. All the data of the orders that were placed in 2004.
8. Order number, shipped date, and comments of the
orders that were shipped in 2005.
9. Order number, shipped date, and comments of the
orders that were placed in 2004 and 2005 and had
any comment.
10. All the data of the orders that were not shipped, not
ordered in 2003, and with a comment.
11. All data of the employees who report to VP Sales.
31. SELECT
Statement
with ORDER
BY
SELECT select_list
FROM table_name
WHERE search_condition
ORDER BY
column1 [ASC|DESC],
column2 [ASC|DESC],
...;
USE test1;
SELECT * FROM buyers
WHERE rating > 5
ORDER BY rating DESC, name ASC;
• When querying data from a table, the order of rows in the
result set is unspecified. The ORDER BY clause is used to sort
the rows in the result set.
• The ASC stands for ascending and the DESC stands for
descending. ASC is optional, for it is the standard order.
32. SELECT
Statement
with ORDER
BY
USE test1;
SELECT name, phone, rating * 10 FROM buyers
WHERE rating > 5
ORDER BY rating * 10 DESC, name ASC;
SELECT name, phone, rating * 10 AS rating_percent FROM
buyers
WHERE rating > 5
ORDER BY rating_percent DESC, name ASC;
• Sometimes, your queries may include calculated
fields/columns. The full calculation must be included in
ORDER BY if the calculated column is used to sort the result
set.
• To make the query more readable, you can assign the
expression in the SELECT clause a column alias and use that
column alias in the ORDER BY clause.
33. Exercise 4
• use customermodels and extract the following
data:
1. All customer data ordered by customer ID.
2. All customer data sorted first by their last name
and then by first name, both in ascending order.
3. The full name and phone number of the
customers who are NOT based in Nantes, Las
Vegas, or Melbourne, sorted by name.
4. All data of the offices in Boston, NYC, Paris,
Tokyo, Sydney sorted by Country (Descending),
office (Ascending), and Postel Code (Ascedning).
5. Order Number, Order Line Number, Product
Code, Quantity Ordered, Unit Cost, and Total
Cost of Order Items with a unit cost greater than
50 and a quantity not less than 50 ordered,
sorted by Order Number, and Order Line
Number (both in ascending order).
35. SELECT
Statement
with WHERE:
Special Cases
• SELECT DISTINCT - eliminate duplicate rows in a result set.
• BETWEEN –query data based on a range using BETWEEN
operator.
• IS NULL – test whether a value is NULL or not by using IS
NULL operator.
• IN – determine if a value matches any value in a set.
• LIKE – the technique to query data based on a simple text
pattern.
• LIMIT – use LIMIT to constrain the number of rows returned
by SELECT statement
36. SELECT
Statement
with WHERE:
SELECT
DISTINCT
SELECT DISTINCT select_list
FROM table_name
WHERE search_condition
USE test1;
SELECT DISTINCT rating FROM buyers;
• When querying data from a table, you may get duplicate rows. To remove
these duplicate rows, you use the DISTINCT clause in the SELECT
statement.
• you can specify one or more columns that you want to select distinct
values after the SELECT DISTINCT keywords. The DISTINCT clause will use
the values of these columns to evaluate the uniqueness of the rows.
• When you specify a column that has NULL values in the DISTINCT clause,
it will keep only one NULL value because it considers all NULL values are
the same.
37. SELECT
Statement
with WHERE:
BETWEEN
expression BETWEEN low AND high
USE test1;
SELECT * FROM buyers
WHERE rating BETWEEN 5 AND 8;
• The BETWEEN operator is a logical operator that specifies
whether a value is in a range or not.
• The BETWEEN operator returns 1 if: value >= low AND value
<= high. Otherwise, it returns 0.
• If the value, low, or high is NULL, the BETWEEN operator
returns NULL.
• To negate the BETWEEN operator, the NOT operator can be
used:
expression NOT BETWEEN low AND high
38. SELECT
Statement
with WHERE:
IS NULL
value IS NULL
value IS NOT NULL
USE test1;
INSERT INTO buyers(name, phone, address, rating, buyer_cat_id)
VALUES
('Gary Lake', ‘243-2221-276', ‘76, Kill Road, TRNT’, NULL, 2),
('HDDFE', '932-4321-233', ‘55, Roul Road, KENS’,NULL, 1)
SELECT * FROM buyers
WHERE rating IS NULL;
SELECT * FROM buyers
WHERE rating IS NOT NULL;
• To check if a value is NULL or not, the IS NULL operator is used, not the
equal operator (=). It returns TRUE if a value is NULL.
39. SELECT
Statement
with WHERE:
IS NULL
• If a DATE or DATETIME column has a NOT NULL constraint and contains a
special date '0000-00-00', you can use the IS NULL operator to find such
rows.
USE test1;
CREATE TABLE IF NOT EXISTS trip (
id INT AUTO_INCREMENT,
name VARCHAR(255),
destination VARCHAR(255),
begin_date DATE NOT NULL,
end_date DATE NOT NULL,
PRIMARY KEY(id)
);
INSERT INTO trip(name, destination. begin_date, end_date)
VALUES('Niagara', 'Niagara Falls', '2020-01-01','0000-00-00'),
('Blue Mountain', 'Blue Mountain', '2020-01-01','0000-00-00'),
('Museum', 'Museum Toronto', '2020-01-01','2030-01-01’);
SELECT * FROM trip
WHERE end_date IS NOT NULL;
40. SELECT
Statement
with WHERE:
IN
value IN (value1, value2, value3,...)
USE test1;
SELECT * FROM buyers
WHERE rating IN (5, 7, 9);
• The IN operator allows you to determine if a value matches
any value in a list of values.
• The IN operator returns 1 (true) if the value equals any value
in the list (value1, value2, value3,…). Otherwise, it returns 0.
• Generally, the IN operator returns NULL in two cases:
• The value on the left side of the operator is NULL.
• The value doesn’t equal any value in the list and one of
values in the list is NULL.
41. SELECT
Statement
with WHERE:
LIMIT
SELECT
select_list
FROM
table_name
ORDER BY
sort_expression
LIMIT offset, row_count;
USE test1;
SELECT * FROM buyers
ORDER BY name
LIMIT 3, 4;
• The LIMIT clause is used in the SELECT statement to constrain
the number of rows to return.
• The LIMIT clause accepts one or two arguments:
• The offset specifies the offset of the first row to return. The offset of
the first row is 0, not 1.
• The row_count specifies the maximum number of rows to return.
42. SELECT
Statement
with WHERE:
LIKE
expression LIKE pattern ESCAPE escape_character;
expression NOT LIKE pattern ESCAPE escape_character;
• The LIKE operator is a logical operator that tests whether a string
contains a specified pattern or not.
• If the expression matches the pattern, the LIKE operator returns 1.
Otherwise, it returns 0.
• MySQL provides two wildcard characters for constructing patterns:
• The percentage ( % ) wildcard: matches any string of zero or more
characters.
• The underscore ( _ ) wildcard: matches any single character.
• For example, k% matches any string starts with the character k such as
knife and kite. The ti_ matches any string starts with ti and is followed by
any character such as tip and tin.
• When the pattern contains the wildcard character and you want to treat
it as a regular character, you can use the ESCAPE clause. In this case, you
can use the ESCAPE clause to specify the escape character so that the
LIKE operator interprets the wildcard character as a literal character.
• If you don’t specify the escape character explicitly, the backslash
character () is the default escape character.
• For example, if you want to find products whose product codes contain
the string _20 , you can use the pattern %_20% with the default escape
character:
43. SELECT
Statement
with WHERE:
IS NULL
USE test1;
SELECT * FROM buyers
WHERE name LIKE g%;
SELECT * FROM buyers
WHERE name LIKE g__;
SELECT * FROM buyers
WHERE name NOT LIKE %g%;
44. Exercise 5
• use customermodels and extract the following
data:
1. Full name of the employees who work for the offices
1,4, and 5.
2. All data of the customers who the second highest
and third highest credit limit.
3. All data of the customers whose name starts with ‘a’.
4. Order Numbers of order that had at least one item
with a total cost greater than $ 200.
5. All data of the employees whose last name starts
with ‘p’ and who work for the office 1.
6. All data of the employees with E and S in any part of
their name.
7. Order Number, Order Line Number, Product Code,
and Total Cost of Order Items with a unit cost
between 50 and 100 and a total cost that is less than
1000, sorted by Order Number, and Order Line
Number (both in ascending order).
8. Name and phone of the customers who are in
France, USA, Australia, or Norway whose Address
Line 2 is Not Null.