Learning MySQL By Example
Learning MySQL By Example
Mathew Miles
Table of Contents
Introduction 1
3. Using Functions 57
Glossary 143
Index 149
Mathew Miles
In a future edition, this book will include SQL design basics and guidance on how to install MySQL and MySQL
Workbench. It may also include screencasts that will walk you through the various concepts.
1
2
1
Code Example:
1 USE world;
2 SELECT name
3 FROM city
4 WHERE CountryCode = “AFG”
5 ORDER BY name
6 LIMIT 3
Results:
3
Let us break the statement line by line:
USE world;
The USE clause sets the database that we will be querying. You typically have more than one database on your
database server. You have to specify which database you are working in.
The semicolon “;” indicates the end of a statement. You can execute multiple statements in sequence by defining
each statement with a semicolon
SELECT name
The SELECT clause defines the columns and column order that you want to retrieve in your results set. If you want
to retrieve all of the columns from the base table you can simply use SELECT *
You separate each column name with a comma “,” ex., SELECT name, CountryCode
There is no trailing comma at the end of a column list
FROM city
The FROM clause specifies the table that the results will be coming from
You can specify multiple tables by using a JOIN clause, but we will address that topic at a future time
ORDER BY name
The ORDER BY clause is not required but when used it defines the sort order of the results
By default, the sort order is ascending. This is implicit However, you can use explicit syntax of ASC. If you want the
sort, order to be descending you can use the keyword DESC.
You can specify more than one column in an Order By statement separated by commas. The sort order DESC, ASC
applies to each column individually. Below IS some examples
ORDER BY population ASC, name DESC
ORDER BY population, name (ASC is always implied if not explicitly stated)
LIMIT 5;
4
If you only want to return a specified number of rows from the result set, you can use the LIMIT clause. This can be
helpful when you want to test a query for accuracy that could potentially bring back a very large number of rows.
The semicolon ; defines the end of the statement
Base Table Value Column Name Comma separated list of column names
Code Example:
USE world;
SELECT name
FROM country
WHERE name LIKE ‘A%’
Results:
5
Table 3. REXEXP Keyword
[char1 – char2] Matches any single character within the given range.
Code Example:
USE world;
SELECT name
FROM country
WHERE name REGEXP 'g[o,u]';
Results:
6
Arithmetic Operators
Arithmetic operators can be used in the SELECT, WHERE, and ORDER BY clauses.
Operators are evaluated in the same way as arithmetic in other contexts.
* Multiplication 1
/ Division 1
+ Addition 2
- Subtraction 2
7
Code Example:
USE world;
SELECT name, population / SurfaceArea
AS "People per square mile"
FROM country;
Results:
Column Aliases
A column alias provides a way to create a clean or more descriptive header for a results set.
A column alias cannot be used in a SELECT, WHERE, GROUP BY or HAVING clause due to the order of
execution. You must refer to the original column name.
In the previous example, we created a new column that was a calculated value. The problem is that the column header
is now population / SurfaceArea. However we can rename the column header to something cleaner be create a column
alias. Look at the code snippet below.
Code Example:
We used the AS keyword then in quotes we put the new column alias of “People per square mile.” Which changes the
column header as seen show below.
8
Results:
Comparison Operators
Operator Description
= Equal
9
Operator Description
!= Not equal
Code Example:
USE world;
SELECT name, population
FROM country
WHERE population > 1000000;
Results:
IS NULL
Null values indicate an unknown or non-existent value and is different from an empty string (‘ ‘).
To test for a null value you use the IS NULL clause
The test for a value use IS NOT NULL clause
Code Example:
Results:
10
BETWEEN Operators
Code Example:
USE world;
SELECT name, IndepYear
FROM country
WHERE name BETWEEN "Aruba" and "Bahamas";
Results:
11
The IN Keyword
The IN clause tests whether an expression is equal to a value or values in a list of expressions.
The order of the items in the list does not matter.
You can use the NOT operator to test for items not in the list.
The IN clause may be used with a subquery.
Code Example:
USE world;
SELECT name
FROM country
WHERE name IN ('Aruba', 'Barbados', 'Cuba', 'Bahamas')
ORDER BY population ASC;
Results:
12
AND, OR, NOT Logical Operators
Example:
USE world;
SELECT name, population
FROM country
WHERE region = 'caribbean'
AND population > 100000
ORDER BY population ASC;
Results:
13
DISTINCT Keyword
Example:
Results:
14
The Five Clauses of the SELECT Statement
Column Specifications
Arithmetic Operators
Column Aliases
Comparison Operators
DISTINCT Clause
15
16
1.1
Results:
17
Let us break the statement line by line:
USE world;
The USE clause sets the database that we will be querying. You typically have more than one database on your
database server. You have to specify which database you are working in.
The semicolon “;” indicates the end of a statement. You can execute multiple statements in sequence by defining
each statement with a semicolon
SELECT name
The SELECT clause defines the columns and column order that you want to retrieve in your results set. If you want
to retrieve all of the columns from the base table you can simply use SELECT *
You separate each column name with a comma “,” ex., SELECT name, CountryCode
There is no trailing comma at the end of a column list
FROM city
The FROM clause specifies the table that the results will be coming from
You can specify multiple tables by using a JOIN clause, but we will address that topic at a future time
ORDER BY name
The ORDER BY clause is not required but when used it defines the sort order of the results
By default, the sort order is ascending. This is implicit However, you can use explicit syntax of ASC. If you want the
sort, order to be descending you can use the keyword DESC.
You can specify more than one column in an Order By statement separated by commas. The sort order DESC, ASC
applies to each column individually. Below IS some examples
ORDER BY population ASC, name DESC
ORDER BY population, name (ASC is always implied if not explicitly stated)
LIMIT 5;
18
If you only want to return a specified number of rows from the result set, you can use the LIMIT clause. This can be
helpful when you want to test a query for accuracy that could potentially bring back a very large number of rows.
The semicolon; defines the end of the statement.
19
20
1.2
Column Specifications
Column Specifications
Source Option Syntax
Base Table Value Column Name Comma separated list of column names
21
22
1.3
Code Example:
USE world;
SELECT name
FROM country
WHERE name LIKE ‘A%’
Results:
23
Table 3. REXEXP Keyword
[char1 – char2] Matches any single character within the given range.
Code Example:
USE world;
SELECT name
FROM country
WHERE name REGEXP 'g[o,u]';
Results:
24
This content is provided to you freely by BYU-I Books.
25
26
1.4
Arithmetic Operators
Arithmetic Operators
Arithmetic operators can be used in the SELECT, WHERE, and ORDER BY clauses.
Operators are evaluated in the same way as arithmetic in other contexts.
* Multiplication 1
/ Division 1
+ Addition 2
- Subtraction 2
Code Example:
USE world;
SELECT name, population / SurfaceArea
AS "People per square mile"
FROM country;
Results:
27
This content is provided to you freely by BYU-I Books.
28
1.5
Column Aliases
Column Aliases
A column alias provides a way to create a clean or more descriptive header for a results set.
A column alias cannot be used in a SELECT, WHERE, GROUP BY or HAVING clause due to the order of
execution. You must refer to the original column name.
In the previous example, we created a new column that was a calculated value. The problem is that the column header
is now population / SurfaceArea. However, we can rename the column header to something cleaner by creating a
column alias. Look at the code snippet below.
Example:
We used the AS keyword then in quotes we put the new column alias of “People per square mile.” Which changes the
column header as seen show below.
Results:
29
This content is provided to you freely by BYU-I Books.
30
1.6
Comparison Operators
Comparison Operators
Operator Description
= Equal
!= Not equal
Example:
USE world;
SELECT name, population
FROM country
WHERE population > 1000000;
31
Results:
32
1.7
IS NULL
Null values indicate an unknown or non-existent value and is different from an empty string (‘ ‘).
To test for a null value you use the IS NULL clause
The test for a value use IS NOT NULL clause
Example:
Results:
33
BETWEEN Operators
Example:
USE world;
SELECT name, IndepYear
FROM country
WHERE name BETWEEN "Aruba" and "Bahamas";
Results:
The IN Keyword
The IN clause tests whether an expression is equal to a value or values in a list of expressions.
The order of the items in the list does not matter.
You can use the NOT operator to test for items not in the list.
The IN clause may be used with a subquery.
Examples:
34
USE world;
SELECT name
FROM country
WHERE name IN ('Aruba', 'Barbados', 'Cuba', 'Bahamas')
ORDER BY population ASC;
Results:
35
36
1.8
Example:
USE world;
SELECT name, population
FROM country
WHERE region = 'caribbean'
AND population > 100000
ORDER BY population ASC;
Results:
37
This content is provided to you freely by BYU-I Books.
38
1.9
DISTINCT Clause
DISTINCT Keyword
Example:
Results:
39
This content is provided to you freely by BYU-I Books.
40
2
41
42
2.1
A JOIN clause allows you to access data from two or more tables in a query.
A join links to tables on a common key between the two tables. Usually the primary key on one table is
compared to the foreign key on another table using the equals ( = ) sign. This is an equijoin or an inner-join.
However, other comparison operators are also valid.
If column names from each table in the join have the same name, they must be qualified with the table
name or a table alias.
Below is a basic example of a SQL statement with an inner join clause using explicit syntax.
1 USE world;
2 SELECT city.name AS "City Name",
3 country.name AS "Country Name"
4 FROM country
6 JOIN city
5 ON city.CountryCode = country. Code;
You could write SQL statements more succinctly with an inner join clause using table aliases. Instead of writing out the
whole table name to qualify a column, you can use a table alias.
1 USE world;
2 SELECT ci.name AS "City Name",
3 co.name AS "Country Name"
4 FROM city ci
5 JOIN country co
6 ON ci.CountryCode = co.Code;
The results of the join query would yield the same results as shown below whether or not table names are completely
written out or are represented with table aliases. The table aliases of co for country and ci for city are defined in the
FROM clause and referenced in the SELECT and ON clause:
Results:
43
Let us break the statement line by line:
USE world;
The USE clause sets the database that we will be querying. You typically have more than one database on your
database server. You have to specify which database you are working in.
The semicolon “;” indicates the end of a statement. You can execute multiple statements in sequence by defining
each statement with a semicolon
The SELECT clause defines the columns and column order that you want to retrieve in your result set. In this
example, we have columns from two separate tables. These columns have the same name, so they MUST be
qualified with the full table name or table alias. Otherwise, the column names are ambiguous.
You separate each column name with a comma “,” including the corresponding table alias if one is provided
To create a friendlier column name in the output, we assign a column alias to each qualified column name. Instead
of ci.name showing in the column header of the report, we assign a friendlier column alias of “City Name” and for
co.name “Country Name.”
FROM city ci
The FROM clause specifies the table(s) from which results will be returned.
In a JOIN clause, the first table to be joined is specified after the FROM clause.
JOIN country co
ON ci.CountryCode = co.Code;
44
The ON clause specifies the common column from each table (usually a PK in one table and its corresponding
foreign key in the other). Each column name is separated with an operator (join condition usually the equals ( = )
sign.
45
46
2.2
To include more tables in the query, you simply add more additional JOIN clauses
Code Snippet:
1 USE world;
2 SELECT ci.name AS "City Name",
3 co.name AS "Country Name",
4 cl.language AS "Country Language"
5 FROM city ci
6 JOIN country co
7 ON ci.CountryCode = co.Code
8 JOIN country language cl
9 ON cl.CountryCode = ci.CountryCode;
Results:
47
JOIN countrylanguage cl.
ON cl.CountryCode = ci.CountryCode;
The common column between the two tables being joined is the CountryCode column from the countrylanguage
table and the CountryCode column from the city table.
The “cl” alias previously defined for countrylanguage is used to specify the CountryCode column.
48
2.3
An outer join will return all the rows from one table and only the rows from the other table that match the
join condition
You can use LEFT JOIN or RIGHT JOIN. If you use LEFT JOIN, all the rows from the table on the left of the
equals ( = ) sign will be included in the result set whether the join condition is satisfied or not
If you use RIGHT JOIN, all the rows from the table on the right of the equals ( = ) sign will be included in the
result set whether the join condition is satisfied or not.
1 USE world;
2 SELECT c.name, c.continent, cl.language
3 FROM country c LEFT JOIN countrylanguage cl
4 ON c.code = cl.CountryCode
5 ORDER BY cl.language ASC;
Results:
49
SELECT c.name, c.continent, cl.language
The “c.” pre-pended to name and continent is a table alias to the country table. Therefore,
return name and continent from the country table.
The “cl” prepended to the language table is a table alias to the countrylanguage table.
Therefore, return language from the countryLanguage table.
ON c.code = cl.CountryCode
ON is the second part of the JOIN clause. It precedes the JOIN condition
c.code refers to the code column from the country table and is a primary key. Since the key is on
the LEFT side of the join condition, all rows from the country table will be included in the results
whether they have a matching key in the countrylanguage table or not.
Cl.CountryCode refers to the CountryCode on the countrylanguage table and is a foreign key to
the country table. Only the rows that have a matching key in the country table will be included
in the results.
50
This content is provided to you freely by BYU-I Books.
51
52
2.4
A UNION combines the results of two or more queries into a single result set
Each result set must have the same number of columns
The corresponding data types for each column must be compatible. However, the column names may be
different from each result set
A UNION removes duplicate rows by default
You may interfile the results using an ORDERY BY clause if there is a column with a common name.
Code Example:
1 USE world;
2 SELECT name, population
3 FROM city WHERE CountryCode = 'AUS'
4 UNION
5 SELECT name, population
6 FROM country
7 WHERE continent = 'Oceania'
8 ORDER BY name;
Results:
53
SELECT name, population
FROM city
WHERE CountryCode = 'AUS'
The first query returns the name and population from the city table.
The filter (WHERE CLAUSE) of the query limits the country code to Australia.
UNION
The ‘UNION’ clause will combine this query with the results of the subsequent query.
The second query returns the name and population from the country table.
The filter (WHERE CLAUSE) of the query limits the continent code to Oceania.
ORDER BY name;
It is possible to sort (ORDER BY CLAUSE) and interfile the results of both queries because each query shares a
column with the same name. Otherwise, the ORDER BY clause would generate an error.
54
This content is provided to you freely by BYU-I Books.
55
56
3
Using Functions
Date Functions
Numeric Functions
String Functions
57
58
3.1
Date Functions
There are a number of functions that give the current date and time. The DATE() function is a date
formatting function, but I include it in the list because it is often confused with the NOW() function
CURRENT_DATE, CURRENT_TIME, UTC_DATE, UTC_TIME can be used with the parentheses “()” or not. They
accept no parameters
59
Function Type Example Result
Results:
DATE_ADD
• Returns a date with a DATE or DATETIME value equal to the original value plus the specified interval.
Code Snippet:
USE bike;
SELECT order_date,
DATE_ADD(order_date, INTERVAL 1 DAY) AS 'ORDER DATE PLUS 1 day',
60
DATE_ADD(order_date, INTERVAL 6 MONTH) AS 'ORDER DATE PLUS 6 months',
DATE_ADD(order_date, INTERVAL '2 12' DAY_HOUR)
AS 'ORDER DATE PLUS 2 days 1 hour'
FROM cust_order;
Results:
DATE_FORMAT
• Dates must be enclosed in quotes • You can pass a DATE or DATETIME datatype to DATE_FORMAT
Code Snippet:
USE world;
SELECT name, continent, DATE_FORMAT('2020-01-28', '%m/%d/%y')
FROM country;
Results:
61
Table 4. Format List
Specifier Description
%D Day of the month with English suffix (0th, 1st, 2nd, 3rd, …)
%f Microseconds (000000..999999)
%H Hour (00..23)
%h Hour (01..12)
%I Hour (01..12)
62
Specifier Description
%k Hour (0..23)
%l Hour (1..12)
%p AM or PM
%S Seconds (00..59)
%s Seconds (00..59)
%U Week (00..53), where Sunday is the first day of the week; WEEK() mode 0
%u Week (00..53), where Monday is the first day of the week; WEEK() mode 1
%V Week (01..53), where Sunday is the first day of the week; WEEK() mode 2; used with %X
%v Week (01..53), where Monday is the first day of the week; WEEK() mode 3; used with %x
%X Year for the week where Sunday is the first day of the week, numeric, four digits; used with %V
%x Year for the week, where Monday is the first day of the week, numeric, four digits; used with %v
63
Specifier Description
%% A literal % character
DATEDIFF
Example:
Results:
64
This content is provided to you freely by BYU-I Books.
65
66
3.2
Numeric Functions
ROUND
The ROUND function has two parameters. The first is a number, usually a DECIMAL or a FLOAT. The second
defines the number of decimals to which the number will be rounded.
If no length is provided, the number is rounded to a whole number.
Example:
USE world;
SELECT name, LifeExpectancy, ROUND(LifeExpectancy)
FROM world.country;
Results:
67
FLOOR, CEILING, TRUNCATE
FLOOR() will return the next lowest whole number no matter what the decimal point.
CEILING() will return the next highest whole number no matter what the decimal point.
TRUNCATE() will return the number truncated to the precision specified.
Example:
USE bike;
SELECT list_price, FLOOR(list_price), CEILING(list_price),
TRUNCATE(list_price, 0)
FROM product;
Results:
68
This content is provided to you freely by BYU-I Books.
69
70
3.3
String Functions
CONCAT
Example:
USE world;
SELECT CONCAT(name, ', ', continent)
FROM country;
Results:
71
RIGHT, LEFT
The RIGHT and LEFT functions have two parameters. The first is a string and the second is the number of
characters to be returned.
The RIGHT function starts counting from the right side of the string. • The LEFT function starts counting
from the left side of the string.
Example:
USE bike;
SELECT category_name,
LEFT(category_name, 8) AS 'First 8 Characters',
RIGHT(category_name, 8) AS 'Last 8 Characters'
FROM category;
Results:
72
TRIM, LTRIM, RTRIM
The TRIM function will remove leading and trailing spaces from a string.
The LTRIM function will remove leading spaces from a string.
The RTRIM function will remove trailing spaces from a string.
Example:
Results:
FORMAT
73
Function Type Example Result
FORMAT(number, decimal) string FORMAT(1234.342, 2) -356
Code Sample:
SELECT FORMAT(list_price,2)
FROM bike.product;
Results:
LOWER, UPPER
Example:
SELECT UPPER('Salmon'),
LOWER('Salmon');
Results:
74
LOCATE, LENGTH, SUBSTRING
LOCATE(), and LENGTH() accept a string but return an integer. • SUBSTRING() accepts a string and returns a
string.
Example:
SELECT LOCATE('al','salmon',1),
LENGTH('salmon'),
SUBSTRING('salmon',3,999);
Results:
75
This content is provided to you freely by BYU-I Books.
76
4
77
78
4.1
1 USE world;
2 INSERT INTO city
3 (name, countryCode, district, population)
4 VALUES
5 ("San Felipe", "CHL", "Valparaiso", 64126);
Results:
79
Results of the Insert:
Insert the value into the city table. The INTO keyword is not required.
VALUES
The VALUES keyword is between the column list and the actual values. No commas are necessary.
The values order must appear in the corresponding order of the column list.
You must enclose strings in quotes.
You must not enclose numbers in quotes.
You do not have to specify columns that allow null values or default values in the column list. They will
automatically get a null or default value.
80
This content is provided to you freely by BYU-I Books.
81
82
4.2
Code Sample:
1 USE world;
2 INSERT INTO city
3 VALUES
4 (DEFAULT, "San Felipe", "CHL", "Valparaiso", 64126);
Results:
83
(DEFAULT "San Felipe", "CHL", "Valparaiso", 64126);
The values order must appear in the same order they exist in the table.
You must enclose strings in quotes.
You must NOT enclose numbers in quotes.
You must specify all column names and provide the keyword “DEFAULT” or a literal value for columns that provide a
default option.
If you do not want to provide a value for columns that allow null values, you must provide the keyword “null”.
84
4.4
Code Sample:
1 USE world;
2 UPDATE city
3 SET Population = 65000, district = 'Aconcagua';
Results:
UPDATE city
85
You indicate the table columns and associated values you want to change them to by using the equals sign ( = ).
You must separate each column and value with a comma.
There is no trailing comma
86
4.4
Code Example:
1 USE world;
2 DELETE
3 FROM city
4 WHERE name = 'san felipe' AND countrycode = 'chl';
Results:
DELETE
87
FROM city
You must specify the table from which you are deleting rows.
You should use a WHERE clause with a DELETE statement to avoid deleting every row in a table.
88
5
Aggregate Functions
Grouping Data
89
90
5.1
Aggregate Functions
Aggregate Functions
AVG([DISTINCT] column_values) numeric The average of the non-null columns in the expression
SUM([DISTINCT] column_values) numeric The total of the non-null columns in the expression
MIN([DISTINCT] column_values) numeric, date, The lowest value off the non-null columns in the
string expression
MAX([DISTINCT] column_values) numeric, date, The highest value of the non-null columns in the
string expression
91
Code Sample:
USE bike;
SELECT AVG(list_price), SUM(list_price), MIN(list_price),
MAX(list_price), COUNT(list_price), COUNT(*)
FROM product;
Output:
92
5.2
Grouping Data
Aggregate Order of
Function Execution Description
Notice the order of execution. GROUP BY happens before WHERE but after HAVING.
It is possible to use WHERE and HAVING in the same statement. They are not mutually exclusive.
93
This content is provided to you freely by BYU-I Books.
94
5.3
Code Example:
USE bike;
SELECT category_id, AVG(list_price)
FROM product
GROUP BY category_id
Results:
USE bike:
FROM product:
95
GROUP BY category_id:
Instead of returning a single value that is the average of all list_price items in the product table, return an average
list_price for each category
Without the GROUP BY clause, we see from our first example only a single row is returned with an average
list_price of 1520.591402.
With the GROUP BY clause, we return an average for each category_id.
96
5.4
The report would be nicer if we showed the category name instead of the category_id. This will require
joining the product table to the category table.
We can ROUND the AVG list price by category to TWO decimals points.
We can CONCAT the dollar sign to the left of the list_price.
Code Sample:
USE bike;
SELECT category_name,
CONCAT('$', ROUND(AVG(list_price),2)) AS 'Average List Price'
FROM product p
JOIN category c
ON p.category_id = c.category_id
GROUP BY category_name
ORDER BY category_name;
Output:
97
USE bike:
SELECT category_name,
FROM product p
JOIN category c
ON p.category_id = c.category_id
GROUP BY category_name
Instead of retrieving a single value with the average price of all products, return a list of average prices by category
name.
98
ORDER BY category_name;
99
100
5.5
The HAVING CLAUSE allows you to use an aggregate function as a filter. This is not allowed in a WHERE
clause.
Any columns or expressions you want to use in a HAVING clause, MUST BE DEFINED IN THE SELECT
CLAUSE as well.
Code Sample:
USE bike;
SELECT category_id, AVG(list_price)
FROM product
GROUP BY category_id
HAVING AVG(list_price) > 1000
Output:
We previously discussed the preceding lines of code for this query so we will focus solely on the HAVING clause.
101
HAVING AVG(list_price) > 1000
The HAVING clause executes after the GROUP BY clause but before the SELECT
If you use an aggregate function in the HAVING clause, you must include the same aggregate function in the
SELECT
If you reference a column or expression in the HAVING clause, you must include the same column or expression in
the SELECT
You cannot use aggregate functions in a WHERE clause
102
5.5
Below is an example of a statement that includes both the HAVING and WHERE clause in the same SQL statement.
USE bike;
SELECT category_id, AVG(list_price)
FROM product
WHERE model_year = 2016
GROUP BY category_id
HAVING AVG(list_price) > 1000
Output:
103
The HAVING clause executes after the GROUP BY clause but before the SELECT
If you use an aggregate function in the HAVING clause, you must include the same aggregate function in the
SELECT
If you reference a column or expression in the HAVING clause, you must include the same column or expression in
the SELECT
You cannot use aggregate functions in a WHERE
104
5.6
COUNT(*) is the only aggregate function that counts rows with null values.
When you specify a count based on a specific column, null values will not be counted.
Code Sample:
USE bike;
SELECT COUNT(phone), COUNT(*)
FROM CUSTOMER
Output:
105
This content is provided to you freely by BYU-I Books.
106
5.7
The DISTINCT keyword allows you to eliminate duplicate rows in aggregate functions.
You may also use the DISTINCT keyword with columns of the base table in a SELECT statement.
COUNT(list_price) counts all the rows in the product table that have a list price.
COUNT(DISTINCT list_price) eliminates duplicate values in the list_price.
Code Sample:
Example
USE bike;
SELECT COUNT(list_price), COUNT(DISTINCT list_price)
FROM product;
Output:
107
This content is provided to you freely by BYU-I Books.
108
6
109
110
6.1
Code Sample:
1 USE world;
2 SELECT name, population
3 FROM city
4 WHERE CountryCode IN
5 (SELECT code
6 FROM country
7 WHERE region = 'Caribbean')
8 ORDER BY population
9 LIMIT 5;
Results:
111
SELECT name, population
FROM city
Return the name and population columns from the city table.
WHERE CountryCode IN
Filter to only rows that have a value found in the subsequent subquery.
(SELECT code
FROM country
The subquery shown above returns a result list of all of the codes from the country table that have a region of
‘Caribbean’.
The subquery must be in parentheses in MySQL.
Each code (PK in country table) returned by the subquery is checked against CountryCode (FK in city table). If they
match, the name and population are retrieved from the city table.
112
This content is provided to you freely by BYU-I Books.
113
114
6.2
Code Sample:
1 UPDATE country
2 SET GNPOld = 0.00
3 WHERE Code IN
4 (SELECT CountryCode FROM countrylanguage WHERE population = 0)
Results:
UPDATE country
115
Update the country table
WHERE Code IN
Update only the rows where the Code column value is in the results list returned in the subquery show below.
Return a list of values from the CountryCode column from the countrylanguage table that has a population equal to
zero.
If these values match a code in the country table, the row is updated.
116
6.3
It is often helpful to create a duplicate table from an existing table for testing purposes
You can combine the CREATE TABLE command with a select statement to create a duplicate of a table
structure as well as the data in the table.
Code Sample:
1 USE world;
2 CREATE TABLE city_bak AS SELECT * FROM city;
Results:
USE world;
Create a new table named city_bak with the exact same structure as the city table.
Copy all of the data from the city table to the city_bak table
117
This content is provided to you freely by BYU-I Books.
118
6.4
NOTE: Before you can run a DELETE or UPDATE statement without a WHERE clause, you must uncheck “Safe Updates”
checkbox in MySQL Preference. Please see below.
Code Sample:
119
USE world;
DELETE FROM city_bak
WHERE CountryCode IN
(SELECT code FROM country
WHERE region = 'Central Africa');
Results:
USE world;
The tables used in this example are in the world database. Make sure it is selected as the default
WHERE CountryCode IN
We are going to use a filter to delete items from the city_bak table where the CountryCode is found in a list of
values that we will pass to it.
We will execute a subquery on the country table and return a list of code values (PK to FK in city_bak table) where
the region is equal to ‘Central Africa’.
You could accomplish the same thing by joining the city_bak table to the country table, then filtering on the region
column from the country table.
120
This content is provided to you freely by BYU-I Books.
121
122
7
SQL Views
123
124
7.1
SQL Views
125
126
7.2
Design Flexibility: By using a view instead of a query in an application, it is easier to make changes to the
underlying table structure.
Improved Security: By using a view to return data from tables instead of a SELECT, you can hide the WHERE
clause or other columns to which you do not want the user to have access.
Query Simplification: You can write simple select statements against views, which handle complex queries
and joins.
Code Sample:
USE WORLD;
CREATE VIEW city_country AS
SELECT ci.name AS city_name, co.name AS country_name
FROM city ci
JOIN country co
ON ci.CountryCode = co.Code;
127
CREATE VIEW city_country AS
Only the columns defined in the SELECT statement will be available to the VIEW
It is a good idea to provide a column alias in the select because the VIEW will not have access to the underlying
table structure.
FROM city ci
JOIN country co
ON ci.CountryCode = co.Code;
128
This content is provided to you freely by BYU-I Books.
129
130
7.3
There are some restrictions to creating a VIEW if you want to be able to run an UPDATE statement against
it.
SELECT list cannot include a DISTINCT clause.
SELECT list cannot contain aggregate functions (SUM, COUNT, MIN, MAX, AVG, COUNT(*))
SELECT statement cannot use GROUP BY or HAVING. The VIEW cannot include a UNION operator.
If you use any of the restricted statements, your view will be read-only.
131
132
8
SQL Indexes
133
134
8.1
SQL Indexes
135
136
8.2
137
138
8.3
139
This content is provided to you freely by BYU-I Books.
140
8.4
141
This content is provided to you freely by BYU-I Books.
142
Glossary
Find something...
Aggregate Function
Performs an operation on a set of records in a column and returns a single value.
Arithmetic Operators
Arithmetic operators ARE: * (multiplication), / (division), DIV (integer division), % (MOD) or remainder, + (addition), -
(subtraction). These operators can be used in the SELECT, WHERE, and ORDER BY clauses. Operators are evaluated in
the same way as arithmetic in other contexts.
AVG function
Returns the average of the non-null columns in the expression.
BETWEEN operator
The BETWEEN operator is similar to >= and <=. BETWEEN includes everything between the two values indicated.
BETWEEN works with both text and number.
CEILING function
Returns the next highest whole number no matter what the decimal point.
Column Aliases
A column alias provides a way to create a clean or more descriptive header for a results set. A column alias cannot be
used in a SELECT, WHERE, GROUP BY or HAVING clause due to the order of execution. You must refer to the original
column name.
Column Specifications
A column specification may be derived from a base table. Or it my be a calculated value as a result of an arithmetic
expression or a function.
143
Comparison Operators
The comparison operators are = (equals), < (less than), > (greater than), <= (less than or equal to), >=, <> (not equal), !=
(not equal). Comparison operators compare two expressions. The result of a comparison results to true or false.
Comparison operators are not case sensitive and are used with text and dates as well as numbers.
Compound condition
When more than one logical operator (AND, OR, NOT) is used in the WHERE clause.
CONCAT function
Combines a list of strings into a single string.
COUNT function
The number of the non-null columns in the expression.
CURRENT_DATE function
Returns current local date.
CURRENT_TIME function
Returns current local time
DATE function
Extracts the date from date/time input. If time is included it is dropped.
DELETE clause
SQL clause that deletes data from a table.
DISTINCT clause
The DISTINCT clause removes duplicate rows from a query.
FLOOR function
Returns the next lowest whole number no matter what the decimal point.
FROM clause
Specifies the base table(s) from which results will be retrieved.
144
GROUP BY clause
Groups rows of a result set based on columns or expressions separated by commas.
HAVING clause
The HAVING CLAUSE allows you to use an aggregate function as a filter. This is not allowed in a WHERE clause.
IN operator
The IN operator tests whether an expression is equal to a value or values in a list of expressions. The order of the items
in the list does not matter. You can use the NOT operator to test for items not in the list. The IN clause may be used with
a subquery.
Indexes
A SQL index is like the index of a book. It speeds up the retrieval of a record. The relational database management
system (RDBMS) can retrieve a record with the index key instead of having to perform a table scan.
INSERT clause
SQL Clause used to insert data into a table.
IS NULL function
Null values indicate an unknown or non-existent value and is different from an empty string (‘ ‘). To test for a null value
you use the IS NULL clause. The test for a value use IS NOT NULL clause
JOIN clause
A JOIN clause allows you to access data from two or more tables in a query.
LEFT function
Returns a substring starting from the left side of the string.
LIKE operator
The LIKE keyword is used with the WHERE clause. The LIKE keyword and can use two symbols as wildcards. The
percent ( % ) symbol matches any number of characters and the underscore ( _ ) matches a single character.
145
LIMIT clause
Specifies the number of rows to be returned.
LTRIM function
Removes leading spaces from a string.
MIN function
The lowest value off the non-null columns in the expression
NOW function
Returns current local date and time.
ORDER BY clause
SQL clause that orders a result set.
REGEXP operator
REGEXP operator allows you to do more complex pattern matching than a LIKE keyword/ Some version of REGEXP
exists in many computer languages. Refer to the “LIKE and REGEXP” handout for a full list of examples.
RIGHT function
Returns a substring starting from the right side of the string.
ROUND function
Rounds to the decimal specified.
RTRIM function
Removes trailing spaces from a string.
SELECT clause
Specifies the columns that will appear in a SQL query result set.
146
Subquery
A subquery is a SELECT statement coded within another SELECT statement.
SUM function
The total of the non-null columns in the expression.
Summary Query
A query that uses at least one aggregate function.
TRIM function
Removes leading and trailing spaces from a string.
TRUNCATE function
Returns the number truncated to the precision specified.
UNION clause
A UNION combines the results of two or more queries into a single result set.
UPDATE clause
SQL clause that updates data in a table.
UTC_DATE function
Returns current UTC date.
UTC_time function
Returns current UTC time.
VIEWS
A SQL view is a SELECT statement that is stored as a database object.
WHERE function
Specifies any conditions for the results set (filter).
147
This content is provided to you freely by BYU-I Books.
148
Index
aggregate functions
Using the HAVING Clause
1. Filtering aggregate functions With The HAVING Clause
Aggregate Functions
1. aggregate functions
2. Table 1. aggregate functions List
and
The DELETE Clause
1. … WHERE name = 'san felipe' and countrycode = 'chl';
2. WHERE name = 'san felipe' and countrycode = 'chl';
Grouping Data
1. Filtering With WHERE and HAVING
149
Using the HAVING and WHERE Clauses Together
1. … that includes both the HAVING and WHERE clause in the same SQL statement.
Introduction
1. … databases that you can download and install in your local MySQL instance.…
2. … will include SQL design basics and guidance on how to install MySQL and MySQL…
Arithmetic Operators
1. Table 4. Operators and precedence order
Date Functions
1. * Returns current local date and time.
String Functions
1. LOCATE(), and LENGTH() accept a string but return an integer. • SUBSTRING()…
150
arithmetic operators
How to Retrieve Data From a Single Table
1. arithmetic operators
Arithmetic Operators
1. arithmetic operators
avg
Simple GROUP BY Query
1. USE bike;SELECT category_id, avg(list_price)FROM productGROUP BY category_id
2. SELECT category_id, avg(list_price):
Aggregate Functions
1. USE bike;SELECT avg(list_price), SUM(list_price), MIN(list_price), …
2. avg([DISTINCT] column_values)
between
How to Retrieve Data From a Single Table
1. between Operators
2. … IndepYearFROM countryWHERE name between "Aruba" and "Bahamas";
151
ceiling
Numeric Functions
1. FLOOR, ceiling, TRUNCATE
2. … list_price, FLOOR(list_price), ceiling(list_price), TRUNCATE(list_price,…
3. ceiling(number)
4. ceiling(6.2)
5. Table 6. FLOOR, ceiling, TRUNCATE functions
column
How to Retrieve Data From a Single Table
1. column Aliases
2. Show all columns
3. Comma separated list of column names
4. … previous example, we created a new column that was a calculated value. The problem…
5. column Name
6. Table 1. column Specifications
7. … then in quotes we put the new column alias of “People per square mile.”…
Column Specifications
1. column Specifications
2. Show all columns
3. column Name
4. Comma separated list of column names
5. column Specifications
Column Aliases
1. column Aliases
2. … previous example, we created a new column that was a calculated value. The problem…
3. … then in quotes we put the new column alias of “People per square mile.”…
152
Grouping Data
1. … rows of a result set based on columns or expressions separated by commas.
Aggregate Functions
1. SUM([DISTINCT] column_values)
2. MIN([DISTINCT] column_values)
3. The average of the non-null columns in the expression
4. MAX([DISTINCT] column_values)
5. COUNT([DISTINCT] column_values)
6. … highest value of the non-null columns in the expression
7. AVG([DISTINCT] column_values)
8. The total of the non-null columns in the expression
9. … lowest value off the non-null columns in the expression
10. The number of the non-null columns in the expression
column aliases
How to Retrieve Data From a Single Table
1. column aliases
Column Aliases
1. column aliases
column specifications
How to Retrieve Data From a Single Table
1. Table 1. column specifications
Column Specifications
1. column specifications
2. column specifications
comparison operators
How to Retrieve Data From a Single Table
1. comparison operators
2. Table 5. comparison operators
153
Comparison Operators
1. comparison operators
2. Table 5. comparison operators
concat
String Functions
1. concat
2. USE world;SELECT concat(name, ', ', continent)FROM country;
count
The INSERT Clause With a Column List
1. (name, countryCode, district, population)
2. … INTO city 3 (name, countryCode, district, population) 4 VALUES 5…
154
Benefits of Using Views
1. USE WORLD;CREATE VIEW city_country ASSELECT ci.name AS city_name, co.name AS…
2. CREATE VIEW city_country AS
3. … ci.name AS city_name, co.name AS country_name
4. JOIN country co
5. ON ci.countryCode = co.Code;
6. Results by selecting from the city_country view:
Aggregate Functions
1. count(*)
2. … MIN(list_price), MAX(list_price), count(list_price), count(*)FROM product;
3. count([DISTINCT] column_values)
Arithmetic Operators
1. … "People per square mile"FROM country;
Column Aliases
1. … “People per square mile”FROM country;
Comparison Operators
1. … world;SELECT name, populationFROM countryWHERE population > 1000000;
155
IS NULL, BETWEEN, IN Operators
1. USE world;SELECT nameFROM countryWHERE name IN ('Aruba', 'Barbados', 'Cuba',…
2. SELECT name, IndepYearFROM countryWHERE IndepYear IS NULL;
3. … world;SELECT name, IndepYearFROM countryWHERE name BETWEEN "Aruba" and "Bahamas";
DISTINCT Clause
1. … DISTINCT continent, nameFROM countryORDER BY continent;
Date Functions
1. … DATE_FORMAT('2020-01-28', '%m/%d/%y')FROM country;
Numeric Functions
1. … ROUND(LifeExpectancy) FROM world.country;
String Functions
1. … CONCAT(name, ', ', continent)FROM country;
156
current_date
Date Functions
1. current_date()
2. current_date
3. … DATE('2020-01-01') AS 'DATE(), date only', current_date AS 'current_date', CURRENT_TIME…
current_time
Date Functions
1. current_time
2. … CURRENT_DATE AS 'CURRENT_DATE', current_time AS 'current_time', UTC_DATE…
3. current_time()
157
date
Date Functions
1. date_FORMAT
2. date_ADD
3. dateDIFF
4. Current date/Time Functions
5. date, dateTIME
6. Table 1. Current date Functions
7. CURRENT_date()
8. date
9. date(date)
10. CURRENT_date
11. Table 3. date_FORMAT Function
12. * Returns current local date
13. date_FORMAT
14. date/time
15. Table 2. date_ADD Function
16. date
17. SELECT NOW() AS 'NOW()', date('2020-01-01') AS 'date(), date only', …
18. • dates must be enclosed in quotes • You can pass a date or dateTIME datatype…
19. SELECT dateDIFF('2018-01-01', '2019-01-01') AS 'date Difference';
20. * extracts the date from input. If time is included, the time is dropped.
21. date_FORMAT(‘2020-09-03’, ‘%m/%d/%y’)
22. … world;SELECT name, continent, date_FORMAT('2020-01-28', '%m/%d/%y')FROM country;
23. * Returns current local date and time.
24. date/time
25. USE bike;SELECT order_date, date_ADD(order_date, INTERVAL 1 DAY) AS 'ORDER…
26. * Returns current UTC date.
27. date
28. date('2020-01-01 11:31:31')
29. date_ADD(date, interval expression unit)
30. * Returns current UTC date.
31. UTC_date()
32. UTC_date
33. date_ADD(‘2020-01-01’, INTERVAL 1 DAY)
34. • Returns a date with a date or dateTIME value equal to the original value…
158
The Subquery In a Delete Statement
1. … Before you can run a DELETE or UPdate statement without a WHERE clause, you…
Aggregate Functions
1. numeric, date, string
2. numeric, date, string
delete
The DELETE Clause
1. The delete Clause
2. 1 USE world;2 delete 3 FROM city 4 WHERE name = 'san felipe'…
3. delete
distinct
Using the DISTINCT Statement
1. Removing Duplicate Values With distinct
2. … bike;SELECT COUNT(list_price), COUNT(distinct list_price) FROM product;
Aggregate Functions
1. SUM([distinct] column_values)
2. MIN([distinct] column_values)
3. MAX([distinct] column_values)
4. COUNT([distinct] column_values)
5. AVG([distinct] column_values)
159
DISTINCT Clause
1. distinct Keyword
2. distinct
3. Table 7. distinct Keyword
4. SELECT distinct continent, nameFROM countryORDER BY continent;
floor
Numeric Functions
1. floor, CEILING, TRUNCATE
2. floor(7.7)
3. USE bike;SELECT list_price, floor(list_price), CEILING(list_price), TRUNCATE(list_price,…
4. floor(number)
5. Table 6. floor, CEILING, TRUNCATE functions
group by
Grouping Data
1. Using the group by Clause
2. Table 1. group by Function
3. group by
having
Grouping Data
1. Filtering With WHERE And having
160
Using the HAVING Clause
1. … Aggregate Functions With The having Clause
2. having AVG(list_price) > 1000
3. … AVG(list_price)FROM productGROUP BY category_idhaving AVG(list_price) > 1000
4. … so we will focus solely on the having clause.
in
The INSERT Clause With a Column List
1. The inSERT Clause With a Column List
2. Below is a basic example of an inSERT statement with a column list:
3. inSERT inTO city
4. Results of the insert:
5. 1 USE world;2 inSERT inTO city 3 (name, countryCode,…
Grouping Data
1. Filtering With WHERE And HAVinG
2. Using the GROUP BY Clause
161
Using the DISTINCT Statement
1. Removing Duplicate Values With DISTinCT
2. … COUNT(list_price), COUNT(DISTinCT list_price) FROM product;
Aggregate Functions
1. SUM([DISTinCT] column_values)
2. Min([DISTinCT] column_values)
3. … average of the non-null columns in the expression
4. … AVG(list_price), SUM(list_price), Min(list_price), MAX(list_price),…
5. MAX([DISTinCT] column_values)
6. COUNT([DISTinCT] column_values)
7. … value of the non-null columns in the expression
8. numeric, date, string
9. AVG([DISTinCT] column_values)
10. … total of the non-null columns in the expression
11. numeric, date, string
12. … value off the non-null columns in the expression
13. … number of the non-null columns in the expression
162
The Subquery In a SELECT Statement
1. The Subquery in a SELECT Statement
2. WHERE CountryCode in
3. … city 4 WHERE CountryCode in 5 (SELECT code 6 …
Introduction
1. Before You Begin
2. … databases that you can download and install in your local MySQL instance.…
3. in a future edition, this book will include SQL design basics and guidance…
163
LIKE and REGEXP Operators
1. Matches any single character within the given range.
2. Matches any single character listed within the brackets.
3. Match the pattern to the beginning of the value being tested.
4. Match any string of characters to the left of the symbol
5. Separates two string patterns and matches either one
6. Matches any single character.
7. … pattern to the end of the value being tested.
8. Match a single character
Arithmetic Operators
1. integer Division
2. Modulo (remainder)
Column Aliases
1. in the previous example, we created a new column that was a calculated value.…
2. We used the AS keyword then in quotes we put the new column alias of “People…
DISTINCT Clause
1. DISTinCT Keyword
2. DISTinCT
3. Eliminates duplicate rows
4. Table 7. DISTinCT Keyword
5. SELECT DISTinCT continent, nameFROM countryORDER BY continent;
164
Joining More Than Two Tables
1. How to Join More than Two Tables
2. JOin countrylanguage cl.
3. … FROM city ci6 JOin country co 7 ON ci.CountryCode…
Date Functions
1. • Dates must be enclosed in quotes • You can pass a DATE or DATETIME…
2. * extracts the date from input. If time is included, the time is dropped.
3. USE world;SELECT name, continent, DATE_FORMAT('2020-01-28', '%m/%d/%y')FROM…
4. Minutes, numeric (00..59)
5. … order_date, DATE_ADD(order_date, inTERVAL 1 DAY) AS 'ORDER DATE PLUS…
6. DATE_ADD(date, interval expression unit)
7. DATE_ADD(‘2020-01-01’, inTERVAL 1 DAY)
8. … DATETIME value equal to the original value plus the specified interval.
Numeric Functions
1. FLOOR, CEILinG, TRUNCATE
2. … list_price, FLOOR(list_price), CEILinG(list_price), TRUNCATE(list_price,…
3. CEILinG(number)
4. CEILinG(6.2)
5. Table 6. FLOOR, CEILinG, TRUNCATE functions
165
String Functions
1. LOCATE, LENGTH, SUBSTRinG
2. string
3. SUBSTRinG(str,start[,length])
4. string
5. string
6. LEFT(string, num. characters)
7. TRIM(string)
8. string
9. … world;SELECT CONCAT(name, ', ', continent)FROM country;
10. string
11. LTRIM(string)
12. string
13. string
14. RIGHT(string, num. characters)
15. … LENGTH('salmon'), SUBSTRinG('salmon',3,999);
16. Table 9. LOCATE. LENGTH, SUBSTRinG functions
17. LOCATE(find,search[,start])
18. string
19. LOWER(string)
20. SUBSTRinG('salmon',3,999)
21. string
22. string
23. LOCATE(), and LENGTH() accept a string but return an integer. • SUBSTRinG()…
24. RTRIM(string)
25. string
26. UPPER(string)
index
SQL Indexes Explained
1. When to Create an index
2. SQL indexes
indexes
Clustered vs. Non-clustered Indexes
1. Clustered vs. Non-clustered indexes
166
insert
The INSERT Clause With a Column List
1. The insert Clause With a Column List
2. Below is a basic example of an insert statement with a column list:
3. insert INTO city
4. Results of the insert:
5. 1 USE world;2 insert INTO city 3 (name, countryCode, district,…
is null
How to Retrieve Data From a Single Table
1. is null
2. … IndepYearFROM countryWHERE IndepYear is null;
join
The JOIN Clause
1. The join Clause
2. … more succinctly with an inner join clause using table aliases. Instead of…
3. join country co
4. … a SQL statement with an inner join clause using explicit syntax.
5. … FROM country 6 join city 5 ON city.CountryCode…
6. The results of the join query would yield the same results as shown below whether…
7. … FROM city ci 5 join country co 6 ON ci.CountryCode…
167
Improving the GROUP BY Query
1. … List Price'FROM product p join category c ON p.category_id = c.category_idGROUP…
2. join category c
left
String Functions
1. … bike;SELECT category_name, left(category_name, 8) AS 'First 8 Characters', …
2. left(‘Salmon’, 3)
String Functions
1. RIGHT, left
2. left(string, num. characters)
3. left(‘Salmon ‘)
4. SELECT LTRIM(' Salmon ') AS "left Trim", RTRIM(' Salmon ') AS…
5. Table 7. RIGHT, left functions
like
How to Retrieve Data From a Single Table
1. like and REGEXP Operators
2. like Symbol
3. Table 2. like Keyword
4. … world;SELECT nameFROM countryWHERE name like ‘A%’
168
limit
How to Retrieve Data From a Single Table
1. limit 5;
logical operators
How to Retrieve Data From a Single Table
1. AND, OR, NOT logical operators
2. Table 6. logical operators
ltrim
String Functions
1. TRIM, ltrim, RTRIM
2. ltrim(string)
3. SELECT ltrim(' Salmon ') AS "Left Trim", RTRIM(' Salmon ') AS "Right…
min
Aggregate Functions
1. min([DISTINCT] column_values)
2. … AVG(list_price), SUM(list_price), min(list_price), MAX(list_price),…
DISTINCT Clause
1. Eliminates duplicate rows
Date Functions
1. minutes, numeric (00..59)
169
now
How to Retrieve Data From a Single Table
1. … is that the column header is now population / SurfaceArea. However we can…
Column Aliases
1. … is that the column header is now population / SurfaceArea. However, we can…
Date Functions
1. now()
2. SELECT now() AS 'now()', DATE('2020-01-01') AS 'DATE(), date only', …
3. now()
null
How to Retrieve Data From a Single Table
1. IS null
2. … IndepYearFROM countryWHERE IndepYear IS null;
Aggregate Functions
1. The average of the non-null columns in the expression
2. The highest value of the non-null columns in the expression
3. The total of the non-null columns in the expression
4. The lowest value off the non-null columns in the expression
5. The number of the non-null columns in the expression
or not
The JOIN Clause
1. … results as shown below whether or not table names are completely written out…
order by
How to Retrieve Data From a Single Table
1. … 'Barbados', 'Cuba', 'Bahamas')order by population ASC;
2. order by name
3. … 'caribbean'AND population > 100000order by population ASC;
4. … DISTINCT continent, nameFROM countryorder by continent;
170
The Five Clauses of the SELECT Statement
1. … CountryCode = “AFG”5 order by name6 LIMIT 3
2. order by name
DISTINCT Clause
1. … DISTINCT continent, nameFROM countryorder by continent;
outer join
The OUTER JOIN Clause
1. The outer join Clause
2. … snippet of a SQL statement with an outer join clause.
regexp
How to Retrieve Data From a Single Table
1. LIKE and regexp Operators
2. … world;SELECT nameFROM countryWHERE name regexp 'g[o,u]';
3. regexp Characters
171
right
String Functions
1. right, LEFT
2. right(string, num. characters)
3. right(‘Salmon’, 3)
4. right(‘ Salmon‘)
5. … RTRIM(' Salmon ') AS "right Trim", TRIM(' Salmon ') AS "Trim";
6. Table 7. right, LEFT functions
7. … AS 'First 8 Characters', right(category_name, 8) AS 'Last 8 Characters'FROM…
round
Improving the GROUP BY Query
1. … category_name, CONCAT('$', round(AVG(list_price),2)) AS 'Average List…
2. CONCAT('$', round(AVG(list_price),2)) AS 'Average List Price'
Numeric Functions
1. round
2. Table 5. round function
3. round(13.37, 1)
4. … world;SELECT name, LifeExpectancy, round(LifeExpectancy) FROM world.country;
5. round(number[, length])
rtrim
String Functions
1. TRIM, LTRIM, rtrim
2. … Salmon ') AS "Left Trim", rtrim(' Salmon ') AS "Right Trim", …
3. rtrim(string)
select
String Functions
1. select UPPER('Salmon'), LOWER('Salmon');
2. USE world;select CONCAT(name, ', ', continent)FROM country;
3. select FORMAT(list_price,2) FROM bike.product;
4. select LOCATE('al','salmon',1), LENGTH('salmon'), SUBSTRING('salmon',3,999);
5. select LTRIM(' Salmon ') AS "Left Trim", RTRIM(' Salmon ') AS "Right…
6. USE bike;select category_name, LEFT(category_name, 8) AS 'First 8 Characters', …
172
Improving the GROUP BY Query
1. USE bike;select category_name, CONCAT('$', ROUND(AVG(list_price),2)) AS…
2. select category_name,
Aggregate Functions
1. USE bike;select AVG(list_price), SUM(list_price), MIN(list_price), MAX(list_price),…
173
How to Retrieve Data From a Single Table
1. The Five Clauses of the select statement
2. USE world;select nameFROM countryWHERE name IN ('Aruba', 'Barbados', 'Cuba',…
3. select name, population / SurfaceArea AS “People per square mile”FROM…
4. select name, IndepYearFROM countryWHERE IndepYear IS NULL;
5. USE world;select nameFROM countryWHERE name REGEXP 'g[o,u]';
6. USE world;select name, populationFROM countryWHERE population > 1000000;
7. USE world;select name, populationFROM countryWHERE region = 'caribbean'AND population…
8. USE world;select name, population / SurfaceAreaAS "People per square mile"FROM…
9. USE world;select name, IndepYearFROM countryWHERE name BETWEEN "Aruba" and "Bahamas";
10. select name
11. select DISTINCT continent, nameFROM countryORDER BY continent;
12. USE world;select nameFROM countryWHERE name LIKE ‘A%’
Arithmetic Operators
1. USE world;select name, population / SurfaceAreaAS "People per square mile"FROM…
Column Aliases
1. select name, population / SurfaceArea AS “People per square mile”FROM…
Comparison Operators
1. USE world;select name, populationFROM countryWHERE population > 1000000;
DISTINCT Clause
1. select DISTINCT continent, nameFROM countryORDER BY continent;
174
The JOIN Clause
1. select ci.name AS “City Name”, co.name AS “Country Name”
2. 1 USE world;2 select city.name AS "City Name", 3 country.name…
3. … clause and referenced in the select and ON clause:
4. 1 USE world;2 select ci.name AS "City Name", 3 co.name…
Date Functions
1. select NOW() AS 'NOW()', DATE('2020-01-01') AS 'DATE(), date only', CURRENT_DATE…
2. select DATEDIFF('2018-01-01', '2019-01-01') AS 'Date Difference';
3. USE world;select name, continent, DATE_FORMAT('2020-01-28', '%m/%d/%y')FROM country;
4. USE bike;select order_date, DATE_ADD(order_date, INTERVAL 1 DAY) AS 'ORDER…
Numeric Functions
1. USE bike;select list_price, FLOOR(list_price), CEILING(list_price), TRUNCATE(list_price,…
2. USE world;select name, LifeExpectancy, ROUND(LifeExpectancy) FROM world.country;
sql indexes
SQL Indexes Explained
1. sql indexes
sql view
SQL View Explained
1. sql views
sql views
SQL View Explained
1. sql views
175
subquery
The Subquery in an UPDATE statement
1. The subquery in an UPDATE statement
sum
Aggregate Functions
1. sum([DISTINCT] column_values)
2. … bike;SELECT AVG(list_price), sum(list_price), MIN(list_price), MAX(list_price),…
trim
String Functions
1. trim, Ltrim, Rtrim
2. trim(string)
3. trim(‘ Salmon ‘)
4. Ltrim(string)
5. Table 8. trim functions
6. SELECT Ltrim(' Salmon ') AS "Left trim", Rtrim(' Salmon ') AS…
7. Rtrim(string)
truncate
Numeric Functions
1. FLOOR, CEILING, truncate
2. truncate(7.9)
3. … FLOOR(list_price), CEILING(list_price), truncate(list_price, 0)FROM product;
4. Table 6. FLOOR, CEILING, truncate functions
5. truncate(NUMBER, length)
union
How to Code a UNION
1. How to Code a union
2. union
3. … city WHERE CountryCode = 'AUS'4 union5 SELECT name, population6 FROM country7…
176
update
The UPDATE Clause With a Column List
1. The update Clause
2. update city
3. 1 USE world; 2 update city 3 SET Population = 65000, district…
utc_date
Date Functions
1. … CURRENT_TIME AS 'CURRENT_TIME', utc_date AS 'utc_date', UTC_TIME AS…
2. utc_date()
3. utc_date
utc_time
Date Functions
1. utc_time
2. utc_time()
3. … UTC_DATE AS 'UTC_DATE', utc_time AS 'utc_time';
view
Benefits of Using Views
1. Benefits of Using views
2. USE WORLD;CREATE view city_country ASSELECT ci.name AS city_name, co.name AS…
3. CREATE view city_country AS
4. … selecting from the city_country view:
177
views
Benefits of Using Views
1. Benefits of Using views
where
The DELETE Clause
1. … DELETE 3 FROM city 4 where name = 'san felipe' AND countrycode…
2. where name = 'san felipe' AND countrycode = 'chl';
Grouping Data
1. Filtering With where And HAVING
178
How to Retrieve Data From a Single Table
1. … world;SELECT nameFROM countrywhere name IN ('Aruba', 'Barbados', 'Cuba', 'Bahamas')ORDER…
2. SELECT name, IndepYearFROM countrywhere IndepYear IS NULL;
3. … world;SELECT nameFROM countrywhere name REGEXP 'g[o,u]';
4. … world;SELECT name, populationFROM countrywhere population > 1000000;
5. … world;SELECT name, populationFROM countrywhere region = 'caribbean'AND population…
6. … world;SELECT name, IndepYearFROM countrywhere name BETWEEN "Aruba" and "Bahamas";
7. … world;SELECT nameFROM countrywhere name LIKE ‘A%’
Comparison Operators
1. … world;SELECT name, populationFROM countrywhere population > 1000000;
Date Functions
1. Year for the week where Sunday is the first day of the week, numeric, four digits;…
2. Week (01..53), where Sunday is the first day of the week; WEEK() mode 2; used…
3. Week (00..53), where Sunday is the first day of the week; WEEK() mode 0
4. Week (00..53), where Monday is the first day of the week; WEEK() mode 1
5. Week (01..53), where Monday is the first day of the week; WEEK() mode 3; used…
6. Year for the week, where Monday is the first day of the week, numeric, four…
179
This content is provided to you freely by BYU-I Books.
180