0% found this document useful (0 votes)
116 views24 pages

Introduction To Database

The document discusses various SQL concepts including: 1) SQL join clauses allow tables to be linked together using common columns, as data in each table is incomplete on its own. Join types include inner, left, and self joins. 2) The DISTINCT operator eliminates duplicate rows from query results, treating NULL values as equal. DISTINCT can be used with single or multiple columns. 3) The GROUP BY clause groups query results and can behave like DISTINCT without aggregate functions. It sorts results while DISTINCT does not. HAVING can be used with GROUP BY to filter groups.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
116 views24 pages

Introduction To Database

The document discusses various SQL concepts including: 1) SQL join clauses allow tables to be linked together using common columns, as data in each table is incomplete on its own. Join types include inner, left, and self joins. 2) The DISTINCT operator eliminates duplicate rows from query results, treating NULL values as equal. DISTINCT can be used with single or multiple columns. 3) The GROUP BY clause groups query results and can behave like DISTINCT without aggregate functions. It sorts results while DISTINCT does not. HAVING can be used with GROUP BY to filter groups.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Introduction to database ORDER BY – show you how to sort the result set

using ORDER BY clause.


You deal with data every day…
SELECT
When you want to listen to your favorite songs, you open select_list
your playlist from your smartphone. In this case, the playlist FROM
is a database. table_name
ORDER BY
column1 [ASC|DESC],
When you take a photo and upload it to your account on a
column2 [ASC|DESC],
social network like Facebook, your photo gallery is a
...;
database.
If we didn’t mention any asc or desc its still ascending only

When you browse an e-commerce website to buy shoes,


clothes, etc., you use the shopping cart database. Using MySQL ORDER BY to sort data using a custom list

