0% found this document useful (0 votes)
56 views42 pages

Mysql SQL Revision Tour-1

Database systems provide a structured way to store and manage large amounts of data for various purposes like analysis, reporting, and transactions. SQL is a programming language used to query and operate on relational database management systems like MySQL. MySQL is an open source database that uses SQL and stores data in tables that can contain many records. It provides advantages over pure SQL like connectivity tools and works with third party processors.
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)
56 views42 pages

Mysql SQL Revision Tour-1

Database systems provide a structured way to store and manage large amounts of data for various purposes like analysis, reporting, and transactions. SQL is a programming language used to query and operate on relational database management systems like MySQL. MySQL is an open source database that uses SQL and stores data in tables that can contain many records. It provides advantages over pure SQL like connectivity tools and works with third party processors.
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/ 42

Prepared By: Er.

Santosh Chapagain

MYSQL SQL REVISION TOUR


Database System:
● A database system is a software application or a set of software tools that allows
users to efficiently store, manage, retrieve, and manipulate data. It is designed to
provide a structured and organized way to store large amounts of data for
various purposes, such as data analysis, reporting, and transaction processing.
● Database systems are used in a wide range of applications and industries,
including business, healthcare, finance, e-commerce, and more.

Advantages of Database System:


● Database systems provide a structured and organized way to store and manage
data.
Database systems reduce data redundancy(data duplication) to a large extent.
● Database systems control data inconsistency to a large extent.
● Databases facilitate sharing of data.
● Database systems offer robust security features.

SQL (Structured Query Language)


● SQL is a language that enables you to create and operate on relational
databases, which are sets of related information stored in tables.

MYSQL
● It is a freely available open source Relational Database Management System
(RDBMS) that uses Structured QueryLanguage(SQL).
● In the MySQL database , information is stored in Tables. A single MySQL
database can contain many tables at once and store thousands of individual
records.
Prepared By: Er.Santosh Chapagain

SQL MySQL

SQL is a query programming language that MySQL is a relational


manages RDBMS. database management
system that uses SQL.

It is used to query and operate the database. MySQL is used for data
handling, storing, deleting, and
updating the data in tabular
form.

No connectors are available in SQL. It provides the MySQL


Workbench tool to design and
develop databases.

SQL does not allow other processors or even its MySQL is less secure than
own binaries to manipulate data during execution. SQL, as it allows third-party
processors to manipulate data
files during execution.
Prepared By: Er.Santosh Chapagain

DIFFERENT DATA MODELS:


➔ A data model refers to a set of concepts to describe the structure of a
database, and certain constraints (restrictions) that the database should
obey.
➔ The four data model that are used for database management are :
1. Relational data model : In this data model, the data is organized into
tables (i.e. rows and columns). These tables are called relations.
2. Hierarchical data model
3. Network data model
4. Object Oriented data model

RELATIONAL MODEL TERMINOLOGY:


1. Relation : A table storing logically related data is called a Relation.Data must
be atomic in a cell.
2. Tuple : A row of a relation is generally referred to as a tuple.
3. Attribute : A column of a relation is generally referred to as an attribute.
4. Degree : This refers to the number of attributes in a relation.
5. Cardinality : This refers to the number of tuples in a relation.
Keys in SQL:
1. Unique Key:
● Uniquely identifies each record in a database table.
● The unique constraint ensures that all values in a column are different.
● There can be many unique key per table
● A unique key column can contain null values.
2. Primary Key:
● The primary key constraint uniquely identifies each record in a table.
● Primary keys must contain unique values,and can’t contain null values.
● A table can have only one primary key.
3. Candidate Key:
● A candidate key uniquely identifies the other attributes of the table.
● A table can have more than one candidate key.
Prepared By: Er.Santosh Chapagain

4. Alternate Key :
● A candidate key that is not primary key, is called an alternate key.
5. Foreign Key:
● A non-key attribute, whose values are derived from the primary key of
some other table, is known as foreign key in its current table.
● A foreign key can have a different name than the primary key it comes
from.
● Foreign key value can be null, even though primary key value can’t.
● Foreign keys don’t have to be unique in fact, they often aren’t.

REFERENTIAL INTEGRITY:
A referential integrity is a system of rules that a DBMS uses to ensure that relationships
between records in related tables are valid, and that users don’t accidentally delete or
change related data. This integrity is ensured by foreign keys.
CLASSIFICATION OF SQL STATEMENTS:
SQL commands can be mainly divided into following categories:
1. Data Definition Language(DDL) Commands:
Commands that allow you to perform task, related to data definition e.g;
● Creating, altering and dropping.
● Granting and revoking privileges and roles.
● Maintenance commands.
● DDL COMMANDS: CREATE, DROP, ALTER, TRUNCATE, RENAME.

2. Data Manipulation Language(DML) Commands:


Commands that allow you to perform data manipulation e.g., retrieval, insertion, deletion
and modification of data stored in a database.
● DML COMMANDS:INSERT, UPDATE,DELETE.

3. Transaction Control Language(TCL) Commands:


Commands that allow you to manage and control the transactions e.g.,
Prepared By: Er.Santosh Chapagain

● Making changes to database, permanent


● Undoing changes to database, permanent
● Creating savepoints
● Setting properties for current transactions.
● TCL COMMANDS: COMMIT,ROLLBACK,SAVEPOINT

MySQL ELEMENTS
1. Literals 2. Datatypes 3. Nulls 4. Comments
LITERALS
● It refers to a fixed data value. This fixed data value may be of character type or
numeric type. For example, ‘replay’ , ‘Raj’, ‘8’ , ‘306’ are all character literals.
● Numbers not enclosed in quotation marks are numeric literals. E.g. 22 , 18 , 1997
are all numeric literals.
● Numeric literals can either be integer literals i.e., without any decimal or be real
literals i.e. with a decimal point e.g. 17 is an integer literal but 17.0 and 17.5 are
real literals.

DATA TYPES
Data types are means to identify the type of data and associated operations for handling
it. MySQL data types are divided into three categories:
1. Numeric
2. Date and time
3. String types

Numeric Data Type


1. int – used for numbers without decimal.
2. Decimal(m,d) – used for floating/real numbers. m denotes the total length of number
and d is the number of decimal digits.
Prepared By: Er.Santosh Chapagain

Date and Time Data Type


1. date – used to store date in YYYY-MM-DD format.
2. time – used to store time in HH:MM:SS format.

String Data Types


1. char(m) – used to store a fixed length string. m denotes max. number of characters.
2. varchar(m) – used to store a variable length string. m denotes max. no. of
characters.

DIFFERENCE BETWEEN CHAR AND VARCHAR DATA TYPE

S.N Char datatype Varchar datatype

1 It specifies the fixed length character It specifies the variable length character
string. string.

2 When a column is given datatype as When a column is given datatype as


CHAR(n), then MySQL ensures that VARCHAR(n), then the maximum size a
all values stored in that column have value in this column can have is n bytes.
this length i.e. n bytes. If a value is Each value that is stored in this column
shorter than this length n then blanks store exactly as you specify it i.e. no
are added, but the size of value blanks are added if the length is shorter
remains n bytes. than maximum length n.

NULL VALUE
If a column in a row has no value, then the column is said to be null , or to contain a
null. You should use a null value when the actual value is not known or when a value
would not be meaningful.
Prepared By: Er.Santosh Chapagain

DATABASE COMMANDS
Prepared By: Er.Santosh Chapagain

Inserting Dates
Dates are by default entered in ‘YYYY-MM-DD’ format i.e first four digits depicting year,
followed by a hyphen,followed by 2 digits of month, followed by a hyphen and a two digit
day.All this is enclosed in single quotes.

Inserting Data into another Table:


Syntax:
INSERT INTO table1
SELECT * FROM table2;

Note: For this purpose table1 and table2 must be on the same database.
Note: you can also add specific data using where clause like:
Prepared By: Er.Santosh Chapagain

INSERT INTO table1


SELECT * FROM table2;
WHERE salary >7000;

Inserting data into another table of different databases:


INSERT INTO target_database.target_table
SELECT *FROM source_database.source_table;
Prepared By: Er.Santosh Chapagain
Prepared By: Er.Santosh Chapagain
Prepared By: Er.Santosh Chapagain
Prepared By: Er.Santosh Chapagain

● sth%: All starting with sth


● %sth : All ending with sth
● %sth%: All containing with sth
Prepared By: Er.Santosh Chapagain

Note: Relational operator like =, <, > etc can’t be used with NULL
Prepared By: Er.Santosh Chapagain
Prepared By: Er.Santosh Chapagain
Prepared By: Er.Santosh Chapagain
Prepared By: Er.Santosh Chapagain
Prepared By: Er.Santosh Chapagain
Prepared By: Er.Santosh Chapagain
Prepared By: Er.Santosh Chapagain

UNIQUE CONSTRAINT
The UNIQUE constraint ensures that all values in a column are distinct. In other words,
no two rows can hold the same value for a column with UNIQUE constraint.
Prepared By: Er.Santosh Chapagain
Prepared By: Er.Santosh Chapagain
Prepared By: Er.Santosh Chapagain
Prepared By: Er.Santosh Chapagain

MYSQL FUNCTIONS:
Function:A function is a special type of predefined command set that performs some
operation and returns a single value.

Types:
1) Text/String Functions:

a) CHAR():

● CHAR() function converts each integer parameter to a character, and


returns these characters as a string.

Syntax:
CHAR(value1,[value2,....])

Example:

SELECT CHAR(65,66) o/p:AB

● If an argument contains a fractional value or a string type number, they are


considered as integers.

Example: SELECT CHAR(65, 67.3, ‘69.3’) o/p: ACE

Note:

Argument Type:integers Return value:String

b) LCASE()/LOWER():

● This function converts a string into lowercase.

Syntax:

LOWER(str) or LCASE(str)
Prepared By: Er.Santosh Chapagain

Example:

SELECT LCASE(‘HELLO’) o/p: hello

● Returns the argument str, with all letters in lowercase.


● The return value has the same data type as the argument char (CHAR
OR VARCHAR)
● LCASE() function returns NULL when the str parameter is NULL.
○ Example: SELECT LOWER(NULL) o/p: NULL

Argument type:String Return value: String

C) UCASE()/UPPER():

● This function converts the given string into upper case.

Syntax:
UPPER(str)
UCASE(str)
Example:
SELECT UPPER(‘hello’) o/p: HELLO
● Returns the argument str, with all letters in uppercase.
● The return value has the same data type as the argument str.
● UPPER() function returns NULL when the str parameter is NULL.
○ Example: SELECT UPPER(NULL) o/p: NULL

Argument Type: String Return Value:String

D) LENGTH():
● This function returns the length of a given string in bytes.

Syntax:
LENGTH(str)
Example:
SELECT LENGTH(‘hello’) o/p:5
● If argument str has datatype CHAR the lengths include all trailing blanks.
● If argument str is NULL , this function returns NULL.

Argument Type:String Return value: Number


Prepared By: Er.Santosh Chapagain

E) LEFT():

● The LEFT() function returns the leftmost N characters of the string.

Syntax:
LEFT(str,len)

Example:
SELECT LEFT(‘Hello’,1) o/p: H

● Return NULL if any argument is NULL.


● If length exceeds the length of the string, the function returns the string.
● If length is zero or negative, the function returns an empty string.

Argument Type: string, integer Return value: String

F) RIGHT():

● In MySQL, the RIGHT() function returns the rightmost N characters of a string.

Syntax:
RIGHT(str,len)

Example:
SELECT Right(‘hello’,1) o/p: o

● If length exceeds the length of the string, the function returns the string.
● If length is zero or negative, the function returns an empty string.
● Returns Null if any argument is NULL.

Argument type: string, integer Return value:string

G) INSTR():

● INSTR() function returns the position of the first occurrence of a substring in a


string.
Prepared By: Er.Santosh Chapagain

Syntax:
INSTR(string1,string2)

Where,
String1:The string that will be searched.
String2: The string to search for in string1.
If string 2 is not found, this function returns zero.

Example:
SELECT INSTR(‘hello world”,”he”) o/p: 1

SELECT INSTR(‘Hello world”, “wo”) o/p:7 (also include space)

SELECT INSTR(NULL,’go’) o/p:0

SELECT INSTR(NULL, NULL) o/p:NULL

Argument: string,string Return: number

H) LTRIM():

● This function removes leading spaces i.e spaces from the left of the given string.

Syntax:
LTRIM(str)

Example:
SELECT LTRIM(‘ Hello ‘) o/p: Hello

SELECT LTRIM(NULL) o/p:NULL

Argument Type:String Return Value:String


Prepared By: Er.Santosh Chapagain

I) RTRIM():
● This function removes leading spaces i.e spaces from the right of the given
string.

Syntax:
RTRIM(str)

Argument Type: string Return value:string

J) Trim():

● TRIM() function returns a string with the specified leading and/or trailing
characters removed.
● It performs combined functions of LTRIM() and RTRIM().

k) MID()/SUBSTRING()/SUBSTR():
● MID() function returns a substring of a specified length starting from the
specified position.

Syntax:
MID(str, pos, len)
or
SUBSTRING(str,pos,len)
or
SUBSTR(str, pos, len)

● If floating point numbers passed as arguments to substr are automatically


converted to integers.

Parameters
Str
Required. The original string from which to extract the substring.
Pos
Required. The start position of the substring. It can be positive or negative.
If it is negative, extract the substring from the end of the string.
Len
Optional. The length (number of characters) of the substring. If not
specified, extract a substring to the end of the original string.
Prepared By: Er.Santosh Chapagain

Return value
● The MID() function returns a substring of a specified length starting from
the specified position.

● If pos is equal to or exceeds the length of the original string, the function
will return an empty string ‘ ‘.
● If any parameter is NULL, the function will return NULL.

Examples:
MID('Hello', 1, 2) o/p: He
MID('Hello', 2, 2) o/p: el
MID('Hello', 1) o/p: Hello
MID('Hello', 1, 8) o/p: Hello
MID('Hello', -1, 2) o/p: o
MID('Hello', 8, 2) o/p:NULL
MID('Hello', 0, 2) o/p:NULL
MID('Hello', 0) o/p:NULL
MID(NULL, 1, 1) o/p: NULL
Prepared By: Er.Santosh Chapagain

2) Math Functions /Numeric Functions:

a) MOD():
● This function returns modulus(i.e reminder) of given two numbers.

Syntax:
MOD(number1,number2) i.e: number1%number2
● Returns number1 if number2 is greater.

Examples:
MOD(100, 7): 2
MOD(100, 10): 0
MOD(10,100):10
MOD(0, 1): 0
MOD(1, 0): NULL
MOD(NULL, 1): NULL

b) POWER()/POW():
● This function returns mn i.e a number m raised to the nth power.

Syntax:
POWER(m,n) or POW(m,n)
● M and n can be any numbers, but if m is negative, n must be an
integer.

Examples:
POW(2, 0): 1
POW(2, 2): 4
POW(2, 4): 16
POW(2.5, 2): 6.25
Prepared By: Er.Santosh Chapagain

POW(2, -2): 0.25


POW(2, -4): 0.0625
POW(2, NULL): NULL
POW(NULL, 2): NULL
POW(NULL, NULL): NULL

c) ROUND():
● ROUND() function rounds the specified number to the specified
number of decimal places.

Syntax:
ROUND(x,d)

Parameters
X: Required. The number to be rounded.
d: Required. The number of decimal places to round x to. The
default is 0.

Examples:
SELECT ROUND(1123.324,2); o/p:1123.32

SELECT ROUND(1323.212,1); o/p:1323.2

SELECT ROUND(1123.326,2); o/p:1123.33

SELECT ROUND(1268.2358,2); o/p: 1268.24

SELECT ROUND(123.179,4); o/p: 123.179


Prepared By: Er.Santosh Chapagain

In case of negative(i.e d=-ve):


If d= -1 rounding nearest 10
If d= -2 rounding nearest 100
If d= -3 rounding nearest 1000
Examples:
SELECT ROUND(1323.212,-1); o/p:1320

SELECT ROUND(6184.453,-2) o/p:6200

SELECT ROUND(2323.454,-3) o/p:2000

SELECT ROUND(8767.4323432,-3) o/p:9000


Prepared By: Er.Santosh Chapagain

3) Date Functions:
a) NOW():
● The NOW() function returns the current date and time in YYYY-MM-DD
hh:mm:ss or YYYYMMDDhhmmss format.
● NOW() returns a constant time that indicates the time at which the
statement began to execute.

Syntax:
NOW()

Example:
SELECT NOW(); o/p:today’s date

SELECT NOW()+1;

NOTE:
● The result of NOW() + 0 is in the YYYYMMDDhhmmss format.
● NOW() + N means adding N seconds to the current datetime.

b) DATE():
● The DATE() function extracts and returns the date part from a datetime
value.
Syntax:
DATE(expr)

Example:
SELECT DATE('2022-02-28'): 2022-02-28
SELECT DATE('2022-02-28 10:10:10'): 2022-02-28
SELECT DATE(NOW()): 2022-04-13
SELECT DATE('2022-02-30'): NULL
SELECT DATE('Not A Date'): NULL
Prepared By: Er.Santosh Chapagain

c) MONTH():
● The MONTH() function extracts the month part of a date and returns it as
a number.
Syntax:
MONTH(date)

Example:
SELECT MONTH('2022-02-28'); o/p: 2
SELECT MONTH('2022-02-28 10:11:12'); o/p: 2

● The return value of the MONTH() function is between 1 and 12 (i.e


Jan-Dec).

d) MONTHNAME():
● The MONTHNAME() function returns the name of the month for a given
date.
Syntax:
MONTHNAME(date)
Example:
MONTHNAME('2021-01-01'): January
MONTHNAME('2021-12-01'): December
MONTHNAME(NULL): NULL
e) YEAR():
● The YEAR() function extracts the year part of a date and returns it as a
number.
● The return value of YEAR() is 0 or an integer number from 1000 to 9999.
Syntax:
YEAR(date)
Example:
YEAR('2022-02-28 10:11:12'): 2022
YEAR('0000-01-01'): 0
Prepared By: Er.Santosh Chapagain

f) DAY():
● This function returns the day part of a date.
Syntax:
DAY(date)
Example:
DAY('2022-02-28 10:10:10'): 28
DAY(NOW()): today’s day
DAY('2022-02-00'): 0
DAY('2022-02-30'): NULL
DAY('Not A DATE'): NULL
DAY(NULL): NULL

g) DAYNAME():
● The DAYNAME() function returns the weekday name for a given date.
● Return value will be one of the following values: Monday, Tuesday,
Wednesday, Thursday, Friday, Saturday, Sunday.
Syntax:
DAYNAME(date)
Example:
DAYNAME('2022-02-21'): Monday
DAYNAME('2022-02-00'): NULL
DAYNAME('2022-02-30'): NULL
DAYNAME('Not A DATE'): NULL
DAYNAME(NULL): NULL
Prepared By: Er.Santosh Chapagain
Prepared By: Er.Santosh Chapagain
Prepared By: Er.Santosh Chapagain

Difference Between Single Row and Multiple Rows Function

S.N Single Row/Scalar Functions Multiple Row/Group/Aggregate


Functions

1 Single row function is applied on Multiple rows functions are applied on the
each row. group of rows.

2 Single row functions return multiple Multiple Rows Functions return only one
outputs i.e output based on each result i.e output based on a group of rows.
row.

3 Single Rows Functions are: Multiple Rows Functions


String Functions,Numeric are:sum(),count(),max(),min(),avg() etc.
Functions, Date Functions I.e Aggregate Functions
Prepared By: Er.Santosh Chapagain

Querying using SQL

Ordering Records in Result–Order By:


Prepared By: Er.Santosh Chapagain
Prepared By: Er.Santosh Chapagain

Placing Conditions on Groups—Having Clause:

You might also like