SlideShare a Scribd company logo
Distributed Database Systems
INF413
Querying for Data
Using SELECT to Retrieve Data
• The SELECT statement retrieves information from one or more tables. Retrievals
tend to be the most common database operation, so it's important to understand
how SELECT works and what you can do with it.
SELECT values_to_display
FROM table_name
WHERE expression
GROUP BY how_to_group
HAVING expression
ORDER BY how_to_sort
LIMIT row_count;
The syntax shown here is simplified from the full SELECT syntax, which includes
additional clauses
MySQL 5 Certification Study Guide 2
Querying for Data
• To indicate what values to retrieve, name them following the SELECT keyword.
mysql> SELECT 2+2, REPEAT('x',5), DATE_ADD('2001-01-01',INTERVAL 7 DAY), 1/0;
+-----+--------------------+----------------------------------------------------------+------+
| 2+2 | REPEAT('x',5) | DATE_ADD('2001-01-01',INTERVAL 7 DAY) | 1/0 |
+-----+--------------------+----------------------------------------------------------+------+
| 4 | xxxxx | 2001-01-08 | NULL |
+-----+--------------------+----------------------------------------------------------+------+
mysql> DESCRIBE City;
+-------------+----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
| ID | int(11) | NO | PRI | NULL | auto_increment |
| Name | char(35) | NO | | | |
| CountryCode | char(3) | NO | | | |
| District | char(20) | NO | | | |
| Population | int(11) | NO | | 0 | |
+-------------+----------+------+-----+---------+----------------+
MySQL 5 Certification Study Guide 3
Querying for Data
• To retrieve the contents of these columns, write the SELECT statement as follows:
SELECT ID, Name, CountryCode, District, Population FROM City;
SELECT * FROM City;
• Output column names, by default, are the same as the column or expression
selected. To rename a column, provide an alias following the column in the output list:
mysql> SELECT 1 AS One, 4*3 'Four Times Three';
+------+------------------------+
| One | Four Times Three |
+------+------------------------+
| 1 | 12 |
+------+------------------------+
• Columns aliases are used as follows:
– The keyword AS is optional.
– An alias may be quoted. If it consists of multiple words, it must be quoted.
• To specify a database explicitly in the SELECT statement itself, qualify the table
name. That is, precede the table name with the database name and a period:
SELECT * FROM world.Country;
MySQL 5 Certification Study Guide 4
Querying for Data
Specifying Which Rows to Retrieve
• A WHERE clause can be as simple or complex as necessary to identify the rows that
are relevant for your purposes.
– SELECT * FROM Country WHERE IndepYear > 1990;
– SELECT * FROM Country
WHERE Population >= 1000000 AND Population <= 2000000;
– SELECT * FROM Country
WHERE Population BETWEEN 1000000 AND 2000000;
• Some operators have higher precedence than others. For example, AND has a
higher precedence than OR.
WHERE GNP < 1000 AND Continent = 'Africa' OR Continent = 'Asia‘
Using ORDER BY to Sort Query Results
By default, the rows in the result set produced by a SELECT statement are returned by
the server to the client in no particular order. When you issue a query, the server is free
to return the rows in any convenient order. This order can be affected by factors such as
the order in which rows are actually stored in the table or which indexes are used to
process the query. If you require output rows to be returned in a specific order, include
an ORDER BY clause that indicates how to sort the results.
MySQL 5 Certification Study Guide 5
Querying for Data
mysql> SELECT id, last_name, first_name, birth FROM t ORDER BY birth;
+------+-----------+------------+-----------------+
| id | last_name | first_name | birth |
+------+-----------+-------------+----------------+
| 2 | Larsson | Sven | 1965-01-03 |
| 4 | Larsson | Selma | 1968-05-29 |
| 3 | Brown | Betty | 1971-07-12 |
| 1 | Brown | Bill | 1972-10-14 |
+------+-----------+-------------+----------------+
mysql> SELECT id, last_name, first_name, birth FROM t ORDER BY last_name, first_name;
+------+-----------+------------+------------+
| id | last_name | first_name | birth |
+------+-----------+------------+------------+
| 3 | Brown | Betty | 1971-07-12 |
| 1 | Brown | Bill | 1972-10-14 |
| 4 | Larsson | Selma | 1968-05-29 |
| 2 | Larsson | Sven | 1965-01-03 |
+------+-----------+------------+------------+
MySQL 5 Certification Study Guide 6
Querying for Data
• By default, ORDER BY sorts values in ascending order (smallest to largest).
ORDER BY last_name, first_name
ORDER BY last_name ASC, first_name ASC
To sort values in descending order (largest to smallest), follow the sort column name with
DESC:
mysql> SELECT id, last_name, first_name, birth FROM t ORDER BY id DESC;
+------+-----------+------------+------------+
| id | last_name | first_name | birth |
+------+-----------+------------+------------+
| 4 | Larsson | Selma | 1968-05-29 |
| 3 | Brown | Betty | 1971-07-12 |
| 2 | Larsson | Sven | 1965-01-03 |
| 1 | Brown | Bill | 1972-10-14 |
+------+-----------+------------+------------+
MySQL 5 Certification Study Guide 7
Querying for Data
• ORDER BY typically refers to table columns by name:
SELECT last_name, first_name FROM t ORDER BY last_name, first_name;
• However, it's possible to refer to columns in other ways. If a column is given an alias
in the output column list, you should refer to that column in the ORDER BY column by
its alias:
SELECT last_name AS last, first_name AS first FROM t ORDER BY last, first;
• Or you can specify a number corresponding to the column's position in the column
output list (1 for the first output column, 2 for the second, and so forth) :
SELECT last_name, first_name FROM t ORDER BY 1, 2;
• It's possible to perform a sort using an expression result.
SELECT id, last_name, first_name, MONTH(birth)
FROM t ORDER BY MONTH(birth);
• Output sorting can be based on values that don't appear in the output at all.
mysql> SELECT id, last_name, first_name, MONTHNAME(birth) FROM t ORDER BY
MONTH(birth);
MySQL 5 Certification Study Guide 8
Querying for Data
Character Sets and Collations in General
• A character set is a set of symbols and encodings. A collation is a set of rules
for comparing characters in a character set. Let's make the distinction clear with
an example of an imaginary character set.
• Suppose that we have an alphabet with four letters: “A”, “B”, “a”, “b”. We give
each letter a number: “A” = 0, “B” = 1, “a” = 2, “b” = 3. The letter “A” is a symbol,
the number 0 is the encoding for “A”, and the combination of all four letters and
their encodings is a character set.
mysql> SHOW CHARACTER SET;
mysql> SHOW COLLATION;
The Natural Sort Order of String
The sort order for a string column that has a data type other than ENUM or SET
depends on whether the column contains non-binary or binary values. Non-binary
strings sort in the order defined by their collation. This order can be case sensitive or
not, depending on the collation. Binary strings sort based on the numeric values of
the bytes contained in the strings. For example, assume that a table t has a CHAR
column c that has the latin1 character set and that contains the following values:
mysql> SELECT c FROM t;
MySQL 5 Certification Study Guide 9
Querying for Data
• A CHAR column is non-binary, so its contents sort according to the column's
collation. If the collation is not case sensitive, values sort lexically without regard
to lettercase:
mysql> SELECT c FROM t ORDER BY c;
• Notice that the results come out in letter order, but the rows for a given letter are
not further sorted by lettercase.
• If the collation is case sensitive, lettercase becomes significant. You can force a
string column sort to be case sensitive by using the COLLATE operator with a
case-sensitive collation:
mysql> SELECT c FROM t ORDER BY c COLLATE latin1_general_cs;
MySQL 5 Certification Study Guide 10
Querying for Data
• If the collation is binary, numeric character values are the determining factor:
mysql> SELECT c FROM t ORDER BY c COLLATE latin1_bin;
• The sort order for members of an ENUM or SET column is based on their
internal numeric values. These values correspond to the order in which the
enumeration or set members are listed in the column definition. Suppose that a
table t contains a column mon that is an ENUM listing abbreviations for months
of the year:
CREATE TABLE t
( mon ENUM('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'));
• Assume that table t has 12 rows, one for each of the possible enumeration
values. When you sort this column, the values come out in month-of-year order:
mysql> SELECT mon FROM t ORDER BY mon;
MySQL 5 Certification Study Guide 11
Querying for Data
• This occurs because 'Jan' through 'Dec' are assigned internal values 1 through 12
based on their order in the column definition, and those values determine the sort
order. To produce a lexical string sort instead, use CAST() to convert the
enumeration values to CHAR values:
mysql> SELECT mon FROM t ORDER BY CAST(mon AS CHAR);
• SET columns also sort using the internal values of the set's legal members. The
ordering is more complex than with ENUM because values may consist of
multiple SET members. For example, the following SET column contains three
members:
CREATE TABLE t (hue SET('red','green','blue'));
• Assume that t contains the following rows:
mysql> SELECT hue FROM t;
The SET members 'red', 'green', and 'blue' have internal values of 1, 2,
and 4, respectively. Thus, the rows of the table have internal numeric
values of 1+2 = 3, 1+2+4 = 7, 1+4 = 5, and 2+4 = 6. An ORDER BY
on the column sorts using those numeric values:
mysql> SELECT hue FROM t ORDER BY hue;
MySQL 5 Certification Study Guide 12
Querying for Data
• As with ENUM, SET values can be sorted lexically by using CAST() to convert
them to strings:
mysql> SELECT hue FROM t ORDER BY CAST(hue AS CHAR);
+----------------+
| hue |
+----------------+
| green,blue |
| red,blue |
| red,green |
| red,green,blue |
+----------------+
• NULL values in a column sort together at the beginning for ascending sorts and at
the end for descending sorts.
MySQL 5 Certification Study Guide 13
Querying for Data
Limiting a Selection Using LIMIT
• MySQL supports a LIMIT clause in SELECT statements, which tells the server to
return only some of the rows selected by the statement.
SELECT * FROM Country LIMIT 10;
SELECT * FROM Country LIMIT 20,10;
SELECT * FROM t ORDER BY id LIMIT 1;
SELECT * FROM t ORDER BY id DESC LIMIT 1;
• The two-argument form of LIMIT is useful in conjunction with ORDER BY for situations
in which you want to process successive sections of a result set. For example, in Web
applications, it's common to display the result of a large search across a series of
pages that each present one section of the result. To retrieve sections of the search
result this way, issue a series of statements that all specify the same number of rows
to return in the LIMIT clause, but vary the number of initial rows to skip:
SELECT * FROM t ORDER BY id LIMIT 0, 20;
SELECT * FROM t ORDER BY id LIMIT 20, 20;
SELECT * FROM t ORDER BY id LIMIT 40, 20;
SELECT * FROM t ORDER BY id LIMIT 60, 20;
...
MySQL 5 Certification Study Guide 14
Querying for Data
Using DISTINCT to Eliminate Duplicates
• Suppose that a query returns a result set that contains duplicated rows:
mysql> SELECT last_name FROM t;
• Adding DISTINCT removes the duplicates and returns only unique rows:
mysql> SELECT DISTINCT last_name FROM t;
• DISTINCT treats all NULL values within a given column as having
the same value. Suppose that a table t contains the following rows:
mysql> SELECT i, j FROM t;
• Adding DISTINCT to the query eliminates one of them
as a duplicate:
mysql> SELECT DISTINCT i, j FROM t;
+------+------+
| i | j |
+------+------+
| 1 | 2 |
| 1 | NULL |
+------+------+
MySQL 5 Certification Study Guide 15
Querying for Data
Aggregating Results
• Functions such as AVG() that calculate summary values for groups are known as
"aggregate" functions because they're based on aggregates or groups of values.
There are several types of aggregate functions. Those discussed here are as follows:
– MIN() and MAX() find smallest and largest values.
– SUM() and AVG() summarize numeric values to produce sums (totals) and averages.
– COUNT() counts rows, values, or the number of distinct values.
– GROUP_CONCAT() concatenates a set of strings to produce a single string value.
The MIN() and MAX() Aggregate Functions
mysql> SELECT MIN(Population), MAX(Population) FROM Country;
+-----------------+-----------------+
| MIN(Population) | MAX(Population) |
+-----------------+-----------------+
| 0 | 1277558000 |
+-----------------+-----------------+
mysql> SELECT MIN(Name), MAX(Name) FROM Country;
+-------------+-----------+
| MIN(Name) | MAX(Name) |
+-------------+-----------+
| Afghanistan | Zimbabwe |
+-------------+-----------+
MySQL 5 Certification Study Guide 16
Querying for Data
• For string values, the behavior of MIN() and MAX() depends on whether the
strings are non-binary or binary. Consider a table t that contains the following
string values: , its values are compared using the numeric values of the bytes in
the strings. If ‘C’ has a smaller numeric value
• ‘a’ (as is true if characters are stored using ASCII codes), MAX(name)returns
‘alex’:
mysql> SELECT name FROM t;
mysql> SELECT MAX(name) FROM t;
mysql> ALTER TABLE t MODIFY name BINARY(20);
mysql> SELECT MAX(name) FROM t;
• MIN() and MAX() ignore NULL values. MySQL 5 Certification Study Guide 17
Querying for Data
The COUNT() Aggregate Function
• The COUNT() function can be used in several ways to count either
rows or values.
mysql> SELECT i, j FROM t;
• COUNT(expression) counts the number of non-NULL values of the
given expression. It's common for expression to be a column name, in
which case COUNT() counts the number of non-NULL values in the
column:
mysql> SELECT COUNT(i), COUNT(j) FROM t;
mysql> SELECT COUNT(DISTINCT i), COUNT(DISTINCT j) FROM t;
+-------------------+-------------------+
| COUNT(DISTINCT i) | COUNT(DISTINCT j) |
+-------------------+-------------------+
| 1 | 3 |
+-------------------+-------------------+
MySQL 5 Certification Study Guide 18
Querying for Data
• It's also possible to give a list of expressions separated by commas. In this
case, COUNT() returns the number of distinct combinations of values that
contain no NULL values. The following query counts the number of distinct
rows for which neither i nor j is NULL:
mysql> SELECT COUNT(DISTINCT i, j) FROM t;
+----------------------+
| COUNT(DISTINCT i, j) |
+----------------------+
| 2 |
+----------------------+
The GROUP_CONCAT() Function
The purpose of the GROUP_CONCAT() function is to concatenate column values
into a single string.
mysql> SELECT Language FROM CountryLanguage WHERE CountryCode =
'THA';
MySQL 5 Certification Study Guide 19
Querying for Data
• To concatenate the values into a single string, use GROUP_CONCAT():
mysql> SELECT GROUP_CONCAT(Language) AS Languages
-> FROM CountryLanguage WHERE CountryCode = 'THA';
+-----------------------------------------------+
| Languages |
+-----------------------------------------------+
| Chinese,Khmer,Kuy,Lao,Malay,Thai |
+-----------------------------------------------+
• The default string separator used by GROUP_CONCAT() is ',' (comma). To
change the separator, use a SEPARATOR clause:
mysql> SELECT GROUP_CONCAT(Language SEPARATOR ' - ') AS Languages
-> FROM CountryLanguage WHERE CountryCode = 'THA';
+--------------------------------------------+
| Languages |
+--------------------------------------------+
| Chinese - Khmer - Kuy - Lao - Malay - Thai |
+--------------------------------------------+
MySQL 5 Certification Study Guide 20
Querying for Data
• GROUP_CONCAT() adds strings to the result in the order in which the
database server reads them. To change the concatenation order, add an
ORDER BY clause.
mysql> SELECT GROUP_CONCAT(Language ORDER BY Language DESC)
-> AS Languages FROM CountryLanguage WHERE CountryCode = 'THA';
+----------------------------------+
| Languages |
+----------------------------------+
| Thai,Malay,Lao,Kuy,Khmer,Chinese |
+----------------------------------+
Grouping Results
• If a query does not contain a GROUP BY clause to place rows of the result set
into groups, an aggregate function produces a result that is based on all the
selected rows. A GROUP BY clause may be added to generate a more fine-
grained summary that produces values for subgroups within a set of selected
rows.
MySQL 5 Certification Study Guide 21
Querying for Data
mysql> SELECT * FROM personnel;
+---------+--------+---------+-------------+----------+
| pers_id | name | dept_id | title | salary |
+---------+--------+---------+-------------+----------+
| 1 | Wendy | 14 | Supervisor | 38000.00 |
| 2 | Wally | 7 | Stock clerk | 28000.00 |
| 3 | Ray | 7 | Programmer | 41000.00 |
| 4 | Burton | 14 | Secretary | 32000.00 |
| 5 | Gordon | 14 | President | 78000.00 |
| 6 | Jeff | 7 | Stock clerk | 29000.00 |
| 7 | Doris | 7 | Programmer | 48000.00 |
| 8 | Daisy | 7 | Secretary | 33000.00 |
| 9 | Bea | 7 | Accountant | 40000.00 |
+---------+--------+---------+-------------+----------+
mysql> SELECT COUNT(*) FROM personnel;
MySQL 5 Certification Study Guide 22
Querying for Data
mysql> SELECT title, COUNT(*) FROM personnel GROUP BY title;
mysql> SELECT dept_id, COUNT(*) FROM personnel
-> GROUP BY dept_id;
mysql> SELECT dept_id, title, COUNT(*) FROM personnel
-> GROUP BY dept_id, title;
MySQL 5 Certification Study Guide 23
Querying for Data
Selecting Groups with HAVING
1. WHERE, if present, identifies the initial set of records to select from a table.
2. GROUP BY arranges the selected records into groups.
3. Aggregate functions compute summary values for each group.
4. HAVING identifies which groups to retrieve for the final result set.
mysql> SELECT title, salary FROM personnel WHERE dept_id = 7;
+-------------+----------+
| title | salary |
+-------------+----------+
| Stock clerk | 28000.00 |
| Programmer | 41000.00 |
| Stock clerk | 29000.00 |
| Programmer | 48000.00 |
| Secretary | 33000.00 |
| Accountant | 40000.00 |
+-------------+----------+
MySQL 5 Certification Study Guide 24
Querying for Data
mysql> SELECT title, COUNT(*), AVG(salary) FROM personnel WHERE dept_id = 7
-> GROUP BY title;
mysql> SELECT title, salary, COUNT(*), AVG(salary)
-> FROM personnel WHERE dept_id = 7
-> GROUP BY title
-> HAVING COUNT(*) > 1;
+-------------+----------+----------+--------------+
| title | salary | COUNT(*) | AVG(salary) |
+-------------+----------+----------+--------------+
| Programmer | 41000.00 | 2 | 44500.000000 |
| Stock clerk | 28000.00 | 2 | 28500.000000 |
+-------------+----------+----------+--------------+
MySQL 5 Certification Study Guide 25
Querying for Data
Using UNION
The UNION keyword enables you to concatenate the results from two or more SELECT
statements.
MySQL 5 Certification Study Guide 26
Querying for Data
String Expressions
mysql> SELECT CONCAT('abc','def',REPEAT('X',3));
+-----------------------------------+
| CONCAT('abc','def',REPEAT('X',3)) |
+-----------------------------------+
| abcdefXXX |
+-----------------------------------+
• The || operator is treated as the logical OR operator by default, but can be used for string
concatenation if you enable the PIPES_AS_CONCAT SQL mode:
mysql> SELECT 'abc' || 'def';
+----------------+
| 'abc' || 'def' |
+----------------+
| 0 |
+----------------+
mysql> SET sql_mode = 'PIPES_AS_CONCAT';
mysql> SELECT 'abc' || 'def';
+----------------+
| 'abc' || 'def' |
+----------------+
| abcdef |
+----------------+
MySQL 5 Certification Study Guide 27
Querying for Data
Case Sensitivity in String Comparisons
mysql> SELECT 'Hello' = 'hello';
+-------------------+
| 'Hello' = 'hello' |
+-------------------+
| 1 |
+-------------------+
mysql> SELECT BINARY 'Hello' = 'hello';
+--------------------------+
| BINARY 'Hello' = 'hello' |
+--------------------------+
| 0 |
+--------------------------+
• String comparison rules also apply to GROUP BY and DISTINCT operations. Suppose that t has a
column c with the following contents:
mysql> SELECT c FROM t;
MySQL 5 Certification Study Guide 28
Querying for Data
• If c is a non-binary, case-insensitive column, GROUP BY and DISTINCT do not make lettercase
distinctions:
mysql> SELECT c, COUNT(*) FROM t GROUP BY c;
+---------+----------+
| c | COUNT(*) |
+---------+----------+
| Goodbye | 2 |
| Hello | 2 |
+---------+----------+
mysql> SELECT DISTINCT c FROM t;
+---------+
| c |
+---------+
| Hello |
| Goodbye |
+---------+
MySQL 5 Certification Study Guide 29
Querying for Data
• On the other hand, if c is a BINARY column, those operations use byte values for sorting:
mysql> SELECT c, COUNT(*) FROM t GROUP BY c;
+---------+----------+
| c | COUNT(*) |
+---------+----------+
| Goodbye | 1 |
| Hello | 1 |
| goodbye | 1 |
| hello | 1 |
+---------+----------+
mysql> SELECT DISTINCT c FROM t;
+---------+
| c |
+---------+
| Hello |
| hello |
| Goodbye |
| goodbye |
+---------+
MySQL 5 Certification Study Guide 30
Querying for Data
• The UPPER() and LOWER() functions perform case conversion only if the argument is a non-
binary string.
mysql> SELECT UPPER('AbCd'), LOWER('AbCd');
+---------------+---------------+
| UPPER('AbCd') | LOWER('AbCd') |
+---------------+---------------+
| ABCD | abcd |
+---------------+---------------+
mysql> SELECT UPPER(BINARY 'AbCd'), LOWER(BINARY 'AbCd');
+----------------------+----------------------+
| UPPER(BINARY 'AbCd') | LOWER(BINARY 'AbCd') |
+----------------------+----------------------+
| AbCd | AbCd |
+----------------------+----------------------+
MySQL 5 Certification Study Guide 31
Querying for Data
Using LIKE for Pattern Matching
• Patterns used with the LIKE pattern-matching operator can contain two special characters (called
"metacharacters" or "wildcards") that stand for something other than themselves:
– The '%' character matches any sequence of zero or more characters. For example, the
pattern 'a%' matches any string that begins with 'a', '%b' matches any string that ends with
'b', and '%c%' matches any string that contains a 'c'. The pattern '%' matches any string,
including empty strings.
– The '_' (underscore) character matches any single character. 'd_g' matches strings such as
'dig', 'dog', and 'd@g'. Because '_' matches any single character, it matches itself and the
pattern 'd_g' also matches the string 'd_g'.
• LIKE evaluates to NULL if either operand is NULL, but any non-NULL literal value matches itself.
Likewise, a function call that produces a non-NULL value matches itself (with one exception).
Thus, the following expressions evaluate as true:
mysql> SELECT 'ABC' LIKE 'abc', 'ABC' LIKE BINARY 'abc';
+------------------+-------------------------+
| 'ABC' LIKE 'abc' | 'ABC' LIKE BINARY 'abc' |
+-----------------+-------------------------+
| 1 | 0 |
+------------------+-------------------------+
MySQL 5 Certification Study Guide 32
Querying for Data
• The exception is that different invocations of the RAND() random-number function might return
different values, even within the same query:
mysql> SELECT RAND(), RAND();
+------------------+------------------+
| RAND() | RAND() |
+------------------+------------------+
| 0.15430032289987 | 0.30666533979277 |
+------------------+------------------+
• As a result, the expression RAND() LIKE RAND() normally will be false.
• To invert a pattern match, use NOT LIKE rather than LIKE:
mysql> SELECT 'ABC' LIKE 'A%', 'ABC' NOT LIKE 'A%';
+-----------------+---------------------+
| 'ABC' LIKE 'A%' | 'ABC' NOT LIKE 'A%' |
+-----------------+---------------------+
| 1 | 0 |
+-----------------+---------------------+
MySQL 5 Certification Study Guide 33
Querying for Data
Functions in SQL Expressions
mysql> SELECT PI ();
+----------+
| PI () |
+----------+
| 3.141593 |
+----------+
• LEAST() and GREATEST() take a set of values as arguments and return the one that is smallest
or largest, respectively:
mysql> SELECT LEAST(4,3,8,-1,5), LEAST('cdef','ab','ghi');
+-------------------+--------------------------+
| LEAST(4,3,8,-1,5) | LEAST('cdef','ab','ghi') |
+-------------------+--------------------------+
| -1 | ab |
+-------------------+--------------------------+
mysql> SELECT GREATEST(4,3,8,-1,5), GREATEST('cdef','ab','ghi');
+----------------------+-----------------------------+
| GREATEST(4,3,8,-1,5) | GREATEST('cdef','ab','ghi') |
+----------------------+-----------------------------+
| 8 | ghi |
+----------------------+-----------------------------+
MySQL 5 Certification Study Guide 34
Querying for Data
• INTERVAL() compares the first argument to the others and returns a value to indicate how many
of them are less than or equal to it.
mysql> SELECT INTERVAL(2,1,2,3,4);
+---------------------+
| INTERVAL(2,1,2,3,4) |
+---------------------+
| 2 |
+---------------------+
mysql> SELECT INTERVAL(0,1,2,3,4);
+---------------------+
| INTERVAL(0,1,2,3,4) |
+---------------------+
| 0 |
+--------------------+
mysql> SELECT INTERVAL(6.3,2,4,6,8,10);
+--------------------------+
| INTERVAL(6.3,2,4,6,8,10) |
+--------------------------+
| 3 |
+--------------------------+
MySQL 5 Certification Study Guide 35
Querying for Data
Control Flow Functions
mysql> SELECT IF(1 > 0, 'yes','no');
+-----------------------+
| IF(1 > 0, 'yes','no') |
+-----------------------+
| yes |
+-----------------------+
• The CASE construct is not a function, but it too provides flow control. It has two forms of syntax.
The first looks like this:
mysql> SET @val = 1;
mysql> SELECT CASE @val
-> WHEN 0 THEN '@val is 0'
-> WHEN 1 THEN '@val is 1'
-> ELSE '@val is not 0 or 1'
-> END AS result;
+-----------+
| result |
+-----------+
| @val is 1 |
+----------+
MySQL 5 Certification Study Guide 36
Querying for Data
• The following CASE expression tests whether the value of the @val user variable is NULL or less
than, greater than, or equal to 0:
mysql> SET @val = NULL;
mysql> SELECT CASE
-> WHEN @val IS NULL THEN '@val is NULL'
-> WHEN @val < 0 THEN '@val is less than 0'
-> WHEN @val > 0 THEN '@val is greater than 0'
-> ELSE '@val is 0'
-> END AS result;
+--------------+
| result |
+--------------+
| @val is NULL |
+-------------+
MySQL 5 Certification Study Guide 37
Querying for Data
Temporal Functions
• Temporal functions perform operations such as extracting parts of dates and times, reformatting
values, or converting values to seconds or days.
mysql> SET @d = '2010-04-15', @t = '09:23:57';
mysql> SELECT YEAR(@d), MONTH(@d), DAYOFMONTH(@d);
+----------+-----------+----------------+
| YEAR(@d) | MONTH(@d) | DAYOFMONTH(@d) |
+----------+-----------+----------------+
| 2010 | 4 | 15 |
+---------+-----------+----------------+
mysql> SELECT DAYOFYEAR(@d);
+---------------+
| DAYOFYEAR(@d) |
+---------------+
| 105 |
+---------------+
mysql> SELECT HOUR(@t), MINUTE(@t), SECOND(@t);
+----------+------------+------------+
| HOUR(@t) | MINUTE(@t) | SECOND(@t) |
+----------+------------+------------+
| 9 | 23 | 57 |
+----------+------------+------------+
MySQL 5 Certification Study Guide 38
Querying for Data
• MAKEDATE() and MAKETIME() compose dates and times from component values. MAKEDATE()
produces a date from year and day of year arguments:
mysql> SELECT MAKEDATE(2010,105);
+--------------------+
| MAKEDATE(2010,105) |
+--------------------+
| 2010-04-15 |
+--------------------+
mysql> SELECT MAKETIME(9,23,57);
+-------------------+
| MAKETIME(9,23,57) |
+-------------------+
| 09:23:57 |
+-------------------+
• If you need to determine the current date or time, use CURRENT_DATE or CURRENT_TIME. To
get the current date and time as a single value, use CURRENT_TIMESTAMP or NOW():
mysql> SELECT CURRENT_DATE, CURRENT_TIME, CURRENT_TIMESTAMP;
+--------------+--------------+---------------------+
| CURRENT_DATE | CURRENT_TIME | CURRENT_TIMESTAMP |
+--------------+--------------+---------------------+
| 2005-05-31 | 21:40:18 | 2005-05-31 21:40:18 |
+--------------+--------------+---------------------+
MySQL 5 Certification Study Guide 39
Querying for Data
.
.
.
.
.
.
.
.
MySQL 5 Certification Study Guide 40

