0% found this document useful (0 votes)
34 views96 pages

CH5 SQL Commands Aggregate Functions and Joins

The document discusses various SQL commands, aggregate functions, and joins. It covers SQL syntax and statements, data types, operators, expressions, comments, aliases, and functions. Some key topics include SQL syntax being governed by ANSI and ISO, the use of semicolons to terminate statements, single-line and multi-line comments, common data types like strings, numbers, and dates, arithmetic and comparison operators, and aggregate functions to perform calculations on table columns.
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)
34 views96 pages

CH5 SQL Commands Aggregate Functions and Joins

The document discusses various SQL commands, aggregate functions, and joins. It covers SQL syntax and statements, data types, operators, expressions, comments, aliases, and functions. Some key topics include SQL syntax being governed by ANSI and ISO, the use of semicolons to terminate statements, single-line and multi-line comments, common data types like strings, numbers, and dates, arithmetic and comparison operators, and aggregate functions to perform calculations on table columns.
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/ 96

SQL COMMANDS,

AGGREGATE FUNCTIONS
& JOINS
MUHAIMIN P. MACAPUNDAG
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

SQL Syntax
 The syntax of SQL is governed by the American National
Standards Institute (ANSI) and the International Organization for
Standardization (ISO).
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

Statements
 SQL statements are very simple and straightforward like plain English
but with specific syntax.
 An SQL statement is composed of a sequence of keywords,
identifiers, etc. terminated by a semicolon (;). Here is an example of a
valid SQL statement.
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

For better readability you can also write the same statement, as follow:
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

Case Sensitivity in SQL


Consider another SQL statement that retrieves the records from
employees table:

The same statement can also be written, as follow:


SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

SQL Comments
 A comment is simply a text that is ignored by the database engine.
Comments can be used to provide a quick hint about the SQL
statement.
 SQL support single-line as well as multi-line comments. To write a
single-line comment start the line with two consecutive hyphens (--).
For example:
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

To write multi-line comments, start the comment with a slash followed


by asterisk (/*) and end the comment with an asterisk followed by a
slash (*/).
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

SQL Data Types


 SQL Data Types define the type of value that can be stored in a table
column
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

Common String Data Types


Data type Description
CHAR(size) A FIXED length string (can contain letters, numbers, and special
characters). The size parameter specifies the column length in
characters - can be from 0 to 255. Default is 1
VARCHAR(size) A VARIABLE length string (can contain letters, numbers, and
special characters). The size parameter specifies the maximum
column length in characters - can be from 0 to 65535
TINYTEXT Holds a string with a maximum length of 255 characters
TEXT(size) Holds a string with a maximum length of 65,535 bytes
MEDIUMTEXT Holds a string with a maximum length of 16,777,215 characters
LONGTEXT Holds a string with a maximum length of 4,294,967,295
characters
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

Common Numeric Data Types


Data type Description
TINYINT(size) A very small integer. Signed range is from -128 to 127. Unsigned range is from 0 to
255. The size parameter specifies the maximum display width (which is 255)

BOOL Zero is considered as false, nonzero values are considered as true.


BOOLEAN Equal to BOOL
SMALLINT(size) A small integer. Signed range is from -32768 to 32767. Unsigned range is from 0 to
65535. The size parameter specifies the maximum display width (which is 255)

MEDIUMINT(size) A medium integer. Signed range is from -8388608 to 8388607. Unsigned range is from
0 to 16777215. The size parameter specifies the maximum display width (which is 255)

INT(size) A medium integer. Signed range is from -2147483648 to 2147483647. Unsigned range
is from 0 to 4294967295. The size parameter specifies the maximum display width
(which is 255)
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

Common Numeric Data Types


Data type Description
TINYINT(size) A very small integer. Signed range is from -128 to 127. Unsigned range is from 0 to
255. The size parameter specifies the maximum display width (which is 255)

BOOL Zero is considered as false, nonzero values are considered as true.


BOOLEAN Equal to BOOL
SMALLINT(size) A small integer. Signed range is from -32768 to 32767. Unsigned range is from 0 to
65535. The size parameter specifies the maximum display width (which is 255)

MEDIUMINT(size) A medium integer. Signed range is from -8388608 to 8388607. Unsigned range is from
0 to 16777215. The size parameter specifies the maximum display width (which is 255)

INT(size) A medium integer. Signed range is from -2147483648 to 2147483647. Unsigned range
is from 0 to 4294967295. The size parameter specifies the maximum display width
(which is 255)
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

Common Numeric Data Types


DOUBLE(size, d) A normal-size floating point number.The total number of digits is
specified in size.The number of digits after the decimal point is
specified in the d parameter
DOUBLE Accepts approximate numeric values, up to a precision of 64.
PRECISION(size, d)
DECIMAL(size, d) An exact fixed-point number. The total number of digits is specified in size.
The number of digits after the decimal point is specified in the d parameter.
The maximum number for size is 65. The maximum number for d is 30. The
default value for size is 10. The default value for d is 0.
DEC(size, d) Equal to DECIMAL(size, d)
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

Common Date and Time Data Types


Data type Description
DATE A date. Format: YYYY-MM-DD. The supported range is from '1000-01-01' to '9999-12-31'

DATETIME(fsp) A date and time combination. Format: YYYY-MM-DD hh:mm:ss. The supported range is from
'1000-01-01 00:00:00' to '9999-12-31 23:59:59'. Adding DEFAULT and ON UPDATE in the column
definition to get automatic initialization and updating to the current date and time

TIMESTAMP(fsp) A timestamp. TIMESTAMP values are stored as the number of seconds since the Unix epoch
('1970-01-01 00:00:00' UTC). Format: YYYY-MM-DD hh:mm:ss. The supported range is from
'1970-01-01 00:00:01' UTC to '2038-01-09 03:14:07' UTC. Automatic initialization and updating to
the current date and time can be specified using DEFAULT CURRENT_TIMESTAMP and ON
UPDATE CURRENT_TIMESTAMP in the column definition

TIME(fsp) A time. Format: hh:mm:ss. The supported range is from '-838:59:59' to '838:59:59'

YEAR A year in four-digit format. Values allowed in four-digit format: 1901 to 2155, and 0000.
MySQL 8.0 does not support year in two-digit format.
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

Operators
An operator is a symbol specifying an action that is performed on one
or more expressions.
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

SQL Arithmetic Operators

Operator Description Example


+ Add SELECT 30 + 20;
- Subtract SELECT 30 - 20;
* Multiply SELECT 30 * 20;
/ Divide SELECT 30 / 10;
% Modulo SELECT 17 % 5;
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

SQL Comparison Operators


Operator Description EXAMPLE
= Equal to SELECT * FROM Products
WHERE Price = 18;
> Greater than SELECT * FROM Products
WHERE Price > 30;
< Less than SELECT * FROM Products
WHERE Price < 30;
>= Greater than or equal to SELECT * FROM Products
WHERE Price >= 30;
<= Less than or equal to SELECT * FROM Products
WHERE Price <= 30;
<> Not equal to SELECT * FROM Products
WHERE Price <> 18;
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

Expression
 An expression is a combination of one or more values, operators and
SQL functions that evaluate to a value. It is used to query the
database for a specific set of data.

Syntax:
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

Types of SQL expressions:


 Boolean
 Numeric
 Date
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

Boolean Expression
 SQL Boolean Expressions fetch the data based on matching a single
value.

Syntax:
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

Consider the CUSTOMERS table having the following records:


SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

The following table is an example of various SQL Boolean Expressions:


SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

Numeric Expression
 This is used to perform any mathematical operation in any query.

Syntax
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

Following is an example of SQL Numeric Expressions:


SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

There are several built-in functions like avg(), sum(), count(), etc., to
perform what is known as the aggregate data calculations against a table
or a column.
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

Date Expressions
 Date Expressions return current system date and time values.

Example:
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

SQL Aliasing
Alias is used to rename columns, tables, subqueries, anything.
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

SQL Aliasing
Alias is used to rename columns, tables, subqueries, anything.

SELECT column1, COUNT(column2) AS number_of_values


FROM table_name
GROUP BY column1;

This query counts the number of values in column2 - for each group of
unique column1 values. Then it renames the COUNT(column2) column
to number_of_values.
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

FUNCTIONS
SQL has many built-in functions for performing processing on string,
numeric, and date data.
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

Aggregate Functions
Group By Clause – It is used with SQL aggregate functions like SUM to
provide means of grouping the result dataset by certain database table
column(s).
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

Now, suppose based on the above table we want to count number of


days each employee did work. If we will write a SQL query as follows,
then we will get the following result:
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

But if we want to display total number of pages typed by each person


separately. This is done by using aggregate functions in conjunction with
a GROUP BY clause as follows:
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

MySQL IN Clause - This is a clause, which can be used along with any
MySQL query to specify a condition.
You can use IN clause to replace many OR conditions. To understand
IN clause, consider an employee_tbl table, which is having the
following records:
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

MySQL BETWEEN Clause - This is a clause, which can be used


along with any MySQL query to specify a condition.
BETWEEN clause is used to replace a combination of "greater than
equal AND less than equal" conditions. To understand BETWEEN
clause, consider an employee_tbl table, which is having the following
records:
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

Now, suppose based on the example table you want to fetch records
with conditions daily_typing_pages more than 170 and equal and less
than 300 and equal. This can be done using >= and <= conditions as
follows:
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

Same can be achieved using BETWEEN clause as follows:


SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

MySQL UNION Keyword - Use a UNION operation to combine


multiple result sets into one. UNION is used to select rows one after
the other from several tables or several sets of rows from a single table
all as a single result set.
Suppose you have two tables that list prospective and actual customers,
a third that lists vendors from whom you purchase supplies, and you
want to create a single mailing list by merging names and addresses
from all three tables. UNION provides a way to do this. Assume the
three tables have the following contents:
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

It does not matter if all the three tables have different column names.
The following query illustrates how to select names and addresses from
the three tables all at once:
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

If you want to select all records, including duplicates, follow the first
UNION keyword with ALL:
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

MySQL COUNT Function - The MySQL COUNT aggregate


function is used to count the number of rows in a database table.

Syntax
SELECT COUNT (Column_Name) FROM table_name
WHERE Condition;
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

COUNT function is the simplest function and very useful in counting the
number of records, which are expected to be returned by a SELECT
statement. To understand COUNT function, consider an employee_tbl
table, which is having the following records:
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

To count the total number of rows in this table, then you can do it as
follows:
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

MySQL MAX Function - The MySQL MAX aggregate function


allows us to select the highest (maximum) value for a certain column.
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

MySQL MIN Function - The MySQL MIN aggregate function


allows us to select the lowest (minimum) value for a certain column.
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

MySQL SUM Function - The MySQL SUM aggregate function


allows selecting the total for a numeric column.
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

MySQL AVG Function - The MySQL AVG aggregate function


selects the average value for certain table column. The AVG function
is used to find out the average of a field in various records.
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

String Functions
String functions are used to manipulate strings in MySQL.
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

MySQL CONCAT Function - This is used to concatenate any


string inside any MySQL command. MySQL CONCAT function is
used to concatenate two strings to form a single string.
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

LEFT() – Returns the leftmost number of characters as specified –


LEFT (str, len)
Returns the leftmost len characters from the string str, or NULL if
any argument is NULL.
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

RIGHT() – Returns the specified rightmost number of characters –


RIGHT(str, len).
Returns the rightmost len characters from the string str, or NULL if
any argument is NULL.
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

LENGTH() – Returns the length of a string in bytes – LENGTH(str)


Returns the length of the string str, measured in bytes. A multi-byte
character counts as multiple bytes.
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

LOWER() – Returns the argument in lowercase – LOWER(str)


LCASE() – Synonym for LOWER()
Returns the string str with all characters changed to lowercase
according to the current character set mapping.
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

UPPER() – Converts to uppercase – UPPER(str)


UCASE() – Synonym for UPPER()
Returns the string str with all characters changed to uppercase
according to the current character set mapping.
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

LTRIM() – Removes leading spaces – LTRIM(str)


Returns the string str with leading space characters removed.
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

RTRIM() – Removes trailing spaces


Returns the string str with trailing space characters removed.
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

TRIM() – Removes leading and trailing spaces


TRIM([{BOTH | LEADING | TRAILING} [remstr] FROM] str)
TRIM([remstr FROM] str)
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

REVERSE() – Reverses the characters in a string – REVERSE(str)


Returns the string str with the order of the characters reversed.
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

Date Functions
These functions are used to retrieve and return date values based
from specified expressions.

DATE(expr)
Extracts the date part of the date or datetime expression expression.
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

DATE_FORMAT(date,format)
Formats the date value according to the format string. The following
specifiers may be used in the format string. The .%. character is
required before format specifier characters.
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

DATEDIFF(expr1,expr2)
DATEDIFF() returns expr1 . expr2 expressed as a value in days from
one date to the other. expr1 and expr2 are date or date-and-time
expressions. Only the date parts of the values are used in the
calculation.
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

CURDATE()
Returns the current date as a value in 'YYYY-MM-DD' or
YYYYMMDD format

TIME()
Returns the time from the given date.
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

CURTIME() - Returns the current time as a value in 'HH:MM:SS' or


HHMMSS format, depending on whether the function is used in a
string or numeric context.

NOW - Returns the current date and time as a value in 'YYYY-MM-


DD HH:MM:SS' or YYYYMMDDHHMMSS format. Also the same with
current time stamp
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

DAYNAME(date) - Returns the name of the weekday for date.

DAYOFMONTH(date) - Returns the day of the month for date, in


the range 0 to 31.
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

DAYOFWEEK(date) - Returns the weekday index for date (1 =


Sunday, 2 = Monday, ., 7 = Saturday).

DAYOFYEAR(date) - Returns the day of the year for date, in the


range 1 to 366.
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

HOUR(time) – same as MINUTE(), SECOND()


Returns the hour for the time. The range of the return value is 0 to
23 for time-of-day values. However, the range of TIME values actually
is much larger, so HOUR can return values greater than 23.
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

USING JOINS
The most frequently used relational operation, which brings together
data from two or more related tables into one resultant table.

The act of joining in MySQL refers to smashing two or more tables


into a single table. JOIN clause combines rows from two or more
tables.This creates a set of rows in a temporary table.
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

Types of SQL JOIN


 EQUI JOIN
 EQUI JOIN is a simple SQL join.
 Uses the equal sign(=) as the comparison operator for the condition
 NON EQUI JOIN
 NON EQUI JOIN uses comparison operator other than the equal
sign.
 The operators uses like >, <, >=, <= with the condition.
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

List of SQL JOINS


 INNER JOIN
 LEFT JOIN OR LEFT OUTER JOIN
 RIGHT JOIN OR RIGHT OUTER JOIN
 FULL JOIN
 NATURAL JOIN
 CROSS JOIN
 SELF JOIN
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

INNER JOIN
 The INNER JOIN selects all rows from both participating tables as
long as there is a match between the columns.
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

Syntax
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

INNER JOIN statement

Output
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

LEFT JOIN OR LEFT OUTER JOIN


 The LEFT JOIN keyword returns all records from the left table
(table1), and the matched records from the right table (table2). The
result is NULL from the right side, if there is no match.
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

Syntax
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

LEFT JOIN Statement

Output
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

RIGHT JOIN
 The RIGHT JOIN keyword returns all records from the right table
(table2), and the matched records from the left table (table1). The
result is NULL from the left side, when there is no match
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

Syntax
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

RIGHT JOIN Statement

Output
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

FULL JOIN
 The FULL OUTER JOIN keyword returns all records when there is
a match in left (table1) or right (table2) table records, and may
return very large results. However, MySQL does not support FULL
JOIN.
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

Syntax
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
(optional condition)
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

USING ALISAING ON JOINS


 To alias a table, write the alias for a specific table after its name as
shown below. Here, CustomerTable is being aliased as cs and
CityTable is aliased as cy.
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

NATURAL JOIN
 In MySQL, the NATURAL JOIN is such a join that performs the
same task as an INNER or LEFT JOIN, in which the ON or USING
clause refers to all columns that the tables to be joined have in
common.
 The MySQL NATURAL JOIN is structured in such a way that,
columns with the same name of associate tables will appear once
only.
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

Syntax
SELECT column_name(s)
FROM table1
NATURAL JOIN
table2
NATURAL JOIN
table3...;
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

Example:
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

CROSS JOIN
 A cross join (also called a Cartesian join) is a join of tables
without specifying the join condition. In this scenario, the query
would return all possible combination of the tables.
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

Note: If you don't specify a join condition when joining two tables,
database system combines each row from the first table with each
row from the second table. This type of join is called a cross join or a
Cartesian product. So, if one table has 5 rows and another has 10
rows, a cross-join query produces 50 rows.

Syntax
SELECT column_name(s) FROM table1 CROSS JOIN
table2;
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

Example
Store_Information Geography
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

A1 is the alias used for table Geography


A2 is the alias used for table Store_Information
Notice that on SELECT statement, A1.Store_Name STORE1 is
like identifying Geography that has a field Store_Name.
Likewise, Store_Name from Geography table is aliased as STORE1
SQL COMMANDS, AGGREGATE FUNCTIONS & JOINS

Output

You might also like