Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

SQL

The document provides an overview of database concepts, focusing on SQL and the relational data model. It explains key terms such as databases, DBMS, data models, and various types of keys, along with an introduction to SQL and its data types. Additionally, it covers SQL operators, null handling, comments, and the classification of SQL command languages.

Uploaded by

asdf lkjh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

SQL

The document provides an overview of database concepts, focusing on SQL and the relational data model. It explains key terms such as databases, DBMS, data models, and various types of keys, along with an introduction to SQL and its data types. Additionally, it covers SQL operators, null handling, comments, and the classification of SQL command languages.

Uploaded by

asdf lkjh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Class 12 Computer Science – SQL

Database Concepts

• Data is a collec)on of characters, numbers, and other symbols that represents values of
some situa)ons or variables. Data – plural; Datum – singular.

• A Database is an organized collec)on of data stored in electronic media.

• A Database Management System (DBMS) is a so>ware system that enables users to define,
create, maintain and control access to the database. Example: MySQL, Oracle, MongoDB.

• A Database along with DBMS so>ware is called Database System.

• Data Model refers to the model used for organizing or storing data in a database.
o Rela5onal Data Model organizes data as a collec)on of two-dimensional
inter-related tables called rela)ons.
o Hierarchical Data Model organizes data into a tree-like structure with each record
(collec)on of fields) having a single parent. A record can have any number of child
records.
o Network Data Model organizes data into a network of inter-linked records (i.e.,
organized like a graph) with no restric)ons on the number of links a record can have.
o Object-Oriented Data Model organizes data into inter-related objects that mirror
objects in object-oriented programming languages.
Relational Data Model
The Relational Data Model organizes data as a collection of two dimensional inter related tables
called relations.
• Rela5on – A collec)on of tuples
• Tuple – A tuple is a set of aQribute values for the aQributes in a rela)on
• AEribute – The column/field of a table/rela)on is known as an aQribute.
• Domain – The domain of an aQribute is the set of permissible values that the aQribute can
take.
• Degree – Number of aEributes in the rela)on.
• Cardinality – Number of tuples in the rela)on.

A database that is modelled on rela)onal data model concept is called Rela5onal Database. A DBMS
that works with rela)onal databases is called a Rela5onal Database Management System (RDBMS).

Examples of Schema Diagram of a Database

Three Important Properties of a Relation


Property 1: (rules on attributes)
• Each aQribute in a rela)on has a unique name.
• Sequence of aQributes in a rela)on is immaterial.

Property 2: (rules on tuples)


• Each tuple in a rela)on is dis)nct.
• Sequence of tuples in a rela)on is immaterial.

Property 3: (rules on state [i.e., attribute values])


• All values of an aQribute must be from the same domain.
• Each value associated of an aQribute must be atomic.
• No aQribute can have mul)ple data values in one tuple
• A special value NULL is used to represent values that are unknown or not-applicable.
Keys

• Candidate Key – An aQribute (or a combina)on of aQributes) that uniquely iden)fies every
tuple in a rela)on is a Candidate Key of the rela)on.

• Primary Key – The Primary Key of a rela)on is an aQribute (or a combina)on of aQributes)
that uniquely iden)fies every tuple in a rela)on (i.e., a Candidate Key) and is the key that is
designated as the most appropriate one to uniquely iden)fy every tuple in the rela)on.

• Alternate Key – Alternate Keys are all the Candidate Keys of a rela)on that are not the
Primary Key.

• Composite Key – A key consis)ng of two or more aQributes.

• Foreign Key

o Referenced table is the table referenced by the foreign key.

o Referencing table is the table where the foreign key is defined.

o Referenced & Referencing tables are also called:


§ Parent & Child tables
§ Primary & Related tables

o Foreign key aQribute values can be NULL

SQL (MySQL)
Introduction

Structured query language (SQL) is a programming language for storing and processing information
in a relational database.

SQL is the standard query language used across all RDBMSs. The level of support for SQL by different
RDBMS implementations may vary.

MySQL is an open source RDBMS that is developed, distributed, and supported by Oracle
Corporation. MySQL uses SQL as the query language.

Relational Data Model Terminology SQL Terminology


Relation Table
Tuple Row
Attribute Column
Domain Data Type
The domain is further restricted by constraints
like NOT NULL, CHECK etc.
References

Official Website
https://www.mysql.com/

MySQL 8.0 Reference Manual


https://dev.mysql.com/doc/refman/8.0/en/

PEP 249 – Python Database API Specification v2.0


https://peps.python.org/pep-0249/

MySQL GitHub
https://github.com/mysql

Data Types

Numeric Data Types

Data Type Name Data Type Synonyms Size Range


INT Integer INTEGER 4 bytes Signed: -231 to 231-1
Unsigned: 0 to 232-1
BIGINT Integer 8 bytes Signed: -263 to 263-1
Unsigned: 0 to 264-1
FLOAT Approximate 4 bytes As per IEEE standard
floa)ng-point number

DOUBLE Approximate DOUBLE 8 bytes As per IEEE standard


floa)ng-point number PRECISION,
REAL

DECIMAL(m, n) Fixed-point number DEC, Varies Varies


m – digits (precision including (stores exact value) NUMERIC,
frac)onal part) - 1 to 65. FIXED
Default value is 10.

n – digits a>er decimal point –


0 to 30. Default value is 0.

n <= m

Note:
• Unsigned numeric types have UNSIGNED added to the types name. For example,
INT UNSIGNED is an unsigned integer.

• Integer types and DECIMAL are called exact value types while FLOAT and DOUBLE are called
approximate value types.
String Data Types

Data Type Name Data Type Size Range


CHAR Fixed length n characters 0 <= n <= 255 (i.e, 28-1)
CHAR(n) string Default value is 1.
n – no. of characters

VARCHAR(n) Variable length Up to n 0 <= n <= 65535 (i.e, 216-1)


n – maximum no. of characters string characters

Date Data Type

Data Type Name Data Type Size Range


DATE Date 3 bytes Year 1000 to 9999

Literals

• Numeric Literals
o Exact value literals

§ Integers. The data type of the literal will be INT if the number can fit in the
INT data type. For numbers that cannot fit in INT, larger data types are used
in the following order BIGINT, BIGINT UNSIGNED, DECIMAL.
Examples: 1, 0, 191, -5

§ Decimals. The data type will be DECIMAL.


Examples: .2, 3.4, -6.78, +9.10, 0.5

o Approximate-value (floa)ng-point) literals. Numbers in exponen)al form. The data


type will be DOUBLE. Note that they are DOUBLE, NOT FLOAT.

Examples 1.2E3, 1.2e-3, -1.2E3, -1.2E-3. -0e1

• Date values are wriQen as strings in the format 'YYYY-MM-DD'. Note that these are string
literals that get automa)cally converted to DATE.

• String literals

o Enclosed in single or double quotes.


o In strings enclosed in single quotes.
§ Double quotes do not need escaping.
§ Single quotes can be escaped as two consecu)ve single quotes.
o In strings enclosed in double quotes.
§ Single quotes do not need escaping.
§ Double quotes can be escaped as two consecu)ve double quotes.
o Escape sequences in string literals. Note: \a \f and \v are not supported.
Escape Sequence Character Represented by Sequence
\0 An ASCII NUL (X'00') character
\' A single quote (') character
\" A double quote (") character
\b A backspace character
\n A newline (linefeed) character
\r A carriage return character
\t A tab character
\Z ASCII 26 (EOF)
\\ A backslash (\) character

Note: TRUE and FALSE pre-defined constants that evaluate to 1 and 0 respectively. They are
technically not literals.

Operators

Following is a subset of SQL operators in order of precedence. Parentheses can be used to override
precedence. Among infix operators with same precedence, le>-to-right associa)vity applies.

Precedence Operators Descrip5on Type


1 ! Same as NOT Logical
2 - + Unary minus and unary plus
Mathema)cal or
3 * / DIV MOD % Mul)plica)on & division
Arithme)c
4 + - Addi)on & subtrac)on
BETWEEN Range check
5
NOT BETWEEN
= >= > <= < != <> Regular comparisons
<=> NULL-safe equal to
String paQern matching. % matches zero or
more characters and _ (underscore) matches
LIKE
a single character. To match % or _ they Rela)onal
NOT LIKE
6 need to be escaped as \% and \_

IN Membership check
NOT IN
IS NULL Null check
IS NOT NULL
Logical not. 1 if operand is zero 0 if it is non-
7 NOT zero.

Logical and. 1 if both operands are non-zero.


8 AND && Else the result is 0.
Logical
Logical exclusive or. 1 if one operand is non-
zero and the other operand is zero. Else the
9 XOR
result is 0.

Logical and. 1 if at least one of the two


10 OR ||
operands is non-zero. Else the result is 0.
DIV and MOD

• x DIV y is calculated as truncate(x/y). – here the truncate opera)on discards the frac)onal
part. Example: –10.1 DIV 3 is –3.
• Data type DIV return value depends on the data type of operands but the result will always
be an integer value.
• x MOD y is calculated as x - (x DIV y) * y. Example: –10.1 MOD 3 is –1.1.
• x MOD y, if non-zero, will have the sign of the x (1st operand).
• % is same as MOD.

Case Insensi5ve string comparison

All string comparisons are case insensi5ve.

Precision Increment in Division

In a division opera)on expr1 / expr2 where expr1 and expr2 are exact value numeric types the data
type of the result will have a scale (i.e., no. of digits a>er decimal point) that is four more than the
scale of expr1. The scale of expr2 has no effect on the scale of the result. Note that the increased
scale will not be larger than 30. The value of the result will be Examples:

2.6 / 3 will give 0.86667