More Related Content

PDF
PPTX
Ben Finkel- Using the order by clause.pptx
PPT
Sql select
PPTX
Chapter-9-MySQL.pptxxzrtyryrydfdsfdsfdsrter
PPT
Basic Commands using Structured Query Langauage(SQL)
PPTX
Lecture2 mysql by okello erick
PDF
MySQL Cookbook 1st ed Edition Paul Dubois
PPTX
DATA BASE || INTRODUCTION OF DATABASE \\ SQL 2018
Ben Finkel- Using the order by clause.pptx
Sql select
Chapter-9-MySQL.pptxxzrtyryrydfdsfdsfdsrter
Basic Commands using Structured Query Langauage(SQL)
Lecture2 mysql by okello erick
MySQL Cookbook 1st ed Edition Paul Dubois
DATA BASE || INTRODUCTION OF DATABASE \\ SQL 2018

Similar to Distributed databases systems-3-2015.ppt (20)

PDF
MySQL Cookbook 1st ed Edition Paul Dubois
PPT
Mysql Database and query formation using
PDF
MySQL Cookbook 1st ed Edition Paul Dubois
PDF
Introduction to MySQL and introduction to basic queries
PPTX
Lab1 select statement
PPT
Intro to my sql
PPT
Intro to my sql
PPTX
MySQL basics
PPTX
Introduction to SQL
PPTX
Lecture5 my sql statements by okello erick
PPT
mysql-Tutorial with Query presentation.ppt
PDF
sql_data.pdf
PDF
介绍 MySQL
PPTX
MySQL Essential Training
DOCX
DBMS Practical file 2019 BCAS301P (1).docx
PPTX
SQL python for beginners easy explanation with concepts and output .pptx
PPTX
SQL Data Manipulation language and DQL commands
PDF
Copy Of Mysql Datadictionary
PDF
Mysql Datadictionary
MySQL Cookbook 1st ed Edition Paul Dubois
Mysql Database and query formation using
MySQL Cookbook 1st ed Edition Paul Dubois
Introduction to MySQL and introduction to basic queries
Lab1 select statement
Intro to my sql
Intro to my sql
MySQL basics
Introduction to SQL
Lecture5 my sql statements by okello erick
mysql-Tutorial with Query presentation.ppt
sql_data.pdf
介绍 MySQL
MySQL Essential Training
DBMS Practical file 2019 BCAS301P (1).docx
SQL python for beginners easy explanation with concepts and output .pptx
SQL Data Manipulation language and DQL commands
Copy Of Mysql Datadictionary
Mysql Datadictionary

Recently uploaded (20)

PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
GDM (1) (1).pptx small presentation for students
PDF
Classroom Observation Tools for Teachers
PPTX
Cell Types and Its function , kingdom of life
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PPTX
Lesson notes of climatology university.
PPTX
Cell Structure & Organelles in detailed.
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
TR - Agricultural Crops Production NC III.pdf
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
Insiders guide to clinical Medicine.pdf
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
Institutional Correction lecture only . . .
PDF
Anesthesia in Laparoscopic Surgery in India
O7-L3 Supply Chain Operations - ICLT Program
GDM (1) (1).pptx small presentation for students
Classroom Observation Tools for Teachers
Cell Types and Its function , kingdom of life
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Lesson notes of climatology university.
Cell Structure & Organelles in detailed.
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
O5-L3 Freight Transport Ops (International) V1.pdf
102 student loan defaulters named and shamed – Is someone you know on the list?
TR - Agricultural Crops Production NC III.pdf
Renaissance Architecture: A Journey from Faith to Humanism
Insiders guide to clinical Medicine.pdf
STATICS OF THE RIGID BODIES Hibbelers.pdf
VCE English Exam - Section C Student Revision Booklet
Institutional Correction lecture only . . .
Anesthesia in Laparoscopic Surgery in India

Distributed databases systems-3-2015.ppt

  • 2. Querying for Data Using SELECT to Retrieve Data • The SELECT statement retrieves information from one or more tables. Retrievals tend to be the most common database operation, so it's important to understand how SELECT works and what you can do with it. SELECT values_to_display FROM table_name WHERE expression GROUP BY how_to_group HAVING expression ORDER BY how_to_sort LIMIT row_count; The syntax shown here is simplified from the full SELECT syntax, which includes additional clauses MySQL 5 Certification Study Guide 2
  • 3. Querying for Data • To indicate what values to retrieve, name them following the SELECT keyword. mysql> SELECT 2+2, REPEAT('x',5), DATE_ADD('2001-01-01',INTERVAL 7 DAY), 1/0; +-----+--------------------+----------------------------------------------------------+------+ | 2+2 | REPEAT('x',5) | DATE_ADD('2001-01-01',INTERVAL 7 DAY) | 1/0 | +-----+--------------------+----------------------------------------------------------+------+ | 4 | xxxxx | 2001-01-08 | NULL | +-----+--------------------+----------------------------------------------------------+------+ mysql> DESCRIBE City; +-------------+----------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | | ID | int(11) | NO | PRI | NULL | auto_increment | | Name | char(35) | NO | | | | | CountryCode | char(3) | NO | | | | | District | char(20) | NO | | | | | Population | int(11) | NO | | 0 | | +-------------+----------+------+-----+---------+----------------+ MySQL 5 Certification Study Guide 3
  • 4. Querying for Data • To retrieve the contents of these columns, write the SELECT statement as follows: SELECT ID, Name, CountryCode, District, Population FROM City; SELECT * FROM City; • Output column names, by default, are the same as the column or expression selected. To rename a column, provide an alias following the column in the output list: mysql> SELECT 1 AS One, 4*3 'Four Times Three'; +------+------------------------+ | One | Four Times Three | +------+------------------------+ | 1 | 12 | +------+------------------------+ • Columns aliases are used as follows: – The keyword AS is optional. – An alias may be quoted. If it consists of multiple words, it must be quoted. • To specify a database explicitly in the SELECT statement itself, qualify the table name. That is, precede the table name with the database name and a period: SELECT * FROM world.Country; MySQL 5 Certification Study Guide 4
  • 5. Querying for Data Specifying Which Rows to Retrieve • A WHERE clause can be as simple or complex as necessary to identify the rows that are relevant for your purposes. – SELECT * FROM Country WHERE IndepYear > 1990; – SELECT * FROM Country WHERE Population >= 1000000 AND Population <= 2000000; – SELECT * FROM Country WHERE Population BETWEEN 1000000 AND 2000000; • Some operators have higher precedence than others. For example, AND has a higher precedence than OR. WHERE GNP < 1000 AND Continent = 'Africa' OR Continent = 'Asia‘ Using ORDER BY to Sort Query Results By default, the rows in the result set produced by a SELECT statement are returned by the server to the client in no particular order. When you issue a query, the server is free to return the rows in any convenient order. This order can be affected by factors such as the order in which rows are actually stored in the table or which indexes are used to process the query. If you require output rows to be returned in a specific order, include an ORDER BY clause that indicates how to sort the results. MySQL 5 Certification Study Guide 5
  • 6. Querying for Data mysql> SELECT id, last_name, first_name, birth FROM t ORDER BY birth; +------+-----------+------------+-----------------+ | id | last_name | first_name | birth | +------+-----------+-------------+----------------+ | 2 | Larsson | Sven | 1965-01-03 | | 4 | Larsson | Selma | 1968-05-29 | | 3 | Brown | Betty | 1971-07-12 | | 1 | Brown | Bill | 1972-10-14 | +------+-----------+-------------+----------------+ mysql> SELECT id, last_name, first_name, birth FROM t ORDER BY last_name, first_name; +------+-----------+------------+------------+ | id | last_name | first_name | birth | +------+-----------+------------+------------+ | 3 | Brown | Betty | 1971-07-12 | | 1 | Brown | Bill | 1972-10-14 | | 4 | Larsson | Selma | 1968-05-29 | | 2 | Larsson | Sven | 1965-01-03 | +------+-----------+------------+------------+ MySQL 5 Certification Study Guide 6
  • 7. Querying for Data • By default, ORDER BY sorts values in ascending order (smallest to largest). ORDER BY last_name, first_name ORDER BY last_name ASC, first_name ASC To sort values in descending order (largest to smallest), follow the sort column name with DESC: mysql> SELECT id, last_name, first_name, birth FROM t ORDER BY id DESC; +------+-----------+------------+------------+ | id | last_name | first_name | birth | +------+-----------+------------+------------+ | 4 | Larsson | Selma | 1968-05-29 | | 3 | Brown | Betty | 1971-07-12 | | 2 | Larsson | Sven | 1965-01-03 | | 1 | Brown | Bill | 1972-10-14 | +------+-----------+------------+------------+ MySQL 5 Certification Study Guide 7
  • 8. Querying for Data • ORDER BY typically refers to table columns by name: SELECT last_name, first_name FROM t ORDER BY last_name, first_name; • However, it's possible to refer to columns in other ways. If a column is given an alias in the output column list, you should refer to that column in the ORDER BY column by its alias: SELECT last_name AS last, first_name AS first FROM t ORDER BY last, first; • Or you can specify a number corresponding to the column's position in the column output list (1 for the first output column, 2 for the second, and so forth) : SELECT last_name, first_name FROM t ORDER BY 1, 2; • It's possible to perform a sort using an expression result. SELECT id, last_name, first_name, MONTH(birth) FROM t ORDER BY MONTH(birth); • Output sorting can be based on values that don't appear in the output at all. mysql> SELECT id, last_name, first_name, MONTHNAME(birth) FROM t ORDER BY MONTH(birth); MySQL 5 Certification Study Guide 8
  • 9. Querying for Data Character Sets and Collations in General • A character set is a set of symbols and encodings. A collation is a set of rules for comparing characters in a character set. Let's make the distinction clear with an example of an imaginary character set. • Suppose that we have an alphabet with four letters: “A”, “B”, “a”, “b”. We give each letter a number: “A” = 0, “B” = 1, “a” = 2, “b” = 3. The letter “A” is a symbol, the number 0 is the encoding for “A”, and the combination of all four letters and their encodings is a character set. mysql> SHOW CHARACTER SET; mysql> SHOW COLLATION; The Natural Sort Order of String The sort order for a string column that has a data type other than ENUM or SET depends on whether the column contains non-binary or binary values. Non-binary strings sort in the order defined by their collation. This order can be case sensitive or not, depending on the collation. Binary strings sort based on the numeric values of the bytes contained in the strings. For example, assume that a table t has a CHAR column c that has the latin1 character set and that contains the following values: mysql> SELECT c FROM t; MySQL 5 Certification Study Guide 9
  • 10. Querying for Data • A CHAR column is non-binary, so its contents sort according to the column's collation. If the collation is not case sensitive, values sort lexically without regard to lettercase: mysql> SELECT c FROM t ORDER BY c; • Notice that the results come out in letter order, but the rows for a given letter are not further sorted by lettercase. • If the collation is case sensitive, lettercase becomes significant. You can force a string column sort to be case sensitive by using the COLLATE operator with a case-sensitive collation: mysql> SELECT c FROM t ORDER BY c COLLATE latin1_general_cs; MySQL 5 Certification Study Guide 10
  • 11. Querying for Data • If the collation is binary, numeric character values are the determining factor: mysql> SELECT c FROM t ORDER BY c COLLATE latin1_bin; • The sort order for members of an ENUM or SET column is based on their internal numeric values. These values correspond to the order in which the enumeration or set members are listed in the column definition. Suppose that a table t contains a column mon that is an ENUM listing abbreviations for months of the year: CREATE TABLE t ( mon ENUM('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec')); • Assume that table t has 12 rows, one for each of the possible enumeration values. When you sort this column, the values come out in month-of-year order: mysql> SELECT mon FROM t ORDER BY mon; MySQL 5 Certification Study Guide 11
  • 12. Querying for Data • This occurs because 'Jan' through 'Dec' are assigned internal values 1 through 12 based on their order in the column definition, and those values determine the sort order. To produce a lexical string sort instead, use CAST() to convert the enumeration values to CHAR values: mysql> SELECT mon FROM t ORDER BY CAST(mon AS CHAR); • SET columns also sort using the internal values of the set's legal members. The ordering is more complex than with ENUM because values may consist of multiple SET members. For example, the following SET column contains three members: CREATE TABLE t (hue SET('red','green','blue')); • Assume that t contains the following rows: mysql> SELECT hue FROM t; The SET members 'red', 'green', and 'blue' have internal values of 1, 2, and 4, respectively. Thus, the rows of the table have internal numeric values of 1+2 = 3, 1+2+4 = 7, 1+4 = 5, and 2+4 = 6. An ORDER BY on the column sorts using those numeric values: mysql> SELECT hue FROM t ORDER BY hue; MySQL 5 Certification Study Guide 12
  • 13. Querying for Data • As with ENUM, SET values can be sorted lexically by using CAST() to convert them to strings: mysql> SELECT hue FROM t ORDER BY CAST(hue AS CHAR); +----------------+ | hue | +----------------+ | green,blue | | red,blue | | red,green | | red,green,blue | +----------------+ • NULL values in a column sort together at the beginning for ascending sorts and at the end for descending sorts. MySQL 5 Certification Study Guide 13
  • 14. Querying for Data Limiting a Selection Using LIMIT • MySQL supports a LIMIT clause in SELECT statements, which tells the server to return only some of the rows selected by the statement. SELECT * FROM Country LIMIT 10; SELECT * FROM Country LIMIT 20,10; SELECT * FROM t ORDER BY id LIMIT 1; SELECT * FROM t ORDER BY id DESC LIMIT 1; • The two-argument form of LIMIT is useful in conjunction with ORDER BY for situations in which you want to process successive sections of a result set. For example, in Web applications, it's common to display the result of a large search across a series of pages that each present one section of the result. To retrieve sections of the search result this way, issue a series of statements that all specify the same number of rows to return in the LIMIT clause, but vary the number of initial rows to skip: SELECT * FROM t ORDER BY id LIMIT 0, 20; SELECT * FROM t ORDER BY id LIMIT 20, 20; SELECT * FROM t ORDER BY id LIMIT 40, 20; SELECT * FROM t ORDER BY id LIMIT 60, 20; ... MySQL 5 Certification Study Guide 14
  • 15. Querying for Data Using DISTINCT to Eliminate Duplicates • Suppose that a query returns a result set that contains duplicated rows: mysql> SELECT last_name FROM t; • Adding DISTINCT removes the duplicates and returns only unique rows: mysql> SELECT DISTINCT last_name FROM t; • DISTINCT treats all NULL values within a given column as having the same value. Suppose that a table t contains the following rows: mysql> SELECT i, j FROM t; • Adding DISTINCT to the query eliminates one of them as a duplicate: mysql> SELECT DISTINCT i, j FROM t; +------+------+ | i | j | +------+------+ | 1 | 2 | | 1 | NULL | +------+------+ MySQL 5 Certification Study Guide 15
  • 16. Querying for Data Aggregating Results • Functions such as AVG() that calculate summary values for groups are known as "aggregate" functions because they're based on aggregates or groups of values. There are several types of aggregate functions. Those discussed here are as follows: – MIN() and MAX() find smallest and largest values. – SUM() and AVG() summarize numeric values to produce sums (totals) and averages. – COUNT() counts rows, values, or the number of distinct values. – GROUP_CONCAT() concatenates a set of strings to produce a single string value. The MIN() and MAX() Aggregate Functions mysql> SELECT MIN(Population), MAX(Population) FROM Country; +-----------------+-----------------+ | MIN(Population) | MAX(Population) | +-----------------+-----------------+ | 0 | 1277558000 | +-----------------+-----------------+ mysql> SELECT MIN(Name), MAX(Name) FROM Country; +-------------+-----------+ | MIN(Name) | MAX(Name) | +-------------+-----------+ | Afghanistan | Zimbabwe | +-------------+-----------+ MySQL 5 Certification Study Guide 16
  • 17. Querying for Data • For string values, the behavior of MIN() and MAX() depends on whether the strings are non-binary or binary. Consider a table t that contains the following string values: , its values are compared using the numeric values of the bytes in the strings. If ‘C’ has a smaller numeric value • ‘a’ (as is true if characters are stored using ASCII codes), MAX(name)returns ‘alex’: mysql> SELECT name FROM t; mysql> SELECT MAX(name) FROM t; mysql> ALTER TABLE t MODIFY name BINARY(20); mysql> SELECT MAX(name) FROM t; • MIN() and MAX() ignore NULL values. MySQL 5 Certification Study Guide 17
  • 18. Querying for Data The COUNT() Aggregate Function • The COUNT() function can be used in several ways to count either rows or values. mysql> SELECT i, j FROM t; • COUNT(expression) counts the number of non-NULL values of the given expression. It's common for expression to be a column name, in which case COUNT() counts the number of non-NULL values in the column: mysql> SELECT COUNT(i), COUNT(j) FROM t; mysql> SELECT COUNT(DISTINCT i), COUNT(DISTINCT j) FROM t; +-------------------+-------------------+ | COUNT(DISTINCT i) | COUNT(DISTINCT j) | +-------------------+-------------------+ | 1 | 3 | +-------------------+-------------------+ MySQL 5 Certification Study Guide 18
  • 19. Querying for Data • It's also possible to give a list of expressions separated by commas. In this case, COUNT() returns the number of distinct combinations of values that contain no NULL values. The following query counts the number of distinct rows for which neither i nor j is NULL: mysql> SELECT COUNT(DISTINCT i, j) FROM t; +----------------------+ | COUNT(DISTINCT i, j) | +----------------------+ | 2 | +----------------------+ The GROUP_CONCAT() Function The purpose of the GROUP_CONCAT() function is to concatenate column values into a single string. mysql> SELECT Language FROM CountryLanguage WHERE CountryCode = 'THA'; MySQL 5 Certification Study Guide 19
  • 20. Querying for Data • To concatenate the values into a single string, use GROUP_CONCAT(): mysql> SELECT GROUP_CONCAT(Language) AS Languages -> FROM CountryLanguage WHERE CountryCode = 'THA'; +-----------------------------------------------+ | Languages | +-----------------------------------------------+ | Chinese,Khmer,Kuy,Lao,Malay,Thai | +-----------------------------------------------+ • The default string separator used by GROUP_CONCAT() is ',' (comma). To change the separator, use a SEPARATOR clause: mysql> SELECT GROUP_CONCAT(Language SEPARATOR ' - ') AS Languages -> FROM CountryLanguage WHERE CountryCode = 'THA'; +--------------------------------------------+ | Languages | +--------------------------------------------+ | Chinese - Khmer - Kuy - Lao - Malay - Thai | +--------------------------------------------+ MySQL 5 Certification Study Guide 20
  • 21. Querying for Data • GROUP_CONCAT() adds strings to the result in the order in which the database server reads them. To change the concatenation order, add an ORDER BY clause. mysql> SELECT GROUP_CONCAT(Language ORDER BY Language DESC) -> AS Languages FROM CountryLanguage WHERE CountryCode = 'THA'; +----------------------------------+ | Languages | +----------------------------------+ | Thai,Malay,Lao,Kuy,Khmer,Chinese | +----------------------------------+ Grouping Results • If a query does not contain a GROUP BY clause to place rows of the result set into groups, an aggregate function produces a result that is based on all the selected rows. A GROUP BY clause may be added to generate a more fine- grained summary that produces values for subgroups within a set of selected rows. MySQL 5 Certification Study Guide 21
  • 22. Querying for Data mysql> SELECT * FROM personnel; +---------+--------+---------+-------------+----------+ | pers_id | name | dept_id | title | salary | +---------+--------+---------+-------------+----------+ | 1 | Wendy | 14 | Supervisor | 38000.00 | | 2 | Wally | 7 | Stock clerk | 28000.00 | | 3 | Ray | 7 | Programmer | 41000.00 | | 4 | Burton | 14 | Secretary | 32000.00 | | 5 | Gordon | 14 | President | 78000.00 | | 6 | Jeff | 7 | Stock clerk | 29000.00 | | 7 | Doris | 7 | Programmer | 48000.00 | | 8 | Daisy | 7 | Secretary | 33000.00 | | 9 | Bea | 7 | Accountant | 40000.00 | +---------+--------+---------+-------------+----------+ mysql> SELECT COUNT(*) FROM personnel; MySQL 5 Certification Study Guide 22
  • 23. Querying for Data mysql> SELECT title, COUNT(*) FROM personnel GROUP BY title; mysql> SELECT dept_id, COUNT(*) FROM personnel -> GROUP BY dept_id; mysql> SELECT dept_id, title, COUNT(*) FROM personnel -> GROUP BY dept_id, title; MySQL 5 Certification Study Guide 23
  • 24. Querying for Data Selecting Groups with HAVING 1. WHERE, if present, identifies the initial set of records to select from a table. 2. GROUP BY arranges the selected records into groups. 3. Aggregate functions compute summary values for each group. 4. HAVING identifies which groups to retrieve for the final result set. mysql> SELECT title, salary FROM personnel WHERE dept_id = 7; +-------------+----------+ | title | salary | +-------------+----------+ | Stock clerk | 28000.00 | | Programmer | 41000.00 | | Stock clerk | 29000.00 | | Programmer | 48000.00 | | Secretary | 33000.00 | | Accountant | 40000.00 | +-------------+----------+ MySQL 5 Certification Study Guide 24
  • 25. Querying for Data mysql> SELECT title, COUNT(*), AVG(salary) FROM personnel WHERE dept_id = 7 -> GROUP BY title; mysql> SELECT title, salary, COUNT(*), AVG(salary) -> FROM personnel WHERE dept_id = 7 -> GROUP BY title -> HAVING COUNT(*) > 1; +-------------+----------+----------+--------------+ | title | salary | COUNT(*) | AVG(salary) | +-------------+----------+----------+--------------+ | Programmer | 41000.00 | 2 | 44500.000000 | | Stock clerk | 28000.00 | 2 | 28500.000000 | +-------------+----------+----------+--------------+ MySQL 5 Certification Study Guide 25
  • 26. Querying for Data Using UNION The UNION keyword enables you to concatenate the results from two or more SELECT statements. MySQL 5 Certification Study Guide 26
  • 27. Querying for Data String Expressions mysql> SELECT CONCAT('abc','def',REPEAT('X',3)); +-----------------------------------+ | CONCAT('abc','def',REPEAT('X',3)) | +-----------------------------------+ | abcdefXXX | +-----------------------------------+ • The || operator is treated as the logical OR operator by default, but can be used for string concatenation if you enable the PIPES_AS_CONCAT SQL mode: mysql> SELECT 'abc' || 'def'; +----------------+ | 'abc' || 'def' | +----------------+ | 0 | +----------------+ mysql> SET sql_mode = 'PIPES_AS_CONCAT'; mysql> SELECT 'abc' || 'def'; +----------------+ | 'abc' || 'def' | +----------------+ | abcdef | +----------------+ MySQL 5 Certification Study Guide 27
  • 28. Querying for Data Case Sensitivity in String Comparisons mysql> SELECT 'Hello' = 'hello'; +-------------------+ | 'Hello' = 'hello' | +-------------------+ | 1 | +-------------------+ mysql> SELECT BINARY 'Hello' = 'hello'; +--------------------------+ | BINARY 'Hello' = 'hello' | +--------------------------+ | 0 | +--------------------------+ • String comparison rules also apply to GROUP BY and DISTINCT operations. Suppose that t has a column c with the following contents: mysql> SELECT c FROM t; MySQL 5 Certification Study Guide 28
  • 29. Querying for Data • If c is a non-binary, case-insensitive column, GROUP BY and DISTINCT do not make lettercase distinctions: mysql> SELECT c, COUNT(*) FROM t GROUP BY c; +---------+----------+ | c | COUNT(*) | +---------+----------+ | Goodbye | 2 | | Hello | 2 | +---------+----------+ mysql> SELECT DISTINCT c FROM t; +---------+ | c | +---------+ | Hello | | Goodbye | +---------+ MySQL 5 Certification Study Guide 29
  • 30. Querying for Data • On the other hand, if c is a BINARY column, those operations use byte values for sorting: mysql> SELECT c, COUNT(*) FROM t GROUP BY c; +---------+----------+ | c | COUNT(*) | +---------+----------+ | Goodbye | 1 | | Hello | 1 | | goodbye | 1 | | hello | 1 | +---------+----------+ mysql> SELECT DISTINCT c FROM t; +---------+ | c | +---------+ | Hello | | hello | | Goodbye | | goodbye | +---------+ MySQL 5 Certification Study Guide 30
  • 31. Querying for Data • The UPPER() and LOWER() functions perform case conversion only if the argument is a non- binary string. mysql> SELECT UPPER('AbCd'), LOWER('AbCd'); +---------------+---------------+ | UPPER('AbCd') | LOWER('AbCd') | +---------------+---------------+ | ABCD | abcd | +---------------+---------------+ mysql> SELECT UPPER(BINARY 'AbCd'), LOWER(BINARY 'AbCd'); +----------------------+----------------------+ | UPPER(BINARY 'AbCd') | LOWER(BINARY 'AbCd') | +----------------------+----------------------+ | AbCd | AbCd | +----------------------+----------------------+ MySQL 5 Certification Study Guide 31
  • 32. Querying for Data Using LIKE for Pattern Matching • Patterns used with the LIKE pattern-matching operator can contain two special characters (called "metacharacters" or "wildcards") that stand for something other than themselves: – The '%' character matches any sequence of zero or more characters. For example, the pattern 'a%' matches any string that begins with 'a', '%b' matches any string that ends with 'b', and '%c%' matches any string that contains a 'c'. The pattern '%' matches any string, including empty strings. – The '_' (underscore) character matches any single character. 'd_g' matches strings such as 'dig', 'dog', and 'd@g'. Because '_' matches any single character, it matches itself and the pattern 'd_g' also matches the string 'd_g'. • LIKE evaluates to NULL if either operand is NULL, but any non-NULL literal value matches itself. Likewise, a function call that produces a non-NULL value matches itself (with one exception). Thus, the following expressions evaluate as true: mysql> SELECT 'ABC' LIKE 'abc', 'ABC' LIKE BINARY 'abc'; +------------------+-------------------------+ | 'ABC' LIKE 'abc' | 'ABC' LIKE BINARY 'abc' | +-----------------+-------------------------+ | 1 | 0 | +------------------+-------------------------+ MySQL 5 Certification Study Guide 32
  • 33. Querying for Data • The exception is that different invocations of the RAND() random-number function might return different values, even within the same query: mysql> SELECT RAND(), RAND(); +------------------+------------------+ | RAND() | RAND() | +------------------+------------------+ | 0.15430032289987 | 0.30666533979277 | +------------------+------------------+ • As a result, the expression RAND() LIKE RAND() normally will be false. • To invert a pattern match, use NOT LIKE rather than LIKE: mysql> SELECT 'ABC' LIKE 'A%', 'ABC' NOT LIKE 'A%'; +-----------------+---------------------+ | 'ABC' LIKE 'A%' | 'ABC' NOT LIKE 'A%' | +-----------------+---------------------+ | 1 | 0 | +-----------------+---------------------+ MySQL 5 Certification Study Guide 33
  • 34. Querying for Data Functions in SQL Expressions mysql> SELECT PI (); +----------+ | PI () | +----------+ | 3.141593 | +----------+ • LEAST() and GREATEST() take a set of values as arguments and return the one that is smallest or largest, respectively: mysql> SELECT LEAST(4,3,8,-1,5), LEAST('cdef','ab','ghi'); +-------------------+--------------------------+ | LEAST(4,3,8,-1,5) | LEAST('cdef','ab','ghi') | +-------------------+--------------------------+ | -1 | ab | +-------------------+--------------------------+ mysql> SELECT GREATEST(4,3,8,-1,5), GREATEST('cdef','ab','ghi'); +----------------------+-----------------------------+ | GREATEST(4,3,8,-1,5) | GREATEST('cdef','ab','ghi') | +----------------------+-----------------------------+ | 8 | ghi | +----------------------+-----------------------------+ MySQL 5 Certification Study Guide 34
  • 35. Querying for Data • INTERVAL() compares the first argument to the others and returns a value to indicate how many of them are less than or equal to it. mysql> SELECT INTERVAL(2,1,2,3,4); +---------------------+ | INTERVAL(2,1,2,3,4) | +---------------------+ | 2 | +---------------------+ mysql> SELECT INTERVAL(0,1,2,3,4); +---------------------+ | INTERVAL(0,1,2,3,4) | +---------------------+ | 0 | +--------------------+ mysql> SELECT INTERVAL(6.3,2,4,6,8,10); +--------------------------+ | INTERVAL(6.3,2,4,6,8,10) | +--------------------------+ | 3 | +--------------------------+ MySQL 5 Certification Study Guide 35
  • 36. Querying for Data Control Flow Functions mysql> SELECT IF(1 > 0, 'yes','no'); +-----------------------+ | IF(1 > 0, 'yes','no') | +-----------------------+ | yes | +-----------------------+ • The CASE construct is not a function, but it too provides flow control. It has two forms of syntax. The first looks like this: mysql> SET @val = 1; mysql> SELECT CASE @val -> WHEN 0 THEN '@val is 0' -> WHEN 1 THEN '@val is 1' -> ELSE '@val is not 0 or 1' -> END AS result; +-----------+ | result | +-----------+ | @val is 1 | +----------+ MySQL 5 Certification Study Guide 36
  • 37. Querying for Data • The following CASE expression tests whether the value of the @val user variable is NULL or less than, greater than, or equal to 0: mysql> SET @val = NULL; mysql> SELECT CASE -> WHEN @val IS NULL THEN '@val is NULL' -> WHEN @val < 0 THEN '@val is less than 0' -> WHEN @val > 0 THEN '@val is greater than 0' -> ELSE '@val is 0' -> END AS result; +--------------+ | result | +--------------+ | @val is NULL | +-------------+ MySQL 5 Certification Study Guide 37
  • 38. Querying for Data Temporal Functions • Temporal functions perform operations such as extracting parts of dates and times, reformatting values, or converting values to seconds or days. mysql> SET @d = '2010-04-15', @t = '09:23:57'; mysql> SELECT YEAR(@d), MONTH(@d), DAYOFMONTH(@d); +----------+-----------+----------------+ | YEAR(@d) | MONTH(@d) | DAYOFMONTH(@d) | +----------+-----------+----------------+ | 2010 | 4 | 15 | +---------+-----------+----------------+ mysql> SELECT DAYOFYEAR(@d); +---------------+ | DAYOFYEAR(@d) | +---------------+ | 105 | +---------------+ mysql> SELECT HOUR(@t), MINUTE(@t), SECOND(@t); +----------+------------+------------+ | HOUR(@t) | MINUTE(@t) | SECOND(@t) | +----------+------------+------------+ | 9 | 23 | 57 | +----------+------------+------------+ MySQL 5 Certification Study Guide 38
  • 39. Querying for Data • MAKEDATE() and MAKETIME() compose dates and times from component values. MAKEDATE() produces a date from year and day of year arguments: mysql> SELECT MAKEDATE(2010,105); +--------------------+ | MAKEDATE(2010,105) | +--------------------+ | 2010-04-15 | +--------------------+ mysql> SELECT MAKETIME(9,23,57); +-------------------+ | MAKETIME(9,23,57) | +-------------------+ | 09:23:57 | +-------------------+ • If you need to determine the current date or time, use CURRENT_DATE or CURRENT_TIME. To get the current date and time as a single value, use CURRENT_TIMESTAMP or NOW(): mysql> SELECT CURRENT_DATE, CURRENT_TIME, CURRENT_TIMESTAMP; +--------------+--------------+---------------------+ | CURRENT_DATE | CURRENT_TIME | CURRENT_TIMESTAMP | +--------------+--------------+---------------------+ | 2005-05-31 | 21:40:18 | 2005-05-31 21:40:18 | +--------------+--------------+---------------------+ MySQL 5 Certification Study Guide 39
  • 40. Querying for Data . . . . . . . . MySQL 5 Certification Study Guide 40