Querying data
SELECT
the syntax of the SELECT statement:
SELECT
column_1, column_2, ...
FROM
table_1
[INNER | LEFT |RIGHT] JOIN table_2 ON conditions
WHERE
conditions
GROUP BY column_1
HAVING group_conditions
ORDER BY column_1
LIMIT offset, length;
If you want to get data for all columns in the employees table, you can list all column names in the SELECT
clause. Or you just use the asterisk (*
) to indicate that you want to get data from all columns of the table like the following query:
SELECT * FROM table1;
DISTINCT
The syntax of using the DISTINCT
clause is as follows:
SELECT DISTINCT
columns
FROM
table_name
WHERE
where_conditions;
-
DISTINCT
clause vs.GROUP BY
clause
If you use the GROUP BY
clause in the SELECT
statement without using aggregate functions, the GROUP BY
clause behaves like the DISTINCT
clause.
Generally speaking, the DISTINCT
clause is a special case of the GROUP BY
clause. The difference between DISTINCT
clause and GROUP BY
clause is that the GROUP BY
clause sorts the result set whereas the DISTINCT
clause does not.
for examples,
SELECT
columns
FROM
table_name
GROUP BY columns;
is equivalent to
SELECT DISTINCT
columns
FROM
table_name
ORDER BY columns;
Filtering Data
WHERE
Even though the WHERE
clause appears at the end of the statement, MySQL evaluates the expression in the WHERE
clause first to select the matching rows.
The following table lists the comparison operators that you can use to form filtering expressions in the WHERE
clause.
AND
The following illustrates the results of the AND
operator when combining true, false, and null.
OR
The following table shows the result of the OR
operator.
IN
The IN
operator allows you to determine if a specified value matches any one of a list or a subquery.
The following illustrates the syntax of the IN
operator.
SELECT
column1,column2,...
FROM
table_name
WHERE
(expr|column_1) [NOT] IN ('value1','value2',...);
!Note that if the
expr
or any value in the list isNULL
, theIN
operator returnsNULL
You can combine the IN
operator with the NOT
operator to determine if a value does not match any value in a list or a subquery.
BETWEEN
The BETWEEN
operator allows you to specify a range to test.
The following illustrates the syntax of the BETWEEN
operator:
expr [NOT] BETWEEN begin_expr AND end_expr;
!NOTE If any expression is
NULL
, theBETWEEN
operator returns aNULL
value.
- with DATA type
When you use the BETWEEN
operator with date values, to get the best result, you should use the type cast
to explicitly convert the type of column or expression to the DATE
type.
CAST('2020-01-01' as DATE)
LIKE
MySQL provides two wildcard characters for using with the LIKE operator, the percentage %
and underscore _
.
%
wildcard allows you to match any string of zero or more characters.
_
wildcard allows you to match any single character.
- with ESCAPE clause
If you don’t specify the escape character explicitly, the backslash character \
is the default escape character.
SELECT
columns
FROM
table_name
WHERE
column LIKE '%\_20%';
Or you can specify a different escape character e.g., $
by using the ESCAPE clause:
SELECT
columns
FROM
table_name
WHERE
column LIKE '%$_20%' ESCAPE '$';
LIMIT
The LIMIT
clause is used in the SELECT
statement to constrain the number of rows in a result set.
The following illustrates the LIMIT clause syntax with two arguments:
SELECT
column1,column2,...
FROM
table
LIMIT offset , count;
The offset
specifies the offset of the first row to return. The offset of the first row is 0, not 1.
The count
specifies the maximum number of rows to return.
When you use the LIMIT
clause with one argument, this argument will be used to determine the maximum number of rows to return from the beginning of the result set.
SELECT
column1,column2,...
FROM
table
LIMIT count;
The query above is equivalent to the following query with the LIMIT
clause that accepts two arguments:
SELECT
column1,column2,...
FROM
table
LIMIT 0 , count;
- Using MySQL LIMIT to get the first N rows
SELECT
column1,column2,...
FROM
table
LIMIT N;
Using MySQL LIMIT to get the highest and lowest values
TheLIMIT
clause often used with theORDER BY
clause. First, you use theORDER BY
clause to sort the result set based on certain criteria, and then you use theLIMIT
clause to find lowest or highest values.Using MySQL LIMIT to get the nth highest value
SELECT
column1, column2,...
FROM
table
ORDER BY column1 DESC
LIMIT nth-1, count;
IS NULL
value IS [NOT] NULL
- MySQL IS NULL’s specialized features
If the DATE or DATETIME column that has
NOT NULL
constraint and contains the special date0000-00-00
, you can use theIS NULL
operator to find such rows.If the variable
@@sql_auto_is_null
is set to 1, you can get the value of a generated column after executing anINSERT
statement by using theIS NULL
operator. Note that by default the variable@@sql_auto_is_null
is 0.
Sorting Data
ORDER BY
The ORDER BY
clause allows you to:
- Sort a result set by a single column or multiple columns.
- Sort a result set by different columns in ascending or descending order.
The following illustrates the syntax of the ORDER BY clause:
SELECT column1, column2,...
FROM tbl
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC],...
By default, the ORDER BY
clause sorts the result set in ascending order if you don’t specify ASC
or DESC
explicitly.
- with customer sort order
TheORDER BY
clause enables you to define your own custom sort order for the values in a column using theFIELD()
function.
ELECT
column_1, column_2, ...
FROM
table_1
ORDER BY FIELD(status,
'Red',
'Green',
'Blue',
'Black',
'White');
Joining tables
AS
MySQL supports two kinds of aliases which are known as column alias and table alias.
MySQL alias for columns
The following statement illustrates how to use the column alias:
SELECT
[column_1 | expression] AS descriptive_name
FROM table_name;
If the alias contains space, you must quote it as the following:
SELECT
[column_1 | expression] AS `descriptive name`
FROM table_name;
Because the AS
keyword is optional, you can omit it in the statement.
MySQL alias for tables
table_name AS table_alias
JOIN
MySQL supports the following types of joins:
- Cross join
- Inner join
- Left join
- Right join
CROSS JOIN
The CROSS JOIN
makes a Cartesian product of rows from multiple tables. Suppose, you join t1 and t2 tables using the CROSS JOIN
, the result set will include the combinations of rows from the t1 table with the rows in the t2 table.
If you add a WHERE
clause, in case T1 and T2 has a relationship, the CROSS JOIN
works like the INNER JOIN
clause as shown in the following query:
SELECT
*
FROM
T1
CROSS JOIN
T2
WHERE
T1.id = T2.id;
SELECT
*
FROM
T1
INNER JOIN T2 ON T1.id = T2.id;
INNER JOIN
To form an INNER JOIN
, you need a condition which is known as a join-predicate.
- The syntax of the INNER JOIN clause is as follows:
SELECT column_list
FROM t1
INNER JOIN t2 ON join_condition1
INNER JOIN t3 ON join_condition2
...
WHERE where_conditions;
For each row in the t1 table, the INNER JOIN
clause compares it with each row of the t2,t3 ... table to check if both of them satisfy the join condition. When the join condition is met, the INNER JOIN
will return a new row which consists of columns in both t1 and t2,t3 ... tables.
LEFT JOIN
Unlike an INNER JOIN
, a LEFT JOIN
returns all rows in the left table including rows that satisfy join-predicate and rows do not. For the rows that do not match the join-predicate, NULL
s appear in the columns of the right table in the result set.
RIGHT JOIN
A RIGHT JOIN
is similar to the LEFT JOIN
except that the treatment of tables is reversed. With a RIGHT JOIN
, every row from the right table ( t2) will appear in the result set. For the rows in the right table that do not have the matching rows in the left table ( t1), NULL
s appear for columns in the left table ( t1).
SELF JOIN
There is a special case that you need join a table to itself, which is known as self join.
Grouping data
GROUP BY
The GROUP BY
clause groups a set of rows into a set of summary rows by values of columns or expressions. The GROUP BY
clause returns one row for each group. In other words, it reduces the number of rows in the result set.
The following illustrates the GROUP BY clause syntax:
SELECT
c1, c2,..., cn, aggregate_function(ci)
FROM
table
WHERE
where_conditions
GROUP BY c1 , c2,...,cn;
HAVING
The HAVING
clause is used in the SELECT
statement to specify filter conditions for a group of rows or aggregates.
If the GROUP BY
clause is omitted, the HAVING
clause behaves like the WHERE
clause.
Notice that the HAVING
clause applies a filter condition to each group of rows, while the WHERE
clause applies the filter condition to each individual row.
Reference
Basic MySQL Tutorial