2.6 / 2 will give 0.30000
4 / 2 will give 2.0000
4 / 0.25 will give 16.0000
4 / 0.25 / 2 will give 8.00000000
Note: Intermediate results will hold more decimal places for accurate calcula)on. For example, 1/3
will return 0.3333 but 1/3*1000*100 will return 33333.3333 as more digits are stored for the
intermediate result of 1/3.
Null handling

• Division operators (DIV MOD / %) give NULL as result when right side operand is zero.

• expr IS NULL will evaluate to true (i.e., 1) if expr is NULL

• expr IS NOT NULL will evaluate to true (i.e., 1) if expr is not NULL

• Following rules apply if one or more expressions is NULL in expr IN (expr1, expr2, …).
o If expr is NULL the result will be NULL.
o If expr is not NULL and is present in the list, result will be true (i.e., 1).
o If expr is not NULL & not present in the list and the list has one or more NULLs, the
result will be NULL.
• Following rules apply if one or more expressions is NULL in expr NOT IN (expr1, expr2, …).
o If expr is NULL the result will be NULL.
o If expr is not NULL and is present in the list, result will be false (i.e., 1).
o If expr is not NULL & not present in the list and the list has one or more NULLs, the
result will be NULL.

• The result of <=> (NULL-safe equal to operator) will never be NULL. Following rules apply if
one or more operands of <=> is NULL.
o If both operands are NULL, result is true (i.e., 1).
o If only one of the operands is NULL, result is false (i.e., 0).

• Except for the above rules the result of all other operators will be NULL when any of the
operands is NULL.

Comments
#…………………..
Begins with # and ends with new-line.
-- …………………..
Begins with -- followed by a space and ends with new-line.
/*…………………..*/
Begins with /* and ends with */ can span mul)ple lines.

Statements

Statement Syntax

Keywords – Words that have special meaning in MySQL. Keywords cannot be used for any user
defined names like table names, column names etc. Example of keywords: CREATE, SELECT, INSERT,
etc.

Statements (or Commands) – Instruc)ons given to the database to perform some ac)on.

Clauses – A statement consists of one or more logically dis)nct parts called clauses. Clauses begin
with a keyword which is followed by arguments.

Classifica5on of SQL Command Languages

1. DDL (Data Defini)on Language)


(i) Crea)ng, modifying and removing schema objects
(ii) Data Control Language (DCL) – manage security permissions
(iii) Maintenance Commands

Rule of thumb: All CREATE, ALTER and DROP statements are DDL.

Note: TRUNCATE is works as a DDL command though it only deletes data without changing
the schema. Just to be safe – don’t give TRUNCATE as an example for DDL. Men)on
TRUNCATE only when it is really required.

2. DML (Data Manipula)on Language)


(i) Retrieval
(ii) Inser)on
(iii) Dele)on
(iv) Modifica)on

Rule of thumb: All INSERT, UPDATE, DELETE and SELECT statements are DML.

3. TCL (Transac)on Control Language) – For transac)on management


4. Session Control Commands

5. System Control Commands

Refer pages 520-521.

Database Commands

• CREATE DATABASE database_name; -- database_name is case sensi)ve in Unix


• CREATE DATABASE IF NOT EXISTS database_name; -- does not fail if database
already exists. Note: USE commend is needed to select the newly created database.

• SHOW DATABASES;

• USE database_name; -- sets the default database for subsequent commands. Note: This
is also referred to as “opening the database”, though it is technically not the case.

• DROP DATABASE database_name;


• DROP DATABASE IF EXISTS database_name;

• SHOW TABLES;

• DESCRIBE table_name;
• DESC table_name; -- same as DESCRIBE

• SHOW CREATE TABLE table_name; -- shows the complete defini)on of a table as a


CREATE statement

Constraints

Constraints ensure database integra)ng. Also called Database Integrity Constraints. Constraints
define certain restric)ons for the data that can be stored in the tables.

Column Constraint – A constraint applied to a single column.


Table Constraint – A constraint applied to two or more columns in a table.

Types of Constraints:

• NOT NULL Constraint


• DEFAULT Constraint
• PRIMARY KEY Constraint
• UNIQUE Constraint
• FOREIGN KEY Constraint
• CHECK Constraint

NOT NULL and DEFAULT constraints can be defined only as column constraints.

PRIMARY KEY, UNIQUE, FOREIGN KEY and CHECK can be defined as both column constraints and
table constraints.
CREATE TABLE Statement

CREATE TABLE table_name (


column_name1 data_type [DEFAULT literal] [[NOT] NULL] [PRIMARY KEY | UNIQUE],...
PRIMARY KEY (column_name1,...)
UNIQUE (column_name1,...),...
FOREIGN KEY (column_name1,...) REFERENCES ref_table_name (ref _column_name1,...),...
)

• Columns that are part of the PRIMARY KEY cannot be specified as nullable.

• If NULL or NOT NULL is not explicitly specified, NOT NULL is assumed for primary key
columns and NULL is assumed for other columns.
Note: Explicitly specifying nullable columns is redundant and causes no change in the
behaviour.

• If DEFAULT value is not specified, it is taken as NULL for nullable columns.

• DEFAULT values cannot be specified as NULL when


o The column is explicitly specified as NOT NULL
o The column is part of the PRIMARY KEY

• The referenced columns in a FOREIGN KEY should be a UNIQUE constraint or be the


PRIMARY KEY of the referenced table.

DROP TABLE Statement

DROP TABLE table_name


DROP TABLE IF EXISTS table_name

• A table referred to by a foreign key cannot be dropped

ALTER TABLE Statement

Adding a single column

ALTER TABLE table_name ADD


column_name data_type [DEFAULT literal] [[NOT] NULL] [PRIMARY KEY | UNIQUE]

• A primary key column can be added only if the table does not already have a primary key.

• All exis)ng records get the DEFAULT value as the value for the newly added column. For
nullable columns with DEFAULT value, all rows get NULL as the value for the newly added
column.

• When a TIME or numeric NOT NULL column is added without DFAULT value, all exis)ng
records get zero as the value for the newly added column.

• When a string NOT NULL column is added without DFAULT value, all exis)ng records get
empty string as the value for the newly added column.
• Adding a DATETIME/TIMESTAMP NOT NULL column without DFAULT value to a table already
containing rows will cause an error.

Adding multiple columns

ALTER TABLE table_name ADD


(column_name data_type ([DEFAULT literal] [[NOT] NULL] [PRIMARY KEY | UNIQUE],...)

Note that the list of column defini)ons is enclosed in parentheses, as in CREATE TABLE.

Removing a column

ALTER TABLE table_name DROP column_name

• A column referred to by a foreign key cannot be dropped.


• If the dropped column is a primary with single column, the primary key is also dropped.
• Unique constraints that have only the dropped column are also dropped.
• If the dropped column is part of a composite primary key (or a unique constraint), the
modified primary key (or unique constraint) will be the remaining columns a>er removing
the dropped column. The data present in the table should be consistent with the modified
primary key (or unique constraint) else the drop will fail.

An op)onal COLUMN keyword can be added (for readability) – DROP COLUMN instead of DROP.

Modify a column

ALTER TABLE table_name MODIFY


column_name data_type [DEFAULT literal] [[NOT] NULL] [PRIMARY KEY | UNIQUE]

• The new defini)on replaces the current defini)on.


• If a DEFAULT value is added/removed/changed it takes effect only for future inserts – exis)ng
row values are not affected.
• If the data type of the column is changes, all exis)ng values should convert to the new data
type without data loss.
• If the new defini)on can make the column NOT NULL only if all exis)ng rows have non-null
value for the column.
• If the column is part of the primary key, it cannot be changed to a nullable column.
• A PRIMARY KEY clause can be specified only if the table does not already have a primary key.
• Not specifying the PRIMARY KEY clause has no effect on the current primary key (if any).
• Not specifying the UNIQUE constraint clause has no effect on the current unique constraints
(if any).

Adding Primary Key

ALTER TABLE table_name ADD PRIMARY KEY (column_name1,...)

Primary key can be added only if the table does not already have a primary key.
Adding Unique Constraint

ALTER TABLE table_name ADD UNIQUE (column_name1,...)

Adding Foreign Key

ALTER TABLE table_name ADD FOREIGN KEY (column_name1,...)


REFERENCES ref_table_name (ref _column_name1,...)

Dropping Primary Key

ALTER TABLE table_name DROP PRIMARY KEY

Primary key cannot be dropped if it is referred to by a foreign key.

INSERT Statement

Inser)ng by giving values for all columns in create order. Values should be provided for all columns in
the table.

INSERT INTO table_name VALUES (value1, value2,....);

Inser)ng by giving values some of the columns in the table. The remaining columns will take the
default values of the respec)ve columns. This syntax should be used when the order of the columns
is not known.

INSERT INTO table_name(column1, column2,....) VALUES (value1, value2,....);

INSERT statement will fail if the provided values result in a viola)on of any constraint.

SELECT Statement

Retrieve all rows and all columns

SELECT * FROM table_name;

Columns are returned in CREATE order.

Retrieve a subset of columns (Projection)

SELECT column1, column2,... FROM table_name;

When the list of columns specified is a subset of the columns in the table, the opera)on is called a
Projec5on.

WHERE clause (Selection)

SELECT * FROM table_name WHERE condi)on;


SELECT column1, column2,... FROM table_name WHERE condi)on;
The condi)on should be an expression. All rows sa)sfying the condi)on are returned. If the condi)on
evaluates to a non-zero value for a row, then the row is said to sa)sfy the condi)on.

An opera)on that selects a subset of rows is called a Selec5on.

Example.

Employee Table:
Name Salary
Tom 10000
Harry 16000
John NULL
MaQ 11000
Peter 10000
Mary NULL

SELECT Name FROM Employee WHERE Salary < 15000 will return Tom, MaE & Peter.
SELECT Name FROM Employee WHERE Salary > 15000 will return Harry.
SELECT Name FROM Employee WHERE Salary BETWEEN 11000 AND 15000 will return Harry & MaE.
SELECT Name FROM Employee WHERE Salary IS NULL will return John & Mary.

Column aliasing

SELECT Name AS Employee, Salary AS "Monthly Salary" FROM Employee


WHERE Salary IS NOT NULL

Here Employee and "Monthly Salary" are column aliases. A column alias is an alternate name given
to an item in the select list.

The above SELECT will return:

Employee Monthly Salary


Tom 10000
Harry 16000
MaQ 11000
Peter 16000

Column aliases can be referred to in:


• ORDER BY clause
• GROUP BY clause
• HAVING clause

But CANNOT be referred in:


• Select list
• FROM clause
• WHERE clause

The AS keyword is op)onal. The below query is same as the above one.

SELECT Name Employee, Salary "Monthly Salary" FROM Employee


Note: When a select column is given an alias, it is s)ll possible to use the column name directly. For
example, both the following SELECT statements are valid and have the same meaning.

SELECT Name EName, Salary "Monthly Salary" FROM Employee ORDER BY EName;
SELECT Name EName, Salary "Monthly Salary" FROM Employee ORDER BY Name;

DISTINCT clause

SELECT DISTINCT Salary FROM Employee

Will return

Salary
10000
16000
NULL
11000

DISTINCT includes NULL values in the result. Example:

Student table.
Name Mark1 Mark2
Tom 60 70
Harry 80 70
John NULL 80
MaQ NULL 80
Peter 70 NULL
Mary NULL NULL
Victor NULL NULL

SELECT DISTINCT Mark1, Mark2 FROM Student

Will return:

Mark1 Mark2
60 70
80 70
NULL 80
70 NULL
NULL NULL

ORDER BY clause

With the above Student table,

SELECT * FROM Student ORDER BY Mark1, Mark2

Will return:
Name Mark1 Mark2
Mary NULL NULL
Victor NULL NULL
John NULL 80
MaQ NULL 80
Tom 60 70
Peter 70 NULL
Harry 80 70

The ordering is in ascending order by default. DESC op)on should be used for descending order:

SELECT * FROM Student ORDER BY Mark1 DESC, Mark2

Will return:

Name Mark1 Mark2


Harry 80 70
Peter 70 NULL
Tom 60 70
Mary NULL NULL
Victor NULL NULL
John NULL 80
MaQ NULL 80

Note:
• NULL values come first in ascending order and last in descending order.
• When DISTINCT is used along with ORDER BY, all columns used in ORDER BY should be in the
select list. This rule prevents unpredictable ordering of the results.

SELECT for expressions without referring to tables

SELECT <exp11>, <expr2>, … FROM DUAL

DUAL is a keyword refers to a dummy table name. The FROM DUAL at the end is op)onal.

Examples:

SELECT NOW();

SELECT 100 + 5;

SELECT 100 + 5 AS Sum;

SELECT 100 + 5 FROM DUAL;

Note that syntac)cally all SELECT statement clauses like WHERE, GROUP BY etc., can be used in this
kind of SELECT as well. However, those clauses are meaningless in this context.

SELECT ALL
ALL a>er the SELECT keyword is to indicate that all records are returned (instead of DISTINCT). This is
the behaviour when neither ALL not DISTINCT is men)oned. ALL keyword is just for readability – it
does not change the seman)cs of the SELECT statement.

Example:

SELECT ALL RollNum FROM Result

Is same as

SELECT RollNum FROM Result

UPDATE Statement

UPDATE table_name
SET column1 = expr1,
column2 = expr2, …
WHERE condi)on;

Example:

UPDATE Student SET Mark1 = 80, Mark2 = 80 WHERE Name = 'Peter';

Cau)on: If the WHERE clause is missed, the updates will occur for all records in the table.

DELETE Statement

DELETE FROM table_name WHERE condi)on;

Example:

DELETE FROM Student WHERE Mark1 IS NULL AND Mark2 IS NULL;

Cau)on: Similar to UPDATE, if the WHERE clause is missed, all records in the table will get deleted.

Functions
Function Types
• Scalar Func5ons or Single Row Func5ons – These func)ons take scalar values as argument
and returns a scalar value. Examples:
o Numeric (Math) func)ons
o String func)ons
o Date & Time func)ons

• Aggregate Func5ons or Mul5ple Row Func5ons or Group Func5ons - These func)ons work
on a set of records as a whole and return a single value.
Scalar Functions
Numeric (Math) functions

• ABS(n)

• POWER(x,y) / POW(x,y)

• ROUND(n) / ROUND(n,d)

• FLOOR(n)

• CEIL(n)

• TRUNCATE(n,d)

Examples:
Func5on Call Result
ABS(-5.7) 5.7
POWER(3,2) 9
POWER(0.09,0.5) 0.3
POWER(-1,0.5) Error
POWER(-1,0.2) Error
POWER(-25,-2) 0.0016
POWER(0,0) 1
ROUND(24.5) 25
ROUND(-24.5) -25
ROUND(24.2345, 3) 24.235
ROUND(-24.2345, 3) -24.235
ROUND(145.5, -1) 150
TRUNCATE(24.23458, 4) 24.2345
TRUNCATE(-24.23458, 4) -24.2345
TRUNCATE(27.5, 0) 27
TRUNCATE(-27.5, 0) -27
TRUNCATE(64.23458, -1) 60
TRUNCATE(64.23458, -2) 0

Note:
• Raising nega)ve number to a frac)onal power causes error
• If any argument is null for a func)on, the result is NULL.
Current Date & Time function

NOW() – Current date & )me – the )me at which the current statement started execu)ng.

NOW(n) – Current date & )me including frac)onal seconds up to n digits. 0 <= n <= 6. Default is zero.

Func5on Call Result


NOW() Similar to:
2023-08-07 15:58:41
NOW(5) Similar to:
2023-08-07 5:58:41.70459

Note: Argument cannot be NULL for NOW().

IFNULL function

IFNULL(v1, v2)

Func5on Call Result


IFNULL(NULL, 100) 100
IFNULL(200, 100) 200
IFNULL(200, NULL) 200
IFNULL(NULL, NULL) NULL

Aggregate functions

Func5on Descrip5on NULL Handling


MAX(column) Finds the maximum value in the
column.
MIN(column) Finds the maximum value in the
column.
SUM(column) Finds the average of the values in
the column.
AVG(column) Finds the sum of the values in the NULLs ignored. Result is NULL if
column. the row count is zero a>er
SUM(DISTINCT column) Finds the sum of the values excluding NULLs.
excluding duplicates and NULLs.

AVG(DISTINCT column) Finds the average of the values


excluding duplicates and NULLs.

COUNT(*) Counts the number of records NULLs not ignored. Result is


including duplicate records. never NULL.
COUNT(column) Counts the number of values
including duplicates and excluding NULLs ignored. Result is never
NULLs. NULL.
COUNT(DISTINCT column) Counts the number of values
excluding duplicates and NULLs.

Examples:
Student table:
Name Subject Marks
Tom Math 76
Tony Math 66
Matt Math 87
Peter Math 56
Tom Physics 46
Tony Physics 71
Matt Physics 70
Peter Physics 71
Tom Chemistry 66
Tony Chemistry 51
Matt Chemistry 56
Mary Chemistry NULL

Query Result
SELECT COUNT(*) FROM Student 12
SELECT COUNT(Marks) FROM Student 11
SELECT COUNT(DISTINCT Marks) FROM Student 8
SELECT MAX(Marks) FROM Student 87
SELECT MIN(Marks) FROM Student 46
SELECT SUM(DISTINCT Marks) FROM Student 523
SELECT SUM(Marks) FROM Student 716
SELECT AVG(Marks) FROM Student 65.0909
SELECT AVG(DISTINCT Marks) FROM Student 65.3750
SELECT COUNT(*) FROM Student WHERE Marks >= 70 5
SELECT COUNT(Marks) FROM Student WHERE Marks >= 70 5

Note:

• DISTINCT op)on is available for MAX() and MIN() but it has no impact on the result.

• ALL op)on can be specified like SUM(ALL Marks). Here, ALL indicates that all values are
included (opposite of DISTINCT). This is the default behaviour if neither ALL nor DISTINCT is
men)oned. ALL is just for readability purpose - it does not change the meaning of the
aggregate func)on call. Examples MAX(ALL Marks), COUNT(ALL *), etc.

• COUNT(DISTINCT col_name) can also be wriQen as COUNT(DISTINCT(col_name)). Same


thing can be done for other aggregate func)ons.

• COUNT(ALL col_name) can also be wriQen as COUNT(ALL(col_name)). Same thing can be


done for other aggregate func)ons. This alternate syntax cannot be used when column name
is not specified – COUNT(ALL(*)) is not allowed.

• Arguments of aggregate func)ons can be expressions involving mul)ple columns. Example:


Student table:
StudentName InternalMarks ExternalMarks
Tom 23 75
Tony 22 66
Matt 24 73
Peter 23 55

Top mark considering internal and external marks together:


SELECT MAX(InternalMarks + ExternalMarks) TopMark FROM Student;

Result:
TopMark
98

GROUP BY clause

Aggregate func)ons by default perform the aggrega)on taking all records got a>er applying the
WHERE clause condi)on. The result is always a single row that has the results of the aggrega)on.

GROUP BY clause is used when it is required to split the records in the table into mul)ple groups and
apply the aggrega)on on each group of records separately. For example, let’s say, with the above
Student table, the requirement is to find the subject-wise averages instead of the overall average.
First the records need to be split into different groups based on the subject (as shown below) and
then the averages need to be calculated for each group (i.e., each subject).

Subject: Math Subject: Physics Subject: Chemistry


Name Marks Name Marks Name Marks
Tom 76 Tom 46 Tom 66
Tony 66 Tony 71 Tony 51
Matt 87 Matt 70 Matt 56
Peter 56 Peter 71 Mary NULL
In SQL, this is done using the GROUP BY clause as below.

SELECT Subject, AVG(Marks) AS Average FROM Student GROUP BY Subject

The result will be:

Subject Average
Math 71.2500
Physics 64.5000
Chemistry 57.6667

Similarly,

SELECT Name, AVG(Marks) AS Average FROM Student GROUP BY Name

Will give the average for each student. The result will be:

Name Average
Tom 62.6667
Tony 62.6667
Matt 71.0000
Peter 63.5000
Mary NULL

Records with NULL in the GROUP BY column are put in a group of its own. For example, let’s say the
Student table has the following two addi)onal rows.

Name Subject Marks


Mary NULL 45
Mary NULL 46

Now, the subject-wise average will give:

Subject Average
Math 71.2500
Physics 64.5000
Chemistry 57.6667
NULL 45.5000

GROUP BY mul5ple columns example

Sales table:
State City SalesDate SalesAmount
Karnataka Bangalore 2023-08-07 10000
Karnataka Mysore 2023-08-07 7000
Karnataka Mangalore 2023-08-07 6000
Tamil Nadu Chennai 2023-08-07 12000
Tamil Nadu Coimbatore 2023-08-07 11000
Tamil Nadu Trichy 2023-08-07 9000
Karnataka Bangalore 2023-08-08 11000
Karnataka Mysore 2023-08-08 8000
Karnataka Mangalore 2023-08-08 5000
Tamil Nadu Chennai 2023-08-08 13000
Tamil Nadu Coimbatore 2023-08-08 19000
Tamil Nadu Trichy 2023-08-08 8000
Tamil Nadu NULL 2023-08-07 6500
Tamil Nadu NULL 2023-08-08 5000
NULL NULL 2023-08-07 7500
NULL NULL 2023-08-08 6000

State-wise, city-wise sales:


SELECT State, City, SUM(SalesAmount) TotalSales FROM Sales GROUP BY State, City
State City TotalSales
Karnataka Bangalore 21000
Karnataka Mysore 15000
Karnataka Mangalore 11000
Tamil Nadu Chennai 25000
Tamil Nadu Coimbatore 30000
Tamil Nadu Trichy 17000
Tamil Nadu NULL 11500
NULL NULL 13500

State-wise, date-wise sales:


SELECT State, SalesDate, SUM(SalesAmount) TotalSales FROM Sales GROUP BY State, SalesDate
State SalesDate TotalSales
Karnataka 2023-08-07 23000
Tamil Nadu 2023-08-07 38500
Karnataka 2023-08-08 24000
Tamil Nadu 2023-08-08 45000
NULL 2023-08-07 7500
NULL 2023-08-08 6000

HAVING clause

A>er the records are split into groups (by GROUP BY) further condi)ons can be defined at the group
level. This is done using the HAVING clause. Example:

Student table:
Name Subject Marks
Tom Math 76
Tony Math 66
Matt Math 87
Peter Math 56
Tom Physics 46
Tony Physics 71
Matt Physics 70
Peter Physics 71
Tom Chemistry 66
Tony Chemistry 51
Matt Chemistry 56
Mary Math 70
Mary Physics NULL
Mary Chemistry NULL

Here we have marks for three subjects. But all three marks are available only for some students
(Tom, Tony and MaQ). The requirement is to calculate the total marks for all students for whom all
three marks are available. It can be done as below.

SELECT Name, SUM(Marks) Total FROM Student GROUP BY Name HAVING COUNT(Marks) = 3

The result will be:


Name Total
Tom 188
Tony 188
Matt 213

If the HAVING clause is not included, the result will include incorrect par)al totals as shown below.

Name Total
Mary 70
Tom 188
Peter 127
Tony 188
Matt 213

Group Expressions

A Group-Expression is expression that can be evaluated at the group level. It can contain:
1. Columns whose values are same for all rows in the group as per group defini)on (i.e.,
columns included in GROUP BY clause)
2. Column whose value is restricted to a single value by WHERE clause.
3. Aggregate func)ons.

Examples:

Let’s say the Student table contains columns Name, Subject, InternalMarks & ExternalMarks and
let’s say a SELECT statement is of the form:

SELECT …… FROM Student WHERE …… GROUP BY Name HAVING …. ORDER BY ….

The following are valid group-expressions in the context of the above SELECT statement:
SUM(InternalMarks)
AVG(InternalMarks)
MAX(InternalMarks) – MIN(InternalMarks)
MAX(InternalMarks) + ExternalMarks)
Name

The following are non-group-expressions in the context of the above SELECT statement:
InternalMarks + ExternalMarks
InternalMarks - AVG(InternalMarks)
Subject
CONCAT(Name, '-', Subject)

When a SELECT statement has aggregate func)ons or a GROUP BY clause: The select list, HAVING
clause and ORDER BY clause can contain only group-expressions. Examples:

SELECT Statement Valid? Remarks


SELECT Name, Subject, SUM(Marks) NO Subject is in select list but not in GROUP BY
FROM Student
GROUP BY Name
SELECT Name, Subject, SUM(Marks) YES
FROM Student
GROUP BY Subject, Name
SELECT Name, Subject, SUM(Marks) YES Though Subject is not in GROUP BY, it is
FROM Student restricted to a single value by WHERE
WHERE Subject = 'Math' clause
GROUP BY Name
SELECT Name, SUM(Marks) NO Subject is in HAVING clause but not in
FROM Student GROUP BY
GROUP BY Name
HAVING Subject = 'Math'
SELECT Name, SUM(Marks) YES
FROM Student
WHERE Subject = 'Math'
GROUP BY Name
SELECT Name, SUM(Marks) YES Subject is in HAVING clause but only with
FROM Student aggrega)on.
GROUP BY Name
HAVING COUNT(Subject) = 3
SELECT AVG(Marks) YES Marks is in HAVING clause but only with
FROM Student aggrega)on.
HAVING COUNT(Marks) >= 10
SELECT Name, SUM(Marks) NO Subject is in ORDER BY clause but not in
FROM Student GROUP BY
GROUP BY Name
ORDER BY Subject
SELECT Name, SUM(Marks) YES Subject is in ORDER BY clause but only with
FROM Student aggrega)on.
GROUP BY Name
ORDER BY COUNT(Subject)
SELECT AVG(Marks) NO Subject is in ORDER BY clause but not in
FROM Student GROUP BY.
ORDER BY Subject The ORDER BY here is actually pointless as
this SELECT statement will always return
only a single row.

Aggregate func)ons can be used only in the select lists, HAVING clauses and ORDER BY clauses. It
cannot be used in WHERE clauses. This is because WHERE clause is processed before grouping is
done by GROUP BY. For the same reason columns referred to by WHERE clause is not restricted by
the GROUP BY clause.

Logical flow of SELECT statement processing

Below is a simplified syntax of a SELECT statement for a single table.

SELECT <select list> FROM <table-name>


WHERE <condi)on>
GROUP BY <column-list>
HAVING <group-expr-condi)on>
ORDER BY <expr-list>

WHERE, GROUP BY, HAVING and ORDER BY clauses are op)onal but need to be in the above order
when specified.

The SELECT statement is logically executed using the below steps.

1. All rows from the table are fetched.


2. The WHERE clause condi)on is applied to the rows and only the rows sa)sfying the condi)on
are taken for further processing.
3. The rows are split into mul)ple groups based on the GROUP BY clause.
4. The HAVING condi)on is applied to each of the groups and only the groups sa)sfying the
condi)on are taken for further processing.
5. The select list is computed. If there is no grouping, the select list is computed once for each
row. In case of groups, the select list is computed once for each group.
6. The select result is ordered as per the ORDER BY clause.

The above steps are to logically understand what the SELECT statement means. SQL is a
non-procedural language that specifies only what needs to be done and not how it needs to be done.
So, the RDBMs will choose the most efficient way to execute SELECT statement and produce the
result that matches the meaning of the SELECT statement.

Joins

Cartesian Product (X)

Cartesian product on two tables results in a table having all combina)ons of rows from the
underlying tables. Cartesian product will include all the columns from both the tables. The degree of
the cartesian product will be the sum of the degrees of the two tables and the cardinality will be the
product of the cardinali)es of the two tables.

Also called unrestricted join or cross join.

Example: The following tables give a sports team’s opponent-wise and ground-wise past performance.

PerfByOpponent table
Opponent WinPercent
Australia 40
West Indies 53
New Zealand 53
England 56

PerfGround table
Ground GroundWinPercent
Bengaluru 71
Chennai 54
Delhi 64
Mumbai 55
The requirement is to find the win probability for each Opponent-Ground carbonata)on. This can be
done using cartesian product with any of the following two SELECT commands.

SELECT Opponent, Ground, (WinPercent + GroundWinPercent) / 2 AS WinProbability


FROM PerfByOpponent, PerfGround

SELECT Opponent, Ground, (WinPercent + GroundWinPercent) / 2 AS WinProbability


FROM PerfByOpponent JOIN PerfGround

SELECT Opponent, Ground, (WinPercent + GroundWinPercent) / 2 AS WinProbability


FROM PerfByOpponent CROSS JOIN PerfGround

The result will be:


Opponent Ground WinProbability
England Bengaluru 63.5000
New Zealand Bengaluru 62.0000
West Indies Bengaluru 62.0000
Australia Bengaluru 55.5000
England Chennai 55.0000
New Zealand Chennai 53.5000
West Indies Chennai 53.5000
Australia Chennai 47.0000
England Delhi 60.0000
New Zealand Delhi 58.5000
West Indies Delhi 58.5000
Australia Delhi 52.0000
England Mumbai 55.5000
New Zealand Mumbai 54.0000
West Indies Mumbai 54.0000
Australia Mumbai 47.5000

Note that the result may be returned in any random sequence.

Equi-Join

Equi-join operation
A join opera)on combines rows from two tables on specified condi)ons. If the condi)on based on
which the rows in one table are joined to rows in another table is equal-to, then the join is called
Equi-join.

Product table:
ProductId Name
1 Shirt
2 Pant
3 Tie
ProductPrice table:
ProductId ProductSize Price
1 S 500
1 M 550
1 L 600
2 S 600
2 M 650
2 L 700
3 M 100
3 L 120

Here each product has different price based on size. The requirement to display prices of all the
products for all the available sizes. This needs an equi-join. It can be done in two ways.

Equi-join with JOIN & ON clauses

SELECT * FROM Product A JOIN ProductPrice B ON A.ProductId = B.ProductId


SELECT * FROM Product A CROSS JOIN ProductPrice B ON A.ProductId = B.ProductId

Equi-join with WHERE clause

SELECT * FROM Product, ProductPrice WHERE Product.ProductId = ProductPrice.ProductId


SELECT * FROM Product JOIN ProductPrice WHERE Product.ProductId = ProductPrice.ProductId
SELECT * FROM Product CROSS JOIN ProductPrice WHERE Product.ProductId = ProductPrice.ProductId

Note that wherever the ProductId column is referred it is qualified by the table name. This is done
because both the tables involved in the join have a column named ProductId. Leaving out the
qualifica)on will cause an error.

The result of all the above join queries will be:

ProductId Name ProductId ProductSize Price


1 Shirt 1 S 500
1 Shirt 1 M 550
1 Shirt 1 L 600
2 Pant 2 S 600
2 Pant 2 M 650
2 Pant 2 L 700
3 Tie 3 M 100
3 Tie 3 L 120

Table Aliases
Similar to column aliases, tables can also be given aliases. This will be useful when there are mul)ple
tables involved and column names referred to exist in two or more tables. For example:

SELECT * FROM Product A, ProductPrice B WHERE A.ProductId = B.ProductId


The above statement is same as the earlier one. When an alias is defined for a table, the table name
can no longer be used to qualify the column within the SELECT statement. For example: the below
statement will cause an error.

SELECT * FROM Product A, ProductPrice B WHERE Product.ProductId = B.ProductId

However, the below SQL is valid because Product.ProductId refers to the un-aliased Product table.

SELECT * FROM Product A, Product WHERE A.ProductId = Product.ProductId

Qualifica)on is not needed for columns that do not have ambiguity. Example:

SELECT A.ProductId, Name, ProductSize, Price FROM Product A, ProductPrice B


WHERE A.ProductId = B.ProductId

Here Name, ProductSize and Price do not need qualifica)on.

Note: If a table is joined to itself, tables alias is a must as the joined tables have duplicate names.

Natural Join

NATURAL JOIN joins tables by matching columns with same name in the two tables. This is also an
equi-join where the equal-to condi)on is implied. Example:

SELECT * FROM Product NATURAL JOIN ProductPrice

Result:

ProductId Name ProductSize Price


1 Shirt S 500
1 Shirt M 550
1 Shirt L 600
2 Pant S 600
2 Pant M 650
2 Pant L 700
3 Tie M 100
3 Tie L 120

The result is same as earlier except that it has only one ProductId column. This is because with
NATURAL JOIN only one of the two columns matched is kept in the result.

NATURAL JOIN will match rows only if the joined tables have one or more columns with the same
name. If there is no common column name between the tables, NATURAL JOIN will give the
Cartesian product as the result.

NATURAL JOIN cannot have an ON clause.


Equi-join with additional filtering conditions
Addi)onal filtering condi)ons can be included. For the join to remain an equi-join, the addi)onal
condi)ons should not be join condi)ons (i.e., condi)ons that relate columns from two different
tables).

Examples: The following SELECT statements get the prices only for 'Shirt'.

SELECT * FROM Product A, ProductPrice B


WHERE A.ProductId = B.ProductId AND Name = 'Shirt';

SELECT * FROM Product A JOIN ProductPrice B


ON A.ProductId = B.ProductId
WHERE Name = 'Shirt';

SELECT * FROM Product NATURAL JOIN ProductPrice


WHERE Name = 'Shirt';

Equi-join based on multiple columns

It is possible to match rows based of mul)ple columns. Example:

Let’s say the is an OrderItem table with columns OrderId, ItemNum, ProductId, ProductSize and
Quan5ty.

Now, the following SELECT statements will join based on two columns (ProductId and ProductSize).

SELECT * FROM OrderItem Ord JOIN ProductPrice Pr


ON Ord.ProductId = Pr.ProductId AND Ord.ProductSize = Pr.ProductSize

The result will be of the form:

OrderId ItemNum ProductId ProductSize Quantity ProductId ProductSize Price

The same join can be done using NATURAL JOIN:

SELECT * FROM OrderItem NATURAL JOIN ProductPrice


The result will be of the form:

ProductId ProductSize OrderId ItemNum Quantity Price

Note:
• The matched columns come first in the order they appear in the le>-side table.
• Remaining columns in the le>-side table come next.
• Remaining columns in the right-side table come last.
If three tables need to be joined, two joins will be required. In general (N-1) joins are needed to join
N tables.
Non-equi-joins

Non-equi-joins are joins that have join condi)ons other than equal-to.

Example:

Sales table
StoreId SaleDate Amount
1 2013-09-01 10000
1 2013-09-02 14000
2 2013-09-01 11000
2 2013-09-02 13000
2 2013-09-03 13000

Inventory table
StoreId InventoryDate Value
1 2013-09-01 41000
1 2013-09-02 24000
1 2013-09-03 43000
2 2013-09-01 31000
2 2013-09-02 33000

The requirement is to list, for all stores, dates on which sales was less than 25% of the inventory. The
below SQL will get the required result.

SELECT S.StoreId, S.SaleDate


FROM Sales S, Inventory I
WHERE S.StoreId = I.StoreId AND
S.SaleDate = I.InventoryDate AND
S.Amount < I.Value * 0.25

In the above join, the join condi)on S.Amount < I.Value * 0.25 is not an equal-to condi)on.
So, this is a non-equi-join query.

The result of the non-equi-join query will be:

StoreId SaleDate
1 2013-09-01

SQL Extra Topics

More Integer Data Type

Data Type Name Data Type Synonyms Size Range


TINYINT Integer 1 byte Signed: -27 to 27-1
Unsigned: 0 to 28-1
SMALLINT Integer 2 bytes Signed: -215 to 215-1
Unsigned: 0 to 216-1
MEDIUMINT Integer 3 bytes Signed: -223 to 223-1
Unsigned: 0 to 224-1
Boolean Data Type

Data Type Name Data Type Synonyms Size Range


BOOLEAN Stored as TINYINT BOOL 1 byte -27 to 27-1

Note that it can store values


beyond just 0 and 1

Note Boolean literals TRUE and FALSE evaluate to 1 and 0.

Time and Date-Time Data Types

Data Type Name Data Type Size Range


TIME Time Interval 3 bytes + 0 <= n <= 6. Number of frac)onal
TIME(n) frac)onal seconds seconds digits. Default is zero.
Can also be
used to store Range: -838:59:59 to 838:59:59
)me.
DATETIME Date & Time 8 bytes + 0 <= n <= 6. Number of frac)onal
DATETIME(n) frac)onal seconds seconds digits. Default is zero.
Year 1000 to 9999 plus )me part.

TIMESTAMP Date & Time. 4 bytes + 0 <= n <= 6. Number of frac)onal


TIMESTAMP(n) Stored in UTC frac)onal seconds seconds digits. Default is zero.
Range: 01-01-1970(approx.) to
19-01-2038(approx.)

Note: Refer pages 534-536 for informa)on on more types.

Date & Time Literal Formats

Date and time as strings

When a date, time or a datetime&time is expected and a string is provided, it is converted as


below.

§ Date
o 'YYYY-MM-DD'
o 'YY-MM-DD'
o 'YYYYMMDD'
o 'YYMMDD'

§ Time (ffffff represents one or more frac)onal seconds digits. Value is rounded to 6 digits if
more than 6 digits are specified)

o 'hh:mm:ss'
o 'hh:mm:ss.ffffff'
o 'hhmmss'
o 'hhmmss.ffffff'

When colon is used to separate )me parts mm and ss can be one or two digits with value
less than 60. hh can be up to 3 digits and can also have a minus sign.

§ Date & Time (all the below formats can op)onally include frac)onal seconds as above)

o 'YYYY-MM-DD hh:mm:ss'
o 'YY-MM-DD hh:mm:ss'
o 'YYYYMMDDhhmmss'
o 'YYMMDDhhmmss'

Date and time as numbers

When a date, time or a datetime&time is expected and a number is provided, it is converted


as below.

• Date
o YYYYMMDD (8 digit number)
o YYMMDD (6 digit number)

• Time
o hhmmss (6 digit number)
o hhmmss.ffffff

• Date & Time


o YYYYMMDDhhmmss (14 digit number)
o YYMMDDhhmmss (12 digit number)
o YYYYMMDDhhmmss.ffffff
o YYMMDDhhmmss.ffffff

When year is specified with two digits (YY), year is taken as 2000 + YY if YY is less than 70.
Else it is taken as 1900 + YY.

MySQL Client Output Formats


MySQL client prints data in the following formats. Numeric values are right aligned and all others are
le> aligned.

Data Type Format Examples


All integer Normal format with no Value: 20000
types separators or decimal point Output: 20000

DECIMAL Number of decimals as per Column type: DECIMAL(10, 3)


value from column defini)on Value: 1.2
column Output: 1.200
DECIMAL As per the precision of the
value from expression value Expression Output
expression 1.2 + 1.25 2.45
2.1 / 3 0.70000

FLOAT value The value is rounded to 6


significant digits. Float Value Output
2.1 2.1
No zero padding on the right 0 0
side when decimal point is 12.34567 12.3457
present 1234567 1234570
2e3 2000
Regular format if exponent is 2e-3 0.002
between -15 to 14 (both 2e14 200000000000000
inclusive). Else exponent 2.123456e15 2.12346e15
format with lower case 'e'. 2e-15 0.000000000000002
2.123456e-16 2.12346e-16

DOUBLE Same as FLOAT but without any rounding. More significant digits (up to 17) will
get printed as DOUBLE is larger in size than FLOAT.

CHAR Printed without quotes.

Leading spaces – Not trimmed


Trailing spaces – Trimmed

VARCHAR Printed without quotes.

Leading spaces – Not trimmed


Trailing spaces – Not trimmed

Boolean value Printed as 0 or 1


Date and
Time types Type Output Format Example
DATE YYYY-MM-DD 2023-08-15
TIME hh:mm:ss 15:01:01
TIME(1) hh:mm:ss.f 15:01:01.3
TIME(2) hh:mm:ss.ff 15:01:01.30
DATETIME / YYYY-MM-DD hh:mm:ss 2023:08:15 15:01:01
TIMESTAMP
DATETIME(1) / YYYY-MM-DD hh:mm:ss.f 2023:08:15 15:01:01.3
TIMESTAMP(1)
DATETIME(2) / YYYY-MM-DD hh:mm:ss.ff 2023:08:15 15:01:01.30
TIMESTAMP(2)

Note: for TIME data type, minimum length of hh is 2. It can be longer


depending on the time interval value.
Implicit Data Type Conversions

Implicit Conversions

All implicit conversions between numeric, string, date, )me and boolean are allowed in MySQL. The
only conversions that can result in error are conversions to date and )me types.

String/numeric to date/)me/date-)me

String/numeric values are converted to date/)me/date-)me values as per the formats described in
Date & Time Literal Formats sec)on. Invalid string/numeric will cause error.

Conversion to string

Done as described in MySQL Client Output Formats sec)on with one excep)on:
• Float values are not rounded when conver)ng

Dates & Times to Numbers

DATE '2023-08-01' is converted to 20230801


TIME '15:20:33.234' is converted to 152033.234
TIME '155:20:33.234' is converted to 1552033.234
DATETIME/TIMESTAMP '2023-08-01 15:20:33.234' is converted to 20230801152033.234

Strings to Numbers

The longest possible valid numeric prefix of the string is used. Examples.

'1234.5' is converted to 1234.5


'1234.5wegweg' is converted to 1234.5
'1e4fhjwseflsdf' is converted to 1e4
'5,000' is converted to 5
'abc' is converted to 0

Boolean to Numbers

TRUE to 1 and FALSE to 0.

Conversions in Column Assignment

• When a value is assigned to a column either in an INSERT/UPDATE statement or in DEFAULT


clause, the provided value is converted implicitly to the data type of the column.

• For numeric columns, frac)onal values are rounded based on the number of decimals the
column can store.

• If the value provided is too big to fit into the column, an error occurs.
Conversions by Mathematical Operators

• Both operands are converted to number.

• When one of the operands is a FLOAT or DOUBLE, both operands are converted to DOUBLE.

• Else if one operand is a DECIMAL, the other is converted to DECIMAL and the data type of
the result will have size large enough to hold the result of the opera)on.

• Else, both operands are of integer type


o If one operand is BIGINT the other is converted to BIGINT
o Smaller integers operands are converted to INT
o If one operand is UNSIGNED, the other is also converted to UNSIGNED

Conversions by Relational Operators other than BETWEEN

• If the two operands are of compa)ble types, then the comparison happens without any type
conversion:

o If both operands are numeric, a numeric comparison is done (boolean is treated as


numeric)

o If both operands are string, a case insensi5ve string comparison is done

o If both operands are TIME, a )me comparison is done.

o If both operands are DATE/DATETIME/TIMESTAMP, a date-)me comparison is done.

o If one operand is TIME and the other is DATE/DATETIME/TIMESTAMP, a date-)me


comparison is done by adding today’s date to the TIME value.

• Else, if one of the operands is numeric or boolean, the other operand is converted to
numeric and a numeric comparison is done.

• Else, one operand is a string and the other is TIME. The string is converted to )me and a )me
comparison is done. Results are unpredictable (see note below) if the string is not a valid
)me.

• Else, one operand is a string and the other is DATE/DATETIME/TIMESTAMP. The string is
converted to date-)me and a date-)me comparison is done. Results are unpredictable (see
note below) if the string is not a valid date-)me.

Conversions by BETWEEN operator

• If all three operands are of compa)ble type (as earlier), the comparison occurs without any
type conversion.

• Else, if one of the operands are a mix of numeric, string and TIME, numeric and string
operands are converted to )me and a )me comparison is done. Results are unpredictable
(see note below) if a string or numeric operand is not a valid )me interval.
• Else, if the operands include at least one DATE/TIME/DATETIME/TIMESTAMP then numeric
and string operands are converted to date-)me and a date-)me comparison is done. For
TIME operands, today’s date is added to get date-)me value. Results are unpredictable (see
note below) if a string or numeric operand is not a valid date-)me.

• Else, the operands are a mix of numeric and strings. All operands are converted to numeric
and a numeric comparison is done.

Conversion of condition expressions

The condi)on expressions in WHERE clauses, HAVING clauses are converted to numeric and
interpreted as below:

• Non-zero value is TRUE


• Zero value is FALSE

Unpredictable behaviour

When conver)ng from invalid string/numeric to DATE/TIME/DATETIME/TIMESTAMP MySQL


behaviour is unpredictable.

In this situa)on any one of the following may happen in MySQL


1. Statement fails with errors
2. Statement succeeds with warnings
3. Statement succeeds without warnings

It is complicated to explain when each of the above will happen. For exam purpose, it is safe to say
that such conversions will result in an error.
More Scalar Functions
String functions

• UCASE(s) / UPPER(s)

• LCASE(s) / LOWER(s)

• LENGTH(s)

• LEFT(s,n)

• RIGHT(s,n)

• MID(s,p,n) / SUBSTRING(s,p,n) / SUBSTR(s,p,n) – Substring


MID(s,p) / SUBSTRING(s,p) / SUBSTR(s,p)

• LTRIM(s)

• RTRIM(s)

• TRIM(s)
• INSTR(s1, s2) – Find string in string.

• INSERT(s1,p,n,s2) – Replaces/inserts string in a string.

• CONCAT(s1,s2,...) – Concatenate strings

Examples:

Func5on Call Result


UCASE("McDonald's") "MCDONALD'S"
LCASE("McDonald's") "mcdonald's"
LENGTH("School") 6
LENGTH("") 0
LEFT("School", 3) "Sch"
LEFT("School", 1) "S"
LEFT("School", 0) ""
LEFT("School", 8) "School"
LEFT("School", -1) ""
RIGHT("School", 3) "ool"
MID("School", 3, 2) "ho"
MID("School", 3, 0) ""
MID("School", -4, 3) "hoo"
MID("School", 3, -1) ""
MID("School", -6, 3) "Sch"
MID("School", 7, 3) ""
MID("School", -7, 3) ""
MID("School", 3) "hool"
MID("School", -5) "chool"
MID("School", -7) ""
LTRIM(" School ") "School "
RTRIM(" School ") " School"
TRIM(" School ") "School"
INSTR("The Coca-Cola is cold", "Co") 5
INSTR("The Coca-Cola is cold", "co") 5
INSTR("The Coca-Cola is cold", "hot") 0
INSTR("The Coca-Cola is cold", "") 1
INSERT("School", 3, 2, "abc") "Scabcol"
INSERT("School", 4, 2, "") "Schl"
INSERT("School", 6, 1, "L") "SchooL"
INSERT("School", -3, 2, "abc") "School"
CONCAT("Abc", "XYZ", "123") "AbcXYZ123"

Note:
• MID() uses nega)ve indices for coun)ng from the last character in the string. -1 posi)on is
the last character, -2 to is the second last, and so on.
• MID() returns empty string if the posi)on is outside the string range. The posi)on should be
non-zero and within -(string length) to +(string length) to get a non-empty result.
• INSTR() is case insensi5ve.
• INSERT() does not perform any inser)on if posi)on is not posi)ve or higher than the string
length.
• CHAR() returns binary string if the encoding is not specified with USING. The binary string is
printed in hexadecimal form.
• If any argument is null for a func)on, the result is NULL.

Date & Time parts extraction functions

• DATE()
• YEAR()
• MONTH()
• DAY()
• TIME() – Returned value will be of TIME type
• MONTHNAME()
• DAYNAME()
Examples:

Func5on Call Result


DATE('2023-08-07 15:58:41.123456') 2023-08-07
YEAR('2023-08-07 15:58:41.123456') 2023
MONTH('2023-08-07 15:58:41.123456') 8
DAY('2023-08-07 15:58:41.123456') 7
TIME('2023-08-07 15:58:41.123456') 15:58:41.123456
HOUR('2023-08-07 15:58:41.123456') 15
MINUTE('2023-08-07 15:58:41.123456') 58
SECOND('2023-08-07 15:58:41.623456') 41
MICROSECOND('2023-08-07 15:58:41.123456') 123456
MICROSECOND('2023-08-07 15:58:41.12345') 123450
MONTHNAME('2023-08-07 15:58:41.123456') 'August'
WEEKDAY('2023-09-18 15:58:41.123456') 0
DAYNAME('2023-09-18 15:58:41.123456') 'Monday'

Note:
• If any argument is null for a func)on, the result is NULL.

NOW() vs SYSDATE()

• NOW() – Current date & )me – the )me at which the current statement started execu)ng.
Returned value will be of DATETIME type.

NOW(n) – Current date & )me including frac)onal seconds up to n digits. 0 <= n <= 6. Default
is zero.

• SYSDATE() & SYSDATE(n) – Similar to NOW() but returns the )me at which the SYSDATE() call
executed. NOW() return value does not change during the execu)on of the current
statement while SYSDATE() can change.

Examples:

Func5on Call Result


NOW() Similar to:
2023-08-07 15:58:41
NOW(5) Similar to:
2023-08-07 15:58:41.70459

Note:
• Argument cannot be NULL for NOW()/SYSDATE().

• The below statement shows the NOW() and SYSDATE() values before sleeping for 0.01
seconds and again a>er sleeping.

SELECT NOW(3), SYSDATE(3), SLEEP(0.01), NOW(3), SYSDATE(3);

The results of the above statement will show that both NOW() calls return the same value
but that is not the case with SYSDATE(). Sample output:
+-------------------------+-------------------------+-------------+-------------------------+-------------------------+
| NOW(3) | SYSDATE(3) | SLEEP(0.01) | NOW(3) | SYSDATE(3) |
+-------------------------+-------------------------+-------------+-------------------------+-------------------------+
| 2023-08-07 16:05:15.667 | 2023-08-07 16:05:15.667 | 0 | 2023-08-07 16:05:15.667 | 2023-08-07 16:05:15.681 |
+-------------------------+-------------------------+-------------+-------------------------+-------------------------+

CREATE TABLE Statement (More Features)

Tables with Composite Keys

CREATE TABLE Course (


Id INT PRIMARY KEY,
Name VARCHAR(40) NOT NULL
);

CREATE TABLE Faculty (


Id INT PRIMARY KEY,
Name VARCHAR(25) NOT NULL
);

CREATE TABLE CourseFaculty (


CourseId INT,
FacultyId INT,
PRIMARY KEY (CourseId, FacultyId), -- composite primary key
FOREIGN KEY (CourseId) REFERENCES Course(Id),
FOREIGN KEY (FacultyId) REFERENCES Faculty(Id)
);

CREATE TABLE Sessions (


Id INT PRIMARY KEY,
CourseId INT NOT NULL,
FacultyId INT,
SessionDate DATE NOT NULL,
RoomNumber INT,
UNIQUE (SessionDate, RoomNumber), -- composite unique constraint
FOREIGN KEY (CourseId, FacultyId)
REFERENCES CourseFaculty(CourseId, FacultyId) -- composite foreign key
);

Note: The blow INSERT will succeed even if course with Id 100 does not exist.

INSERT INTO Sessions (Id, CourseId, SessionDate) VALUES(1, 100, '2024-01-17');

This can be prevented by adding the below foreign key to the Sessions table.

FOREIGN KEY (CourseId) REFERENCES Course(Id)

CHECK Constraint

CREATE TABLE Student (


Id INT PRIMARY KEY,
Name VARCHAR(25) NOT NULL,
Sex CHAR(1) NOT NULL CHECK (Sex IN ('M', 'F'))
);

The above statement is same as:

CREATE TABLE Student (


Id INT PRIMARY KEY,
Name VARCHAR(25) NOT NULL,
Sex CHAR(1) NOT NULL,
CHECK (Sex IN ('M', 'F'))
);

CHECK table constraint example:

CREATE TABLE Student (


Id INT PRIMARY KEY,
Name VARCHAR(25) NOT NULL,
InternalMarks INT,
ExtrnalMarks INT,
CHECK (InternalMarks + ExtrnalMarks <= 100)
);

Expressions as DEFAULT value

CREATE TABLE IdCard (


Id INT PRIMARY KEY,
Name VARCHAR(25) NOT NULL,
IssuedDate DATE DEFAULT (CURRENT_DATE)
);

DEFAULT value can be an expression but needs to be enclosed in parenthesis. The default value
expression can refer to other columns in the table but there should be no circular reference.

Self-Referencing Foreign Keys


In a foreign key, the referencing and the referenced tables can be the same table.

Example:

CREATE TABLE Employee (


EmpId INT PRIMARY KEY,
Name VARCHAR(10),
ManagerId INT,
FOREIGN KEY (ManagerId) REFERENCES Employee(EmpId)
);

Update of columns referenced by FOREIGN KEY

The default behaviour is to prevent update of the referenced column in the referenced (or
parent/primary) table.

Example:

CREATE TABLE Student(


RollNum INT PRIMARY KEY,
Name VARCHAR(10)
);

CREATE TABLE Result(


RollNum INT,
Marks INT,
FOREIGN KEY (RollNum) REFERENCES Student(RollNum)
);

Student table data:


RollNum Name
101 Adam
102 Tom
103 Mary

Result table data:


RollNum Marks
101 98
102 96

With the above tables and data, the following UPDATE fail because the RollNum 101 is referenced by
a Result table row.
UPDATE Student SET RollNum = 104 WHERE RollNum = 101

This default behaviour of UPDATE can be changed by using an ON UPDATE clause as below when
defining the FOREIGN KEY in the Result table.

FOREIGN KEY (RollNum) REFERENCES Student(RollNum) ON UPDATE CASCADE

The earlier UPDATE statement will succeed when ON UDATE CASCADE clause is added to the
FOREIGN KEY defini)on. The resul)ng data will be as below.
Student table data:
RollNum Name
104 Adam
102 Tom
103 Mary

Result table data:


RollNum Marks
104 98
102 96

No)ce that the update occurs in the parent table and one or more records in the child table.

There are more ways to handle updates. Below are the different ON UPDATE op)ons possible.

• CASCADE – All child rows are updated with the new parent column value

• NO ACTION – The default behaviour

• RESTRICT – Same as NO ACTION

• SET DEFAULT – Available in standard SQL but ignored by MySQL. This op)on sets the values
in child rows to the default value of the column.

• SET NULL – Sets the values in child rows to NULL. In the above example, Result table will be
as below a>er the update.

Result table data:


RollNum Marks
NULL 98
102 96

Note that in MySQL only CASCADE and SET NULL will affect the UPDATE behaviours, other op)ons
will have no effect.

Delete of rows referenced by FOREIGN KEY

Simila to the ON UPDATE clause to control UPDATE opera)ons the ON DELETE clause can be used to
control DELETE opera)ons.

Example:

FOREIGN KEY (RollNum) REFERENCES Student(RollNum)


ON UPDATE CASCADE
ON DELETE SET NULL

With above foreign key,


- updates in parent table (Student) cascade to child table (Result)
- deletes in parent cause child table columns to be set to NULL
Note that ON DELETE CASCADE will cause child table records to be deleted when a parent record is
deleted.

ON DELETE and ON UPDATE clauses are independent of each other – each one can specify a different
behaviour.

CREATE TABLE from a SELECT

The result returned by SELECT can be used to create a new table using.

CREATE TABLE table_name AS SELECT <rest of the select statement>

The AS keyword is op)onal.

Example:

CREATE TABLE ResultCopy AS SELECT * FROM Result

This creates ResultCopy table with the same column defini)ons as in Result table and copies all the
rows from Result to ResultCopy.

A Column in the new table has NOT NULL constraints set if the column directly refers to a NOT NULL
column or is an expression involving only NOT columns.

A Column in the new table has DEFAULT value set if it directly refers to a column with a DEFAULT
value.

PRIMARY KEY, UNIQUE, FOREIGN KEY and CHECK constraints are not set in the new table.

Assigning names to constraints

MySQL assigns internally generated names to UNIQUE, FOREIGN KEY and CHECK constraints. Note
that no name is internally assigned form PRIMARY KEY constraint. It is possible to explicitly give
names to constraints. Names can be given to UNIQUE, FOREIGN KEY, CHECK and PRIMARY KEY
constraints by using the CONSTRAINT clause.

Example:

CREATE TABLE Result (


RollNum INT PRIMARY KEY,
Marks INT,
CONSTRAINT Chk_Mark CHECK(Marks BETWEEN 0 AND 100)
);

Here the CHECK constraint is given the name Chk_Mark. The name can be used to refer to the
constraint when required – for example in an ALTER TABLE statement. Both the following statements
have the same effect.

ALTER TABLE Result DROP CHECK Chk_Mark;


ALTER TABLE Result DROP CONSTRAINT Chk_Mark;
UNIQUE, FOREIGN KEY and PRIMARY KEY constraints defined along with the column defini)on
cannot be given a name. The following statement will cause error.

CREATE TABLE Student (


RollNum INT PRIMARY KEY,
Name VARCHAR(20),
Mobile NUMERIC(10) CONSTRAINT Unq_Mobile UNIQUE
);

The following statement will give the desired result.

CREATE TABLE Student (


RollNum INT PRIMARY KEY,
Name VARCHAR(20),
Mobile NUMERIC(10),
CONSTRAINT Unq_Mobile UNIQUE(Mobile)
);

However, CHECK constraints defined along with the column defini)on can be given names. The
following statement is valid.

CREATE TABLE Result (


RollNum INT PRIMARY KEY,
Marks INT CONSTRAINT Chk_Mark CHECK(Marks BETWEEN 0 AND 100)
);

Views

A view is a virtual table that does not hold data but derives its data from other tables through a
SELECT query.

CREATE VIEW SubjectAverage AS


SELECT Subject, AVG(Marks) AS Average FROM Student GROUP BY Subject

A>er the SubjectAverage is created, it can be used just like a table, For example:
SELECT * FROM SubjectAverage

ALTER TABLE Statement (More Features)

Renaming a column

This works the same way as MODIFY with the addi)on of changing the column name.

ALTER TABLE table_name CHANGE


old_column_name new_column_name data_type [DEFAULT literal] [[NOT] NULL]
[PRIMARY KEY | UNIQUE]

Specifying the position of the column


ADD/MODIFY/CHANGE for columns can op)onally specify the posi)on of the column. By default, a
newly added column is placed at the last and exis)ng columns do not change posi)on. The FIRST or
AFTER clauses can be used to specify any posi)on for the column within the table.

Adding a column as the first column:

ALTER TABLE table_name ADD …………….. FIRST

Moving exis)ng column to first posi)on:

ALTER TABLE table_name MODIFY …………….. FIRST


Moving exis)ng column to first posi)on along with renaming:

ALTER TABLE table_name CHANGE …………….. FIRST

Adding a column a>er an exis)ng column named Marks:

ALTER TABLE table_name ADD …………….. AFTER Marks

AFTER can be used in the same way with MODIFY and CHANGE.

Note that column posi)on cannot be specified when adding mul)ple columns using a single ALTER
statement.

Assigning names to constraints

MySQL assigns internally generated names to UNIQUE, FOREIGN KEY and CHECK constraints. Note
that no name is internally assigned form PRIMARY KEY constraint. It is possible to explicitly give
names to constraints. Names can be given to UNIQUE, FOREIGN KEY, CHECK and PRIMARY KEY
constraints by using the CONSTRAINT clause.

Example:

CREATE TABLE Result (


RollNum INT PRIMARY KEY,
Marks INT,
CONSTRAINT Chk_Mark CHECK(Marks BETWEEN 0 AND 100)
);

Here the CHECK constraint is given the name Chk_Mark. The name can be used to refer to the
constraint when required – for example in an ALTER TABLE statement. Both the following statements
have the same effect.

ALTER TABLE Result DROP CHECK Chk_Mark;


ALTER TABLE Result DROP CONSTRAINT Chk_Mark;

UNIQUE, FOREIGN KEY and PRIMARY KEY constraints defined along with the column defini)on
cannot be given a name. The following statement will cause error.

CREATE TABLE Student (


RollNum INT PRIMARY KEY,
Name VARCHAR(20),
Mobile NUMERIC(10) CONSTRAINT Unq_Mobile UNIQUE
);

The following statement will give the desired result.

CREATE TABLE Student (


RollNum INT PRIMARY KEY,
Name VARCHAR(20),
Mobile NUMERIC(10),
CONSTRAINT Unq_Mobile UNIQUE(Mobile)
);

However, CHECK constraints defined along with the column defini)on can be given names. The
following statement is valid.

CREATE TABLE Result (


RollNum INT PRIMARY KEY,
Marks INT CONSTRAINT Chk_Mark CHECK(Marks BETWEEN 0 AND 100)
);

INSERT Statement (More Features)

Inserting multiple rows

Mul)ple rows can be inserted with a single INSERT statement by providing mul)ple value sets.
Example:

INSERT INTO Empl


VALUES
(8369, 'SMITH', 'CLERK', '1990-12-18', 800.00, NULL),
(8499, 'ANYA', 'SALESMAN', '1991-02-20', 2600.00, 300.00),
(8521, 'SETH', 'SALESMAN', '1991-02-22', 1250.00, 500.00),
(8882, 'SHIVANSH', 'MANAGER', '1991-05-01', 2450.00, NULL);

INSERT form a SELECT

INSERT INTO ResultCopy SELECT * FROM Result;

• The column counts of the inserted table should match the select result.
• The column name of the inserted table should match the column names in the select result.

Fewer column values can be inserted:

INSERT INTO ResultCopy(RollNum) SELECT RollNum FROM Result WHERE Marks > 90;

A>er checking that the column count and names match, MySQL maps columns by posi)on not name.
For example:

Result table:
RollNum Marks
1 95
2 85

CREATE TABLE ResultCopy SELECT * FROM Result;


INSERT INTO ResultCopy SELECT Marks, RollNum FROM Result;

A>er the above commands:

ResultCopy table:
RollNum Marks
1 95
2 85
95 1
85 2

Set Operations

Union (∪) – Combines the tuples of two selected rela)ons into a single rela)on.

Intersec5on (∩) – Gets the tuples that are present in both the selected rela)ons.

Minus (–) – Also called set difference. Gets the tuples that are present in the first rela)on but not in
the second rela)on.

Duplicates are eliminated in all the set opera)ons. The degrees of the two rela)ons should match for
the set opera)ons to work.
Example:

Faculty table:
Name Mobile
Oswald 9287862627
Derek 9730786996
Grace 9409368878
Henry 9487205331
Oswald 9287862627
Kevin 9458616553
Kevin 9458616553
Tom 9458616556

Student table:
Name Mobile
Steven 9060282540
Thomas 9005103559
Adam 9219569682
Kevin 9458616553
Helen 9828874297
Thomas 9005103559
Tom 9458616556

Union:
SELECT * FROM Faculty
UNION
SELECT * FROM Student;

Name Mobile
Oswald 9287862627
Derek 9730786996
Grace 9409368878
Henry 9487205331
Kevin 9458616553
Tom 9458616556
Steven 9060282540
Thomas 9005103559
Adam 9219569682
Helen 9828874297

Intersec)on:
SELECT * FROM Faculty
INTERSECT
SELECT * FROM Student;

Name Mobile
Kevin 9458616553
Tom 9458616556

Minus:
SELECT * FROM Faculty
EXCEPT
SELECT * FROM Student;

Name Mobile
Oswald 9287862627
Derek 9730786996
Grace 9409368878
Henry 9487205331

Outer joins
The results of the joins discussed so far will not include rows that do not have a matching row
sa)sfying the join condi)on.

For example, let us take the Sales and Inventory tables from the earlier example and run the
following query, which calculates the percentage of inventory sold.
SELECT
IFNULL(S.StoreId, I.StoreId) AS StoreId,
IFNULL(S.SaleDate, I.InventoryDate) AS Date,
S.Amount As Sales,
I.Value As Inventory,
Amount * 100 / Value AS SalePercent
FROM Sales S JOIN Inventory I
ON S.StoreId = I.StoreId AND
S.SaleDate = I.InventoryDate

The result will be:

StoreId Date Sales Inventory SalePercent


1 2013-09-01 10000 41000 24.3902
1 2013-09-02 14000 24000 58.3333
2 2013-09-01 11000 31000 35.4839
2 2013-09-02 13000 33000 39.3939

Note that for Store Id 2 and date 2013-09-03, there is no Inventory table row. Similarly, for Store Id 1
and date 2013-09-03, there is no Sales table row. Since these rows do not have matching rows, they
are not included in the result. This type of join is called an inner join. The default join is inner join. It
can also be explicitly specified on the query as INNER JOIN instead of just JOIN.

In the inner join, the fact that some data is missing is not reflected in the result. To include
unmatched rows an outer join needs to be used. Outer joins are joins that return the matched rows
as well as the unmatched rows from either or both tables.

Le| outer join includes unmatched rows from the le>-side table in the result. Example:

SELECT
#### select columns same as above
FROM Sales S LEFT OUTER JOIN Inventory I
#### join condition same as above

Returns
StoreId Date Sales Inventory SalePercent
1 2013-09-01 10000 41000 24.3902
1 2013-09-02 14000 24000 58.3333
2 2013-09-01 11000 31000 35.4839
2 2013-09-02 13000 33000 39.3939
2 2013-09-03 13000 NULL NULL

Note that the result includes unmatched rows from Sales table (the le>-side table).

Right outer join includes unmatched rows from the right-side table in the result. Example:

SELECT
#### select columns same as above
FROM Sales S RIGHT OUTER JOIN Inventory I
#### join condition same as above
Returns:
StoreId Date Sales Inventory SalePercent
1 2013-09-01 10000 41000 24.3902
1 2013-09-02 14000 24000 58.3333
1 2013-09-03 NULL 43000 NULL
2 2013-09-01 11000 31000 35.4839
2 2013-09-02 13000 33000 39.3939

Note that the result includes unmatched rows from Inventory table (the right-side table).

Full outer join includes unmatched rows from both the joined tables in the result. MySQL does not have
direct support for full outer join – it can be done by doing a union of le> and right outer joins. Example:

SELECT
#### select columns same as above
FROM Sales S LEFT OUTER JOIN Inventory I
#### join condition same as above
UNION
SELECT
#### select columns same as above
FROM Sales S RIGHT OUTER JOIN Inventory I
#### join condition same as above

Returns
StoreId Date Sales Inventory SalePercent
1 2013-09-01 10000 41000 24.3902
1 2013-09-02 14000 24000 58.3333
2 2013-09-01 11000 31000 35.4839
2 2013-09-02 13000 33000 39.3939
2 2013-09-03 13000 NULL NULL
1 2013-09-03 NULL 43000 NULL

The keyword OUTER is op)onal as in case of INNER. So, LEFT OUTER JOIN is same as LEFT JOIN and
RIGHT OUTER JOIN is same as RIGHT JOIN. The ON clause must be present for LEFT or RIGHT joins.

If there join is based on matching column names, NATURAL LEFT JOIN or NATURAL LEFT JOIN can be
used. Note that the ON clause is implied in case of natural join.

You might also like