Databases are everywhere. So what is a database? By The ORDER BY clause allows you to sort data using a
definition, a database is merely a structured collection of custom list by using the FIELD() function.
data.
SELECT orderNumber, status FROM orders ORDER BY
FIELD(status, 'In Process', 'On Hold',
A relational database is a collection of data items with pre-
'Cancelled’, 'Resolved', 'Disputed', 'Shipped');
defined relationships between them. These items are
organized as a set of tables with columns and rows. Tables
are used to hold information about the objects to be Suppose that you want to sort the sales orders based on
represented in the database. their statuses in the following order:

A table may relate to another table using a relationship,


 In Process
e.g., one-to-one and one-to-many relationships.
 On Hold
SQL – the language of the relational database
 Canceled
SQL stands for the structured query language.
 Resolved

SQL is the standardized language used to access the  Disputed


database.  Shipped

SQL contains three parts:
To do this, you can use the FIELD() function to map each
1. Data definition language includes statements that order status to a number and sort the result by the result of
help you define the database and its objects, e.g., the FIELD() function:
tables, views, triggers, stored procedures, etc.
2. Data manipulation language contains statements that
SELECT DISTINCT –
allow you to update and query data.
3. Data control language allows you to grant the
It show you how to use the DISTINCT operator in
permissions to a user to access specific data in the
database. the SELECT statement to eliminate duplicate rows in a
result set.
MySQL is a database management system that allows you
to manage relational databases. MySQL DISTINCT and NULL values
If a column has NULL values and you use
the DISTINCT clause for that column, MySQL keeps only
one NULL value because DISTINCT treats all NULL values as
the same value.
SELECT state FROM customers GROUP BY state;
MySQL DISTINCT with multiple columns
You can use the DISTINCT clause with more than one
column. In this case, MySQL uses the combination of values
in these columns to determine the uniqueness of the row in
the result set.
For example, to get a unique combination of city and state
from the customers table, you use the following query:

SELECT DISTINCT state, city FROM customers WHERE state


IS NOT NULL ORDER BY state, city; You can achieve a similar result by using
the DISTINCT clause:
SELECT DISTINCT state FROM customers;

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
Without the DISTINCT clause, you will get the duplicate
the DISTINCT clause does not.
combination of state and city as follows:
If you add the ORDER BY clause to the statement that uses
SELECT state, city FROM customer WHERE state IS NOT
the DISTINCT clause, the result set is sorted and it is the
NULL ORDER BY state , city;
same as the one returned by the statement that
uses GROUP BY clause.

SELECT orderNumber `Order no.`, SUM(priceEach *


quantityOrdered) total
FROM orderDetails
GROUP BY `Order no.`
HAVING total > 60000;

SELECT customerName, COUNT(o.orderNumber) total


FROM customers c
DISTINCT clause vs. GROUP BY clause INNER JOIN
orders o
If you use the GROUP BY clause in the SELECT statement ON c.customerNumber = o.customerNumber
without using aggregate functions, the GROUP BY clause GROUP BY customerName
behaves like the DISTINCT clause. ORDER BY total DESC;
The following statement uses the GROUP BY clause to
select the unique states of customers
from the customers table.
Using

SELECT m.member_id, m.name member,


c.committee_id, c.name committee
FROM members m
INNER JOIN committees c
USING(name);

MySQL LEFT JOIN clause

SELECT m.member_id, m.name member,


c.committee_id, c.name committee
FROM members m
LEFT JOIN committees c
Introduction to MySQL join clauses USING(name);

A relational database consists of multiple related tables


linking together using common columns which are known
as foreign key columns. Because of this, data in each table
is incomplete from the business perspective.

MySQL Self Join

There is a special case that you need to join a table to itself,


which is known as a self join.
The self join is often used to query hierarchical data or to
compare a row with other rows within the same table.
CREATE TABLE members (
member_id INT AUTO_INCREMENT,
To perform a self join, you must use table aliases to not
name VARCHAR(100),
repeat the same table name twice in a single query. Note
PRIMARY KEY (member_id)
that referencing a table twice or more in a query without
);
using table aliases will cause an error.
CREATE TABLE committees (
committee_id INT AUTO_INCREMENT,
name VARCHAR(100),
PRIMARY KEY (committee_id) Using MySQL self join to compare successive rows
);
SELECT c1.city, c1.customerName, c2.customerName
SELECT m.member_id, m.name
FROM customers c1
member, c.committee_id, c.name committee
FROM members m INNER JOIN customers c2
INNER JOIN committees c
ON c.name = m.name; ON c1.city = c2.city

AND c1.customername > c2.customerName

ORDER BY

c1.city;
The HAVING clause is often used with the GROUP BY clause
to filter groups based on a specified condition. If
the GROUP BY clause is omitted, the HAVING clause
behaves like the WHERE clause.

To filter the groups returned by GROUP BY clause, you use


a HAVING clause. The following query uses
the HAVING clause to select the total sales of the years
after 2003.

SELECT YEAR(orderDate) AS year,


SUM(quantityOrdered * priceEach) AS total
In this example, the table customers is joined to itself using FROM orders
the following join conditions: INNER JOIN orderdetails
USING (orderNumber)
 c1.city = c2.city makes sure that both customers WHERE status = 'Shipped'
have the same city. GROUP BY year
 c.customerName > c2.customerName ensures that HAVING year > 2003;
no same customer is included.

SELECT
ordernumber,
SUM(quantityOrdered) AS itemsCount,
SUM(priceeach*quantityOrdered) AS total
FROM orderdetails
GROUP BY ordernumber;

SELECT
YEAR(orderDate) AS year,
SUM(quantityOrdered * priceEach) AS total
FROM orders
INNER JOIN orderdetails
USING (orderNumber)
WHERE status = 'Shipped'
GROUP BY YEAR(orderDate);

SELECT
ordernumber,
SUM(quantityOrdered) AS itemsCount,
Using MySQL GROUP BY with HAVING clause example SUM(priceeach*quantityOrdered) AS total
FROM orderdetails
GROUP BY ordernumber
The HAVING clause is used in the SELECT statement to HAVING
specify filter conditions for a group of rows or aggregates. total > 1000 ;
SELECT productLine, orderYear, SUM(orderValue)
totalOrderValue

FROM sales

GROUP BY productline, orderYear

WITH ROLLUP;

SELECT
ordernumber,
SUM(quantityOrdered) AS itemsCount,
SUM(priceeach*quantityOrdered) AS total
FROM orderdetails
GROUP BY ordernumber
HAVING
total > 1000
AND itemscount>600 ;

The ROLLUP generates the subtotal row every time


ROLLUP – generate multiple grouping sets considering a the product line changes and the grand total at the
hierarchy between columns specified in the GROUP end of the result.
BY clause. The ROLLUP clause is an extension of the GROUP
BY clause with the following syntax: Reversing the above hierarchy

SELECT
productLine,
SUM(orderValue) totalOrderValue
FROM
sales
GROUP BY
productline WITH ROLLUP;

SELECT orderYear,
productLine,
SUM(orderValue) totalOrderValue
FROMsales
GROUP BY
orderYear,
productline
WITH ROLLUP;
orderYear,
productline
WITH ROLLUP;

SELECT
IF(GROUPING(orderYear),
The ROLLUP generates the subtotal every time the 'All Years',
year changes and the grand total at the end of the orderYear) orderYear,
result set. IF(GROUPING(productLine),
'All Product Lines',
productLine) productLine,
SUM(orderValue) totalOrderValue
GROUPING() function
FROM
To check whether NULL in the result set represents the
sales
subtotals or grand totals, you use
GROUP BY
the GROUPING() function.
orderYear ,
The GROUPING() function returns 1 when NULL occurs in a
productline
supper-aggregate row, otherwise, it returns 0.
WITH ROLLUP;
The GROUPING() function can be used in the select
list, HAVING clause, and (as of MySQL 8.0.12 ) ORDER
BY clause.

SELECT
orderYear,
productLine,
SUM(orderValue) totalOrderValue,
GROUPING(orderYear),
GROUPING(productLine)
FROM
sales
GROUP BY
When the query is executed, the subquery runs first and
returns a result set. Then, this result set is used as an input for
the outer query.

SELECT
customerNumber, checkNumber, amount
FROM
payments
WHERE
amount = (SELECT MAX(amount) FROM payments);

SELECT customerNumber, checkNumber, amount


FROM payments
WHERE
amount > ( SELECT AVG(amount)
FROM payments);

MySQL Subquery
A MySQL subquery is a query nested within another query
such as SELECT, INSERT, UPDATE or DELETE. In addition, a
subquery can be nested inside another subquery.
A MySQL subquery is called an inner query while the query
that contains the subquery is called an outer query. A
subquery can be used anywhere that expression is used and
must be closed in parentheses.

SELECT lastName, firstName


FROM employees
WHERE officeCode IN ( SELECT officeCode  First, use a subquery to calculate the average payment
FROM offices using the AVG aggregate function.
WHERE country = 'USA' );  Then, query the payments that are greater than the
average payment returned by the subquery in the outer
query.
 The subquery returns all office codes of the offices MySQL subquery with IN and NOT IN operators
located in the USA.
If a subquery returns more than one value, you can use other
 The outer query selects the last name and first name of operators such as IN or NOT IN operator in the WHERE clause.
employees who work in the offices whose office codes
are in the result set returned by the subquery.
It returns 3 rows, meaning that there are 3 sales orders whose
total values are greater than 60K.

You can use the query above as a correlated subquery to find


customers who placed at least one sales order with the total
value greater than 60K by using the EXISTS operator:

SELECT customerNumber, customerName


FROM customers
We can use subquery not in operator to find out WHERE EXISTS
customers who have not placed any orders. ( SELECT
orderNumber, SUM(priceEach * quantityOrdered)
FROM orderdetails
SELECT customerName INNER JOIN
FROM customers orders USING (orderNumber)
WHERE customerNumber NOT IN (SELECT DISTINCT WHERE
customerNumber customerNumber = customers.customerNumber
FROM orders); GROUP BY orderNumber
HAVING SUM(priceEach * quantityOrdered) > 60000 );

Introduction to MySQL derived table


A derived table is a virtual table returned from
a SELECT statement. A derived table is similar to
a temporary table, but using a derived table in
the SELECT statement is much simpler than a temporary
table because it does not require steps of creating the
temporary table.

The term derived table and subquery is often used


interchangeably. When a stand-alone subquery is used in
the FROM clause of a SELECT statement, we call it a derived
table.
The following query finds sales orders whose total values are
greater than 60K.

SELECT orderNumber,
SUM(priceEach * quantityOrdered) total
FROM orderdetails
INNER JOIN orders USING (orderNumber)
GROUP BY orderNumber
HAVING SUM(priceEach * quantityOrdered) > 60000;
Unlike a subquery, a derived table must have a an alias so that
you can reference its name later in the query. If a derived
table does not have an alias, MySQL will issue the following SELECT productName, sales
error: FROM
(SELECT
1 Every derived table must have its own alias. productCode,
ROUND(SUM(quantityOrdered * priceEach)) sales
FROM
orderdetails
INNER JOIN orders USING (orderNumber)
WHERE
YEAR(shippedDate) = 2003
GROUP BY productCode
ORDER BY sales DESC
LIMIT 5) top5products2003
INNER JOIN
products USING (productCode);
The following query gets the top 5 products by sales revenue
in 2003 from the orders and orderdetails tables in the sample
database:

SELECT productCode,
ROUND(SUM(quantityOrdered * priceEach)) sales
FROM orderdetails
INNER JOIN
orders USING (orderNumber)
In this example:
WHERE YEAR(shippedDate) = 2003
GROUP BY productCode
ORDER BY sales DESC 1. First, the subquery executed to create a result set or
LIMIT 5; derived table.
2. Then, the outer query executed that joined
the top5product2003 derived table with
the products table using the productCode column.

BUT the above problem can be done through join itself .


Given below:

SELECT productName, ROUND(SUM(quantityOrdered *


You can use the result of this query as a derived table and join priceEach)) sales FROM orders INNER JOIN
it with the products table as follows
orderdetails USING (orderNumber)

INNER JOIN products USING (productCode)

WHERE YEAR(shippedDate) = 2003

GROUP BY productCode

ORDER BY sales DESC

LIMIT 5;

A more complex MySQL derived table example


Suppose you have to classify the customers in the year of
2003 into 3 groups: platinum, gold, and silver. In addition, you
need to know the number of customers in each group with
the following conditions: SELECT customerGroup,
COUNT(customerGroup) AS groupCount
1. Platinum customers who have orders with the volume FROM
greater than 100K
2. Gold customers who have orders with the volume (SELECT
between 10K and 100K customerNumber,
3. Silver customers who have orders with the volume less ROUND(SUM(quantityOrdered * priceEach)) sales,
than 10K (CASE
WHEN SUM(quantityOrdered * priceEach) <
To construct this query, first, you need to put each customer 10000 THEN 'Silver'
into the respective group using CASE expression and GROUP WHEN SUM(quantityOrdered * priceEach) BETWEEN
BY clause as follows:
10000 AND 100000 THEN 'Gold'
WHEN SUM(quantityOrdered * priceEach) > 100000
SELECT customerNumber, THEN 'Platinum'
ROUND(SUM(quantityOrdered * priceEach)) sales, END) customerGroup
FROM
(CASE orderdetails
WHEN SUM(quantityOrdered * priceEach) < 10000 INNER JOIN orders USING (orderNumber)
THEN 'Silver' WHERE
WHEN SUM(quantityOrdered * priceEach) BETWEEN YEAR(shippedDate) = 2003
10000 AND 100000 THEN 'Gold' GROUP BY customerNumber) cg
WHEN SUM(quantityOrdered * priceEach) > 100000
THEN 'Platinum' GROUP BY customerGroup;
END) customerGroup
FROM orderdetails (cg.customergroup can also be used)
INNER JOIN
orders USING (orderNumber)
WHERE YEAR(shippedDate) = 2003
GROUP BY customerNumber;

Introduction to MySQL EXISTS operator


The EXISTS operator is a Boolean operator that returns either
true or false. The EXISTS operator is often used to test for the
existence of rows returned by the subquery.

SELECT
select_list
FROM
a_table
WHERE
Then, you can use this query as the derived table and perform [NOT] EXISTS(subquery);
grouping as follows:
If the subquery returns at least one row, the EXISTS operator
returns true, otherwise, it returns false.
In addition, the EXISTS operator terminates further processing
immediately once it finds a matching row, which can help
improve the performance of the query.
The NOT operator negates the EXISTS operator. In other words,
the NOT EXISTS returns true if the subquery returns no row,
otherwise it returns false.
MySQL UPDATE EXISTS examples
SELECT customerNumber, customerName Suppose that you have to update the phone’s extensions of
FROM customers the employees who work at the office in San Francisco.
WHERE
EXISTS (SELECT
The following statement finds employees who work at the
1
office in San Franciso:
FROM orders
WHERE
SELECT employeenumber, firstname, lastname,
orders.customernumber
Extension FROM employees
= customers.customernumber);
WHERE EXISTS ( SELECT 1
FROM offices
WHERE
city = 'San Francisco' AND
offices.officeCode = employees.officeCode);

( OR )

SELECT employeenumber,firstname,lastname,
extension FROM employees
INNER JOIN offices
USING(officeCode)
WHERE city = 'San Francisco' ;
In this example, for each row in the customers table, the
query checks the customerNumber in the orders table. If
the customerNumber, which appears in
the customers table, exists in the orders table, the
subquery returns the first matching row. As a result,
the EXISTS operator returns true and stops examining
the orders table. Otherwise, the subquery returns no row
and the EXISTS operator returns false.

The following example uses the NOT EXISTS operator to


find customers who do not have any orders: This example adds the number 1 to the phone extension of
employees who work at the office in San Francisco:
SELECT customerNumber, customerName
FROM customers UPDATE employees
WHERE NOT EXISTS (SELECT 1 SET extension = CONCAT(extension, '1')
FROM orders WHERE EXISTS ( SELECT 1
WHERE FROM offices
orders.customernumber = WHERE
customers.customernumber city = 'San Francisco' AND
); offices.officeCode = employees.officeCode);
As you see the article with id 2 does not have
How it works. the excerpt, which is not nice for displaying.

 First, the EXISTS operator in the WHERE clause gets


A typical solution is to get the first number of
only employees who works at the office in San
Fransisco. characters in the body of the article for
 Second, the CONCAT() function concatenate the displaying as the excerpt. This is why
phone extension with the number 1. the COALESCE function comes into play.

SELECT id, title, COALESCE(excerpt, LEFT(body,


150)), published_at
Introduction to MySQL COALESCE FROM articles;
function

MySQL COALESCE and CASE


expression
SELECT id , title,
As you see, the state column has NULL values
(CASE
because some this information is not applicable WHEN excerpt IS NULL THEN LEFT(body, 150)
to the country of some customers. ELSE excerpt
END) AS excerpt,
published_at FROM articles;
To substitute the NULL value in the result set,
you can use the COALESCE function as follows:

SELECT
customerName, city, COALESCE(state, 'N/A'), MySQL GREATEST
country FROM customers;
and LEAST
Introduction to MySQL GREATEST
and LEAST functions
Both GREATEST and LEAST functions take N
arguments and return the greatest and smallest
values respectively.:
Another typical example of using
the COALESCE function is to substitute value in one
column by another when the first one is NULL.  If any argument is NULL, the both functions
return NULLs immediately without doing any
comparison.
 If functions are used in the INT or REAL
contexts, or all arguments are integer-valued
or REAL-valued, they are compared as INT
and REAL respectively.
 If arguments consists of both numbers and IFNULL(1,0) returns 1 because 1 is not NULL .
strings, the functions will compare them as
numbers. SELECT IFNULL(NULL,'IFNULL function'); --
returns IFNULL function
 If a least an argument is a non-binary
(character) string, the functions will compare IFNULL(NULL,'IFNULL
the arguments as non-binary strings. function') returns IFNULL function string
 In all other cases, the functions compare because the first argument is NULL.
arguments as binary strings. SELECT company_id,
LEAST(IFNULL(q1, 0),
SELECT GREATEST(10, 20, 30), ----- 30 IFNULL(q2, 0),
LEAST(10, 20, 30); -- 10 IFNULL(q3, 0),
IFNULL(q4, 0)) low,
GREATEST(IFNULL(q1, 0),
SELECT GREATEST(10, null, 30), ----- null IFNULL(q2, 0),
LEAST(10, null , 30); -- null IFNULL(q3, 0),
IFNULL(q4, 0)) high
FROM revenues;
INSERT INTO revenues(company_id,q1,q2,q3,q4)
VALUES (1,100,120,110,130),
(2,250,260,300,310);

SELECT company_id,
LEAST(q1, q2, q3, q4) low,
GREATEST(q1, q2, q3, q4) high
FROM revenues;
IF NULL

If there is null value in the column

INSERT INTO revenues(company_id,q1,q2,q3,q4)


VALUES (3,100,120,110,null); It would be nice if we can get the contact’s
home phone if the contact’s business phone is
SELECT company_id, not available. This is where the
LEAST(q1, q2, q3, q4) low,
GREATEST(q1, q2, q3, q4) high
FROM revenues; This is where the IFNULL function comes to
play. The IFNULL function returns the home
phone if the business phone is NULL.
Third, use the following query to get the names
and phones of all the contacts:

SELECT
As you can see, the low and high values of the contactname, IFNULL(bizphone, homephone)
company id 3 are NULLs. phone FROM contacts;

To avoid this, you can use the IFNULL function


as follows:
SELECT IFNULL(1,0); -- returns 1
Introduction to MySQL ISNULL
function
The ISNULL function takes one argument and
tests whether that argument is NULL or not.
The ISNULL function returns 1 if the argument
is NULL, otherwise, it returns 0.

INSERT INTO special_isnull(start_date)


VALUES('2000-01-01'), ('0000-00-00');
Using CASE expression with an
SELECT * FROM special_isnull
WHERE ISNULL(start_date); aggregate function example
The following example uses
the CASE expression with the SUM() function to
calculate the total of sales orders by order
status:

Using CASE expression in the ORDER SELECT


SUM(CASE
BY clause example WHEN status = 'Shipped' THEN 1
The following example uses ELSE 0
END) AS 'Shipped',
the CASE expression to sort customers by states SUM(CASE
if the state is not NULL, or sort the country in WHEN status = 'On Hold' THEN 1
case the state is NULL: ELSE 0
END) AS 'On Hold',
SELECT customerName, state, SUM(CASE
Country FROM customers WHEN status = 'In Process' THEN 1
ORDER BY ( ELSE 0
CASE END) AS 'In Process',
WHEN state IS NULL THEN country SUM(CASE
ELSE state WHEN status = 'Resolved' THEN 1
END) ; ELSE 0
END) AS 'Resolved',
SUM(CASE
WHEN status = 'Cancelled' THEN 1
ELSE 0
END) AS 'Cancelled',
SUM(CASE
WHEN status = 'Disputed' THEN 1
ELSE 0
END) AS 'Disputed',
COUNT(*) AS Total
FROM
orders;
 First, the CASE statement returns 1 if the
status equals the corresponding status
such as Shipped, on hold, in Process,
Cancelled, Disputed and zero otherwise.
 Second, the SUM() function returns the MySQL SUM IF – Combining the IF
total number of orders per order status. function with the SUM function
Introduction to MySQL IF function SELECT
SUM(IF(status = 'Shipped', 1, 0)) AS Shipped,
MySQL IF function is one of the MySQL control SUM(IF(status = 'Cancelled', 1, 0)) AS Cancelled
flow functions that returns a value based on a FROM orders;
condition. The IF function is sometimes referred
to as IF ELSE or IF THEN ELSE function.

MySQL COUNT IF – Combining the IF


function with the COUNT function
SELECT IF(1 = 2,'true','false'); -- false
SELECT DISTINCT status
SELECT FROM order ORDER BY status;
customerNumber, customerName, state, country
FROM customers;

Second, we can get the number of orders in


each status by combining the IF function with
the COUNT function. Because the COUNT function
We can improve the output by using
does not count NULL values, the IF function
the IF function to return N/A if the state is NULL
as the following query: returns NULL if the status is not in the selected
status, otherwise it returns 1. See the following
SELECT query:
customerNumber, customerName,
IF(state IS NULL, 'N/A', state) state, SELECT
country COUNT(IF(status = 'Cancelled', 1, NULL))
FROM customers; Cancelled,
COUNT(IF(status = 'Disputed', 1, NULL))
Disputed,
COUNT(IF(status = 'In Process', 1, NULL)) 'In
Process',
COUNT(IF(status = 'On Hold', 1, NULL)) 'On STR_TO_DATE - Converts a string into a date
Hold',
and time value based on a specified format.
COUNT(IF(status = 'Resolved', 1, NULL))
'Resolved',
SYSDATE - Returns the current date.
COUNT(IF(status = 'Shipped', 1, NULL))
'Shipped'
TIMEDIFF - Calculates the difference between
FROM
orders; two TIME or DATETIME values.

TIMESTAMPDIFF - Calculates the difference


between two DATE or DATETIME values.
If we add count(*) as total then it will show the total in WEEK - Returns a week number of a date.
another column.
WEEKDAY - Returns a weekday index for a
SELECT status, count(status) date.
FROM orders
group by status with rollup; YEAR - Return the year for a specified date
it will display in a single column with total but not CURDATE
as single row .
SELECT CURRENT_DATE(),
CURRENT_DATE,
CURDATE();
MySQL Date Functions +----------------+--------------+------------+
| CURRENT_DATE() | CURRENT_DATE |
CURDATE - Returns the current date. CURDATE() |
+----------------+--------------+------------+
DATEDIFF - Calculates the number of days | 2017-07-13 | 2017-07-13 | 2017-07-13 |
between two DATE values.
DATEDIFF - Calculates the number of days
DAY - Gets the day of the month of a specified between two DATE values.
date.
SELECT orderNumber,
DATE_ADD - Adds a time value to date value. DATEDIFF(requiredDate, shippedDate) daysLeft
FROM orders
DATE_SUB - Subtracts a time value from a ORDER BY daysLeft DESC;
date value.
DATE_FORMAT - Formats a date value based
on a specified date format.
DAYNAME - Gets the name of a weekday for a
specified date.
DAYOFWEEK - Returns the weekday index for
a date.
EXTRACT - Extracts a part of a date.
LAST_DAY - Returns the last day of the month
of a specified date The following statement gets all orders whose
NOW - Returns the current date and time at statuses are in-process and calculates the
which the statement executed. number of days between ordered date and
MONTH - Returns an integer that represents a required date:
month of a specified date.
SELECT orderNumber,
DATEDIFF(requiredDate, orderDate)
remaining_days
FROM orders
WHERE status = 'In Process'
ORDER BY remaining_days;

For calculating an interval in week or month,


you can divide the returned value of
the DATEDIFF function by 7 or 30 as the
following query:

SELECT orderNumber, MONTH


ROUND(DATEDIFF(requiredDate, orderDate) / 7, 2),
ROUND(DATEDIFF(requiredDate, orderDate) / 30,2) SELECT MONTH('2010-01-01');
FROM orders +---------------------+
WHERE status = 'In Process'; | MONTH('2010-01-01') |
+---------------------+
| 1|

DATE_ADD function

The DATE_ADD function adds an interval to


a DATE or DATETIME value.

SELECT
DATE_ADD('1999-12-31 23:59:59',
DAY() function INTERVAL 1 SECOND) result;

+---------------------+
The DAY() function returns the day of the month | result |
of a given date. +---------------------+
| 2000-01-01 00:00:00 |
SELECT DAY('2010-01-15'); +---------------------+

OUTPUT : 15 Add 1 minute and 1 second to 1999-12-31


23:59:59.
The following statement uses the DAY() function to DATE_ADD('1999-12-31 23:59:59',
return the number of orders by day number in 2003. INTERVAL '1:1' MINUTE_SECOND)

SELECT DAY(orderdate) dayofmonth, We can add hour day month second by giving interval
COUNT(*) FROM orders and date_add etc..
WHERE YEAR(orderdate) = 2004
GROUP BY dayofmonth
ORDER BY dayofmonth;
DATE_SUB function +------------------------+
The DATE_SUB() function subtracts a time value SELECT LAST_DAY(CURDATE());
(or an interval) from a DATE or DATETIME value.
It will display the last date of that month
SELECT DATE_SUB('2017-07-04',INTERVAL 1
DAY) result; SELECT LAST_DAY(CURDATE() + INTERVAL 1
+------------+ MONTH);
| result |
+------------+ It will display the last date of next month
| 2017-07-03 |

DATE_FORMAT function SELECT FIRST_DAY('2017-02-15');

It will display the first date of that month


To format a date value to a specific format, you
use the DATE_FORMAT function.
NOW() function
DAYNAME function
MySQL DAYNAME function returns the name of a The MySQL NOW() function returns the current
weekday for a specified date. date and time in the configured time zone as a
SELECT DAYNAME('2000-01-01') dayname; string or a number in the 'YYYY-MM-DD
+----------+ HH:MM:DD' or 'YYYYMMDDHHMMSS.uuuuuu' form
| dayname | at.
+----------+
| Saturday | SELECT NOW ( ) ;

DAYOFWEEK Function
If you want to get exact time at which the
The DAYOFWEEK function returns the weekday statement executes, you need to
index for a date i.e., 1 for Sunday, 2 for Monday, use SYSDATE()
… 7 for Saturday.
SELECT SYSDATE(), SLEEP(5), SYSDATE();
SELECT DAYNAME('2012-12-01'),
DAYOFWEEK('2012-12-01');
+-----------------------+-------------------------+
| DAYNAME('2012-12-01') | DAYOFWEEK('2012-12-
01') |
+-------------------------------+-------------------------+ It seems that
| Saturday | 7| both SYSDATE() and NOW() functions return a
same value which is the current date and time
LAST_DAY() function at which it is executed.
The LAST_DAY() function takes However, the SYSDATE() function actually
a DATE or DATETIME value and returns the last day of returns the time at which it executes while
the month for the input date. the NOW() function returns a constant time at
which the statement began to execute.
SELECT LAST_DAY('2016-02-03');

+------------------------+ TIMEDIFF function


| LAST_DAY('2016-02-03') | The TIMEDIFF returns the difference between
+------------------------+ two TIME or DATETIME values
| 2016-02-29 |
SELECT TIMEDIFF('12:00:00','10:00:00') diff; SELECT
TIMESTAMPDIFF (MINUTE, '2010-01-01
Output: 02:00:00 10:00:00', '2010-01-01 10:45:59') result ;

SELECT Here the output will 45 only . The difference


TIMEDIFF('2010-01-01 01:00:00',
should be 45 minutes 59 seconds. However, we
'2010-01-02 01:00:00') diff ;
pass the unit argument as MINUTE, therefore,
Output: -24:00:00 the function returns 45 minutes as expected.

SELECT TIMESTAMPDIFF( SELECT


HOUR, TIMESTAMPDIFF (SECOND, '2010-01-01
'2009-01-01 00:00:00', 10:00:00', '2010-01-01 10:45:59') result ;
'2009-03-01 00:00:00') diff;
Output: 2759
Output: 1416 45 minutes 59 second = 45 x 60 + 59 (seconds)
= 2759 seconds
The above statement would come wrong in
TIMEDIFF function .if it shows for warning we can SELECT id, full_name, date_of_birth,
go for TIMESTAMPDIFF TIMESTAMPDIFF (YEAR, date_of_birth,
NOW()) age
TIMESTAMPDIFF function FROM persons;

The TIMESTAMPDIFF function allows its


arguments to have mixed types e.g., begin is
a DATE value and end is a DATETIME value. In
case you use a DATE value,
the TIMESTAMPDIFF function treats it as
a DATETIME value whose time part
is '00:00:00'.
DAY NAME AND WEEKDAY
SELECT
SELECT DAYNAME('2010-01-01'),
TIMESTAMPDIFF (MONTH, '2010-01-01',
'2010-06-01') result; WEEKDAY('2010-01-01');

Output: 5 +-----------------------+-----------------------+
| DAYNAME('2010-01-01') | WEEKDAY('2010-01-
SELECT 01') |
TIMESTAMPDIFF (DAY, '2010-01-01', '2010-06- +-----------------------+-----------------------+
01') result; | Friday | 4|
+-----------------------+-----------------------+
Output: 151

SELECT
TIMESTAMPDIFF(MINUTE, '2010-01-01
10:00:00', '2010-01-01 10:45:00') result;

Output: 45
Note that the TIMESTAMPDIFF only considers the
time part that is relevant to the unit argument.
MySQL Window
Functions

The SUM() window function reports not only the


total sales by fiscal year like it does in the query
with the GROUP BY clause, but also the result in
each row, rather than the total number of rows
SELECT SUM(sale) FROM sales; returned.
OUTPUT :1500
The ORDER BY clause specifies the logical order
SELECT fiscal_year, SUM(sale) of the rows in each partition or the whole result
FROM sales set in case the PARTITION BY is omitted.
GROUP BY fiscal_year; The CUME_DIST() function calculates the
cumulative distribution value of each row based
on its order in the partition.

CUME_DIST Function
In both examples, the aggregate functions
reduce the number of rows returned by the ROW_NUMBER() / total_rows
query.
SELECT name, score,
ROW_NUMBER() OVER (ORDER BY score)
Like the aggregate functions with the GROUP row_num,
BY clause, window functions also operate on a CUME_DIST() OVER (ORDER BY score)
subset of rows but they do not reduce the cume_dist_val
FROM scores;
number of rows returned by the query.

For example, the following query returns the


sales for each employee, along with total sales
of the employees by fiscal year:

SELECT fiscal_year, sales_employee, sale,


SUM(sale) OVER (PARTITION BY fiscal_year)
total_sales
FROM sales;
In this example, the score is sorted in ascending
order from 55 to 100. Note that
the ROW_NUMBER() function was added for
reference.

So how the CUME_DIST() function performs


calculation?

For the first row, the function finds the number


of rows in the result set, which have value less
than or equal to 55. The result is 2.
Then CUME_DIST() function divides 2 by the
total number of rows which is 10: 2/10. the
result is 0.2 or 20%. The same logic is applied
to the second row. DENSE_RANK
Function
Assigns a rank to every row within its partition
based on the ORDER BY clause. It assigns the
same rank to the rows with equal values. If two
or more rows have the same rank, then there
will be no gaps in the sequence of ranked
values.

SELECT val,
DENSE_RANK() OVER ( ORDER BY val
) my_rank
For the third row, the function finds the number FROM t;
of rows with the values less than or equal to 62.
There are four rows. Then the result of
the CUME_DIST() function is: 4/10 = 0.4 which is
40%.
The same calculation logic is applied to the
remaining rows.

ROW_NUMBER
Function Rank
SELECT val,
RANK() OVER ( ORDER BY val ) my_rank
FROM t ;
SELECT ROW_NUMBER() OVER (
ORDER BY productName
) row_num, productName, msrp
FROM products
ORDER BY productName;
Sales table

SELECT sales_employee, fiscal_year, sale,


DENSE_RANK() OVER (PARTITION BY
fiscal_year ORDER BY sale DESC) sales_rank NTH_VALUE Function
FROM sales;
The NTH_VALUE() is a window function that
allows you to get a value from the Nth row in an
ordered set of rows.

SELECT employee_name, salary,


NTH_VALUE(employee_name, 2) OVER (
ORDER BY salary DESC
) second_highest_salary
FROM basic_pays;

 First, the PARTITION BY clause divided


the result sets into partitions using fiscal
year.
 Second, the ORDER BY clause specified
the order of the sales employees by sales
in descending order.
 Third, the DENSE_RANK() function is
applied to each partition with the rows
order specified by the ORDER BY clause.
FIRST VALUE
PERCENT_RANK() over the partition
SELECT employee_name, hours,
FIRST_VALUE(employee_name) OVER (
ORDER BY hours) least_over_time SELECT productLine , orderYear, orderValue,
FROM overtime ; ROUND( PERCENT_RANK() OVER (
PARTITION BY orderYear
ORDER BY orderValue
),2) percentile_rank
FROM productLineSales;

Percentile Rank:

SELECT productLine, orderValue,


ROUND( PERCENT_RANK() OVER (
ORDER BY orderValue ) ,2) percentile_rank
FROM t;

 First, we used a common table expression


to summary the order values by product
lines.
 Second, we used the PERCENT_RANK() to
calculate the percentile rank of order
value of each product. In addition, we
used the ROUND() function to round the
values to 2 decimal for a better SQL query to find second
representation.
highest salary?
SELECT name, MAX(salary) AS salary
FROM employee
WHERE salary < (SELECT MAX(salary)
FROM employee);
SELECT name, MAX(salary) AS salary
FROM employee
WHERE salary IN
(SELECT salary FROM employee MINUS
SELECT MAX(salary)
FROM employee);

How to find the third largest salary?


SELECT name, MAX(salary) AS salary
FROM employee
WHERE salary < (SELECT MAX(salary)
FROM employee
WHERE salary <
(SELECT MAX(salary)
FROM employee)
);

2nd highest salary in each department

SELECT * FROM
(select e.employee_id,
rank() over(partition by
d.department_name order by salary
desc) RNK ,
e.salary ,
d.department_name
from employees e join departments d
on e.department_id = d.department_id)
A where A.RNK=2;

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy