SlideShare a Scribd company logo
LECTURE ON
Introduction to DBMS &
MySQL
BY: ABHISHEK BHARDWAJ
PGT- COMPUTER SCIENCE
Introduction to DBMS
DBMS
RDBMS
SQL
Database Database is a collection of related data.
Database System = Database + Software
Data is stored in the form of rows and columns, i.e. in a table.
Structured Query Language
Why Database?
Advantages of Database :
 Data Security eg. Database of a banking system, Database of a
Social Networking Site like Facebook.
 Data is arranged in a specific order.
 Data retrieval is too fast.
 Data manipulation becomes very fast.
 Minimized data inconsistency (anomaly or discrepancy) eg.
Student name is saved as “John Asthana” on a main computer of
school but on teacher registered system same student name is “J.
Asthana”
Relational Database Management System (RDBMS)
RDBMS : In Relational Database Management System (RDBMS),
data is stored in the form of rows and columns, i.e. in a table.
Example: A table named ‘Student’ is shown below
Roll No Name Class Gender
3204 Ram IX M
3205 Sita X F
3206 Mohan XI M
Total Rows/ Tuples/ Cardinality : 03
Total Columns/ Degree : 04
Student
Terms in Relational DB
Ser Term
Terminology in
RDBMS
1. Table Relation
2. Rows Tuples
3. Columns Attribute
4. Pool of Values Domain
NOTE :
(i) Headings are not included in the
counting of rows.
(ii) For attribute Gender, character
values F / M are called domain.
MySQL Installation for Windows
https://www.mysql.com/ : Copy this link in a Browser
Click Here
Click Here
MySQL Installation for Windows
Click Here
Click Here
MySQL Installation for Windows
Click Here
Download
Double Click on downloaded file to run setup.
Click Here
Database Management System (DBMS)
“A DBMS is a collection of programs that enables the users to
create and maintain the database”.
 Hence DBMS is a general-purpose software system that
facilitates the processes of defining, constructing and
manipulating databases for various applications.
 Defining a database involves specifying the data types,
structures and constraints for the data to be stored in the
database.
 Constructing is the process of storing the database itself on
some storage medium that is controlled by the DBMS.
 Manipulating includes such functions as querying the database
to retrieve specific data, updating the database to reflect
changes in the mini world, and generating reports from the data.
Database Management System (DBMS)
Purpose/ Intended Uses of a DBMS
Controlling Redundancy and removing Data Inconsistency : Data
duplication is not possible in DBMS as data is stored at one place
in the database and accessed through a unique key. It also
controls the inconsistency of data i.e. multiple copies of same
data.
Restricting unauthorized access : Multiple users can share a
database at a same time but all users will not be authorized to
access all information in the database because of role of each
user is already defined.
Providing multiple user interface : Casual (random) users may
interact using query language, application programmers uses
programming language interface and menu driven interfaces or
natural languages interface is used for standalone users.
Purpose/ Intended Uses of a DBMS
Enforcing integrity constraints : We can apply certain integrity
constraints that must hold for the data.
e.g. The value of ‘Name’ in STUDENT record must be an string of
no more than 30 alphabetic characters.
Backup and recovery : Provides facility for recovering from
hardware or software failures.
 The backup and recovery subsystem of a DBMS is responsible
for recovery.
SQL (Structured Query Language)
SQL stands for Structured Query Language. It is used to create a
database, which will be there in the form of rows and columns
i.e. in a table.
SQL is a collection of different commands & for every task we
have a command.
All the SQL commands are divided into four sections/Processing
capabilities of SQL :
(i) DDL (Data Definition Language)
(ii) DML (Data Manipulation Language)
(iii) TCL (Transaction Control Language)
(iv) DCL (Data Control Language)
SQL (Structured Query Language)
DDL (Data Definition Language) :
 DDL use commands to create or modify existing structure of
database objects like create, alter, drop or truncate database
objects in database. In SQL server following operations will
come under DDL operations.
CREATE – By using this operation we can create objects (like
Tables, procedures, etc…) in database.
ALTER – We can modify objects (like Tables, procedures,
etc…) in database.
DROP – We can drop or delete objects in database.
TRUNCATE – It will delete all the records from table and it
will reset identity of column to initial value.
A database object is any defined object in a database that is used to store or reference
data. Anything which we make from create command is known as Database Object.
SQL (Structured Query Language)
DML (Data Manipulation Language) :
 DML use commands to perform multiple operations like
insert, update, retrieve and delete data in database.
 In SQL server following operations will come under DML
operations.
INSERT – By using this operation we can insert data in
table.
SELECT – We can get or retrieve data from table.
DELETE – We can delete data from table.
UPDATE – We can update data in the table.
SQL (Structured Query Language)
TCL (Transaction Control Language) :
 TCL use commands to perform multiple transactional
operations like commit, rollback, save transactions in
database.
 In SQL server following operations will come under TCL
operations.
COMMIT – By using this operation we can save work we
done in transactions.
ROLLBACK – We can rollback database to original state
before COMMIT operation on transactions.
SAVE TRANSACTION – We can set save point in transactions.
SQL (Structured Query Language)
DCL (Data Control Language) :
 DCL use commands to secure database objects by creating
roles, permissions using GRANT, REVOKE operations in
database.
 In SQL server following operations will come under DCL
operations.
GRANT – By using this operation we can create access
permissions for users to database.
REVOKE – We can rollback or take back user access
permissions for database.
Characteristics of SQL
(i) SQL is easy to learn.
(ii) SQL is used to access data from relational database
management systems.
(iii) SQL can execute queries against the database.
(iv) SQL is used to describe the data.
(v) SQL is used to define the data in the database and
manipulate it when needed.
(vi) SQL is used to create and drop the database and table.
(vii) SQL is used to create a view, stored procedure, function in a
database.
(viii) SQL allows users to set permissions on tables, procedures,
and views.
Data Types of SQL
Following are some important data types of SQL :
char : char stores only fixed-length character string
(1-255 characters) data types. Use this when
the length of the characters are concise and
known.
varchar : varchar stores variable-length string where
an upper limit of length (65535 characters) is
specified. Use this when the data entries
length is varying.
integer : Stores integer value.
decimal : Stores decimal value.
date : Stores date in year, month, and day.
time : Stores time in hour, minute, and second.
SQL Constraints
Constraints : Constraints are set of rules that are applied to a
table. Constraints enforce limits to the data or type of data
that can be inserted/updated/deleted from a table. The
whole purpose of constraints is to maintain the data
integrity during an update/delete/insert into a table.
Some important SQL constraints are :
(i) Primary Key
(ii) Unique
(iii) NOT NULL
(iv) Default
(v) Check
(vi) Foreign Key
SQL Constraints
 Primary Key constraint states that a field/ attribute/ column
cannot contain duplicate value and it can’t be left blank. It
must uniquely identify each row.
Employee
 In Employee table Emp_Code is Primary Key and this field
does not contain any duplicate value as well as it must not
left with blank.
Emp_Code Emp_Name Emp_Salary
101 Ram 20,000
102 Ravi 25,0000
103 Mohan 15,000
Primary Key = Unique + NOT NULL
SQL Constraints
 Unique constraint states that a field/ attribute/ column
cannot contain duplicate value. UNIQUE constraint enforces
a column or set of columns to have unique values.
Employee
 In Employee table Mobile_No. is Unique, now this field does
not contain any duplicate value but can be left with blank
(null values).
Emp_Code Emp_Name Emp_Salary Mobile_No.
101 Ram 20,000 9925223311
102 Ravi 25,0000 null
103 Mohan 15,000 8906204482
SQL Constraints
 NOT NULL constraint states that a field/ attribute/ column
cannot be left blank. It is used to ensure that a given column
of a table is never assigned the null value.
Employee
 In Employee table if Salary is assigned as NOT NULL
constraint, then this field can’t be left with blank (null
values).
Emp_Code Emp_Name Emp_Salary Mobile_No.
101 Ram 20,000 9925223311
102 Ravi 25,0000 null
103 Mohan 15,000 8906204482
SQL Constraints
 Default constraint states that a field/ attribute/ column may
be given a default value when no values are specified for
that column.
Employee
 In Employee table if Gender is assigned as Default constraint
with value ‘M’, and if no other value is specified in any of the
records then default value ‘M’ will be added to all new
records.
Emp_Code Emp_Name Emp_Salary Mobile_No. Gender
101 Ram 20,000 9925223311 M
102 Rashmi 25,0000 null F
103 Mohan 15,000 8906204482 M
SQL Constraints
 Check constraint states that a field/ attribute/ column can be
checked for a particular condition before entering it into the
table. It will allow only certain values for this column.
Employee
 In Employee table if Emp_Salary is assigned as Check
constraint with a condition Emp_Salary > 10,000, then values
<= 10,000 cannot be assigned to this particular field.
Emp_Code Emp_Name Emp_Salary Mobile_No. Gender
101 Ram 20,000 9925223311 M
102 Rashmi 25,0000 null F
103 Mohan 15,000 8906204482 M
SQL Constraints
 Foreign Key : A Foreign Key is a field (or collection of fields) in
one table, that refers to the Primary Key in another table. The
table with the foreign key is called the child table, and the table
with the primary key is called the referenced or parent table.
The keyword used to create Foreign Key is called references.
Employee Department
 In Employee table Dept_Code is Non Primary Key, while in
Department table Dept_Code is Primary Key. Dept_Code in
Employee table will be treated as Foreign Key.
Emp_Code Emp_Name Dept_Code
101 Ram 2001
102 Rashmi 2001
103 Mohan 2002
Dept_Code Dept_Name
2001 Computer
2002 Biology
2003 Maths
SQL Commands
(CREATE DATABASE)
CREATE DATABASE : This command is used to create database.
Remember that a database is a logical concept.
eg. by using this command a database named employee will be
created on a portion of our hard disk, on which we may create
multiple tables related to this database.
Syntax : mysql> CREATE DATABASE database_name;
SQL Commands
(USE Database)
USE Database : This command is used to select a database. A
database needs to be created only once, but must be selected for
use each time, we begin a mysql session.
eg. by using this command a database named employee will be
selected.
Syntax : mysql> USE database_name;
SQL Commands
(SHOW DATABASES)
SHOW DATABASES : This command list all databases in mysql.
Syntax : mysql> SHOW DATABASES;
SQL Commands
(CREATE TABLE)
After creating database employee, now if we want to create
table emp by the selecting data base employee, then we must
decide the structure of table emp in advance.
Emp_Code Emp_Name Emp_Designation Emp_Mobile Emp_Salary Emp_DOJ
emp
Creating a table means, creating the structure of the table with
column names and its type of data along with their length, which
particular column will hold.
int varchar(50) varchar(40) char(10) decimal date
SQL Commands
(CREATE TABLE)
CREATE TABLE : The statement is used to create a new table in a
database.
Syntax : mysql> CREATE TABLE table_name(
column1 datatype contraint,
column2 datatype contraint,
column3 datatype contraint,
……….
);
Constraint is optional. It may be added as per requirement.
SQL Commands
(CREATE TABLE)
CREATE TABLE : The statement is used to create a new table in a
database.
SQL Commands
(SHOW TABLES)
SHOW TABLES : The statement is used to get a list of the tables in
a mysql database.
eg. In our previous example we have created a table emp under
employee database, so after using this command list of all tables
under employee database will be displayed.
Syntax : mysql> SHOW TABLES;
SQL Commands
(INSERT INTO)
INSERT INTO : The INSERT INTO statement is used to insert new
records (row) in a table.
It is possible to write the INSERT INTO statement in two ways:
Syntax -1 : mysql> INSERT INTO table_name
VALUES(value1, value2, value3,……..);
Syntax-1 is used when, we have values for each field. If not so, use Syntax-2.
SQL Commands
(INSERT INTO)
INSERT INTO : The INSERT INTO statement is used to insert new
records (row) in a table.
Syntax-2:
mysql> INSERT INTO table_name (column1, column2,...)
VALUES (value1, value2, ...);
• In Syntax-2 select the columns/fields then assign values in the sequence of fields.
• Only those fields can be left in Syntax-2 which do not have constraint NOT NULL.
SQL Commands
(UPDATE)
UPDATE : The UPDATE statement is used to modify the existing
records in a table.
Syntax : mysql> UPDATE table_name
SET field1=value1, field2=value2,….
WHERE condition;
• WHERE clause is used because if, condition is not added, then, all employees having salary
=70000 will be updated to salary=90000.
SQL Commands
(ALTER)
ALTER : The ALTER statement is used to add, delete, or modify
columns in an existing table.
 The ALTER TABLE statement is also used to add and drop
various constraints on an existing table
Syntax to ADD column/field :
mysql> ALTER TABLE table_name
ADD column_name data type;
• After ADDING column/ field, it is required to fill values with respect to that
field in each record.
• Data type char by default takes 1 character , so we may write it as char(1)
or simply char, while executing query on SQL prompt.
SQL Commands
(ALTER)
Syntax to ADD column/field : To add a column in a table.
mysql> ALTER TABLE table_name
ADD column_name data type;
ADDING new column in existing
table emp.
UPDATING record wrt new
column in existing table emp.
SQL Commands
(ALTER)
Syntax to DROP column/field : To delete a column in a table.
mysql> ALTER TABLE table_name
DROP column_name;
Column deleted after
drop statement.
SQL Commands
(ALTER)
Syntax to MODIFY column/field : To change the data type of a
column in a table.
mysql> ALTER TABLE table_name
MODIFY column_name data type;
SQL Commands
(ALTER)
Syntax to RENAME column/field for MySQL version 5.7 :
mysql> ALTER TABLE table_name
CHANGE old_column_name new_column_name data type;
Syntax to RENAME Column in MySQL 8.0 :
ALTER TABLE table_name RENAME COLUMN old_column_name TO new_column_name;
SQL Commands
(DESCRIBE)
DESCRIBE/ DESC : The DESC is the short form of DESCRIBE
command and used to display the information about a table like
column names and constraints on column name.
Syntax : mysql> DESC table_name;
The DESCRIBE/ DESC command is equivalent to the following command :
Syntax : mysql> SHOW COLUMS FROM table_name;
SQL Commands
(SELECT)
SELECT : The SELECT statement is used to select data from a
database. The data returned is stored in a result table, called the
result-set.
Syntax 1: mysql> SELECT * FROM table_name;
SQL Commands
(SELECT)
SELECT : The SELECT statement is used to select data from a
database. Here, column1, column2, ... are the field names of the
table, we want to select data from.
Syntax 2:
mysql> SELECT column1, column2, … FROM table_name;
SQL Commands
(SELECT with WHERE clause)
SELECT with WHERE clause : The WHERE clause is used to filter
records. It is used to extract only those records that fulfill a
specified condition.
Syntax 3: mysql> SELECT * FROM table_name WHERE condition;
WHERE clause is not only used in SELECT statements, it is also used in UPDATE, DELETE, etc.!
SQL Commands
(Examples of SELECT with WHERE clause)
 Select the list of all the employees having salary >90000.
SQL Commands
(Examples of SELECT with WHERE clause)
 Display the list of all the employees, who have joined before
2022.
SQL Commands
(Examples of SELECT with WHERE clause)
 Display the list of all the employees, who have been
appointed as Developer.
SQL Commands
(Examples of SELECT with WHERE clause)
 Display the list of all the employees, who have joined before
2022 AND have salary<100000.
MySQL logical AND operator compares two expressions and returns true if both of the
expressions are true.
SQL Commands
(Examples of SELECT with WHERE clause)
 Display the list of all the employees, who have joined before
2022 OR have salary<100000.
MySQL logical OR operator compares two expressions and returns true if any of the
expressions is true.
SQL Commands
(Examples of SELECT with WHERE clause)
 Display the list of all the employees, who have salary in
between 80000 - 100000.
SQL Commands
(SELECT DISTINCT)
SELECT DISTINCT : The SELECT DISTINCT statement is used to
return only distinct (different) values.
Inside a table, a column often contains many duplicate values;
and DISTINCT keyword list the different (distinct) values.
Syntax: mysql> SELECT DISTINCT column1, column2, ...
FROM table_name;
SQL Commands
(BETWEEN)
BETWEEN : The BETWEEN operator selects values within a given
range. The values can be numbers, text, or dates.
The BETWEEN operator is inclusive : begin and end values are
included.
Syntax: mysql> SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
SQL Commands
(IN Operator)
IN : The IN operator allows you to specify multiple values in
a WHERE clause.
The IN operator is a shorthand for multiple OR conditions.
Syntax : mysql> SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
SQL Commands
(NOT IN Operator)
NOT IN : The NOT operator negates the IN operator.
Syntax : mysql> SELECT column_name(s)
FROM table_name
WHERE column_name NOT IN (value1, value2, ...);
SQL Commands
(Pattern Matching & LIKE Operator)
SQL pattern matching enables us to use _ to match any single
character and % to match an arbitrary number of characters
(including zero characters). In MySQL, SQL patterns are case-
insensitive by default.
LIKE :The LIKE operator is used in a WHERE clause to search for a
specified pattern in a column.
There are two wildcards often used in conjunction with
the LIKE operator:
(a) The percent sign (%) represents zero, one, or multiple
characters.
(b) The underscore sign (_) represents one, single character
The percent sign and the underscore can also be used in combinations!
NOT LIKE : NOT operator negates the LIKE operator.
SQL Commands
(Pattern Matching & LIKE Operator)
Syntax : mysql> SELECT * FROM table_name
WHERE column LIKE pattern;
Examples of LIKE Operator :
LIKE Operator Description
WHERE Emp_Name LIKE 'a%' Finds any values that start with "a"
WHERE Emp_Name LIKE '%a' Finds any values that end with "a"
WHERE Emp_Name LIKE '%or%' Finds any values that have "or" in any
position
WHERE Emp_Name LIKE '_r%' Finds any values that have "r" in the second
position
WHERE Emp_Name LIKE 'a_%' Finds any values that start with "a" and are
at least 2 characters in length
WHERE Emp_Name LIKE 'a_ _%' Finds any values that start with "a" and are
at least 3 characters in length
WHERE Emp_Name LIKE 'a%o' Finds any values that start with "a" and ends
with "o"
SQL Commands
(Pattern Matching & LIKE Operator)
After A here are 4 Underscores to
match with Designation – Admin
If there is no match in record, then it
shows Empty Set as output.
SQL Commands
(Foreign Key Concept)
Foreign Key : The foreign key is used to link one or more than one
table together.
 It is also known as the referencing key.
 A foreign key matches the primary key field of another table.
 It means a foreign key field in one table refers to the primary
key field of the other table.
 It identifies each row of another table uniquely that
maintains the referential integrity in MySQL.
MySQL defines the foreign key in two ways:
 Using CREATE TABLE Statement
 Using ALTER TABLE Statement
SQL Commands
(Foreign Key Theory Concept Not to be written in Exam)
Using CREATE TABLE (Method-1) : Use it, when, we are declaring
Foreign Key at the time of Creating New Table.
E_Code E_Name E_Salary Dept_Code
child
Dept_Code Dept_Name Dept_HoD
parent
Foreign Key
Primary Key
Primary Key
1. Data type of Dept_Code field must be same in both tables i.e. here it is declared as INTEGER.
2. REFERENCES keyword is used in child table to make Dept_Code Foreign Key for parent table.
3. Dept_Code in child table REFERENCES Dept_Code in parent table (parent.Dept_Code) which
creates a connection between two tables i.e. parent and child table.
SQL Commands
(Foreign Key Practical Concept For Exam Purpose)
Using CREATE TABLE (Method-2) : Use it, when, we are declaring
Foreign Key at the time of Creating New Table.
E_Code E_Name E_Salary Dept_Code
child
Dept_Code Dept_Name Dept_HoD
parent
Foreign Key
Primary Key
Primary Key
SQL Commands
(Foreign Key Concept)
Using ALTER TABLE : Use it, when, we have existing tables and
want to ADD constraint Foreign Key.
E_Code E_Name E_Salary Dept_Code
children
Dept_Code Dept_Name Dept_HoD
parents
Foreign Key
Primary Key
Primary Key
SQL Commands
(MySQL Functions)
MySQL Functions : MySQL has many built-in functions.
This reference contains string, numeric, date and time, functions
in MySQL.
1. String / Char Function
2. Numeric Function
3. Date & Time Function
SQL Commands
(MySQL Functions – String / Char Function)
CHAR() : MySQL CHAR() returns the character value of the given
integer value according to the ASCII table. It ignores the NULL
value.
Example : SELECT CHAR(65);
Output : A
Example : SELECT CHAR(67,72,65,82);
Output : CHAR
SQL Commands
(MySQL Functions – String / Char Function)
CONCAT() : Adds two or more expressions together.
Example : SELECT CONCAT(“MEERA”, “DESAI”);
Output : MEERADESAI
SQL Commands
(MySQL Functions – String / Char Function)
LOWER() / LCASE() : Converts a string to lower-case.
Example : SELECT LCASE(“I LOVE MY COUNTRY”);
Output : i love my country
SQL Commands
(MySQL Functions – String / Char Function)
UPPER() / UCASE() : Converts a string to upper-case.
Example : SELECT UCASE(“i love my country”);
Output : I LOVE MY COUNTRY
SQL Commands
(MySQL Functions – String / Char Function)
SUBSTR() : Extracts a substring from a string (starting at any
position).
Syntax : SUBSTRING(string, position, no_of_characters)
Example : SELECT SUBSTR(“MOHAN”,3, 3 );
Output : HAN
-3 will be counted from
last character of the
string i.e. N but after
counting -3 from last
character, 3 characters
of substring will taken in
sequence i.e. HAN
SQL Commands
(MySQL Functions – String / Char Function)
LTRIM() : Removes leading spaces from a string.
Syntax : LTRIM(string)
Example : SELECT LTRIM(“ MOHAN” );
Output : MOHAN
SQL Commands
(MySQL Functions – String / Char Function)
RTRIM() : Removes trailing spaces from a string.
Syntax : RTRIM(string)
Example : SELECT RTRIM(“MOHAN ” );
Output : MOHAN
SQL Commands
(MySQL Functions – String / Char Function)
TRIM() : Removes leading and trailing spaces from a string.
Syntax : TRIM(string)
Example : SELECT TRIM(“ MOHAN ” );
Output : MOHAN
Removing Leading
Character “X” from the
String.
Removing Trailing
Character “X” from the
String.
Removing Trailing &
Leading Character “X”
from the String.
SQL Commands
(MySQL Functions – String / Char Function)
INSTR() : Returns the position of the first occurrence of a string in
another string. If string2 is not found, this function returns 0.
Syntax : INSTR(string1, string2)
Example : SELECT INSTR(“MOHAN”, “HAN” );
Output : 3
SQL Commands
(MySQL Functions – String / Char Function)
LENGTH() : Returns the length of a string (in bytes).
Syntax : LENGTH(string)
Example : SELECT LENGTH(“MOHAN” );
Output : 5
SQL Commands
(MySQL Functions – String / Char Function)
LEFT() : Extracts a number of characters from a string (starting
from left).
Syntax : LEFT(string, number_of_chars)
Example : SELECT LEFT(“MOHAN”, 4 );
Output : MOHA
If this parameter is
larger than the
number of characters
in string, this function
will return string.
SQL Commands
(MySQL Functions – String / Char Function)
RIGHT() : Extracts a number of characters from a string (starting
from right).
Syntax : RIGHT(string, number_of_chars)
Example : SELECT RIGHT(“MOHAN”, 4 );
Output : OHAN
If this parameter is
larger than the
number of characters
in string, this function
will return string.
SQL Commands
(MySQL Functions – String / Char Function)
MID() : Extracts a substring from a string (starting at any
position)
Syntax : MID(string, start_pos, number_of_chars)
Example : SELECT MID(“MOHAN”, 2, 3 );
Output : OHA
The start position, Can
be both a positive or
negative number. If it is a
positive number, this
function extracts from the
beginning of the string. If
it is a negative number,
this function extracts
from the end of the string
SQL Commands
(MySQL Functions – Numeric Function)
MOD() : Returns the remainder of a number divided by another
number.
Syntax : MOD(x, y)
Example : SELECT MOD(5, 2);
Output : 1
If the divisor is zero,
The MOD (dividend,
0) returns NULL.
SQL Commands
(MySQL Functions – Numeric Function)
POWER()/POW() : Returns the value of a number raised to the
power of another number.
Syntax : POW(x, y)
Example : SELECT POW(5, 2);
Output : 25
SQL Commands
(MySQL Functions – Numeric Function)
ROUND() : Rounds a number to a specified number of decimal
places.
Syntax : ROUND(number, decimal_places)
Example : SELECT ROUND(15.567, 2);
Output : 15.57
Nearest TENS
Nearest HUNDRED
Nearest THOUSAND
SQL Commands
(MySQL Functions – Numeric Function)
SIGN() : Returns the sign of a number.
If number > 0, it returns 1
If number = 0, it returns 0
If number < 0, it returns -1
Syntax : SIGN(number)
Example : SELECT SIGN(15);
Output : 1
SQL Commands
(MySQL Functions – Numeric Function)
SQRT() : Return the square root of a number
Syntax : SQRT(number)
Example : SELECT SQRT(64);
Output : 8
SQL Commands
(MySQL Functions – Numeric Function)
TRUNCATE() : The TRUNCATE() function truncates (to make something
shorter) a number to the specified number of decimal places.
Syntax : TRUNCATE(number, decimals)
Example : SELECT TRUNCATE(15.565);
Output : 15.56
Nearest TENS
Nearest HUNDRED
Nearest THOUSAND
SQL Commands
(MySQL Functions – Numeric Function)
Implementation of TRUNCATE() on a Table Column :
TRUNCATE() can be used with other function like AVG(), which will calculate the AVERAGE
SALARY of a particular department . Also TRUNCATE() function can be used to view records of
numeric data to the specified number of decimal places.
SQL Commands
(MySQL Functions – Date & Time Function)
CURDATE()/ CURRENT_DATE() : Returns the current date.
Syntax : CURDATE() /CURRENT_DATE()
Example : SELECT CURDATE();
Output : 2022-03-18
The date is returned as "YYYY-MM-DD" (string) or as YYYYMMDD (numeric)
format depending on whether numeric or string is used in the function.
* Result is depending upon
current System date.
* Result is depending upon
current System date.
SQL Commands
(MySQL Functions – Date & Time Function)
Ques : Display the date after 10 days from the Current Date.
Ques : Display the date before 10 days from the Current Date.
Syntax : SELECT DATE_ADD(DATE, INTERVAL N DAY);
Syntax : SELECT DATE_SUB(DATE, INTERVAL N DAY);
SQL Commands
(MySQL Functions – Date & Time Function)
DATE() : Extracts the date part from a date-time expression.
Returns NULL if expression is not a date or a date-time.
Syntax : DATE()
Example : SELECT DATE(“2022-03-18 10:50:00”);
Output : 2022-03-18
In database many entries are done in date and time stamp format. This format is used to
extract date from that format.
SQL Commands
(MySQL Functions – Date & Time Function)
MONTH() : Returns the month part for a given date.
Syntax : MONTH()
Example : SELECT MONTH(“2022-03-18”);
SELECT MONTH(CURDATE());
Output : 3
SQL Commands
(MySQL Functions – Date & Time Function)
MONTHNAME() : The MONTHNAME() function returns the name
of the month for a given date.
Syntax : MONTHNAME()
Example : SELECT MONTHNAME(“2022-03-18”);
SELECT MONTHNAME(CURDATE());
Output : MARCH
SQL Commands
(MySQL Functions – Date & Time Function)
DAY() : Return the day of the month for a date.
Syntax : DAY()
Example : SELECT DAY(“2022-03-18”);
SELECT DAY(CURDATE());
Output : 18
SQL Commands
(MySQL Functions – Date & Time Function)
DAYNAME() : Returns the weekday name for a given date.
Syntax : DAYNAME()
Example : SELECT DAYNAME(“2022-03-18”);
SELECT DAYNAME(CURDATE());
Output : FRIDAY
SQL Commands
(MySQL Functions – Date & Time Function)
YEAR() : Returns the year part for a given date.
Syntax : YEAR()
Example : SELECT YEAR(“1983-02-08”);
SELECT YEAR(CURDATE());
Output : 1983, 2022
SQL Commands
(MySQL Functions – Date & Time Function)
DAYOFMONTH() : Returns the day of the month for a given date.
Syntax : DAYOFMONTH()
Example : SELECT DAYOFMONTH(“2022-03-18”);
Output : 18
DAY() and DAYOFMONTY() both returns the Day of a given date, but the difference is DAY()
returns the Day of a particular date, while DAYOFMONTH() returns the day in terms of ‘nth ‘
day of the month.
SQL Commands
(MySQL Functions – Date & Time Function)
DAYOFWEEK() : Returns the weekday index for a given date.
Syntax : DAYOFWEEK()
Example : SELECT DAYOFWEEK(“2022-03-18”);
Output : 6
1ST DAY OF WEEK IS SUNDAY.
SQL Commands
(MySQL Functions – Date & Time Function)
DAYOFYEAR() : Returns the day of the year for a given date.
Syntax : DAYOFYEAR()
Example : SELECT DAYOFYEAR(“2022-03-18”);
Output : 77
SQL Commands
(MySQL Functions – Date & Time Function)
NOW() : Returns the current date and time.
Syntax : NOW()
Example : SELECT NOW();
Output : 2022-03-18 11:50:00
SQL Commands
(MySQL Functions – Date & Time Function)
SYSDATE() : Return the current date and time.
Syntax : SYSDATE()
Example : SELECT SYSDATE();
Output : 2022-03-18 11:52:50
SQL Commands
(MySQL Functions – Date & Time Function)
Difference between NOW() and SYSDATE() : The output of both of
them depends upon the execution time.
 NOW() function returns a steady (fix) time that indicates the
time at which the particular statement began to execute.
 SYSDATE() function returns the accurate time at which the
statement executes.
SQL Commands
(Two Types of SQL Functions)
Functions
Multiple- row
functions
Single- row
functions
String Function
Numeric Function
Date Function
Aggregate Function
• Single-row functions operate on single row only and return one result per row.
• Multiple-row functions can manipulate groups of rows to give one result per group of rows.
These functions are also known as group functions.
SQL Commands
(MySQL Functions – Aggregate Function)
AVG() : The AVG() function returns the average value of a
numeric column.
Syntax : SELECT AVG (column_name) FROM table_name
WHERE condition;
SQL Commands
(MySQL Functions – Aggregate Function)
MAX() : The MAX() function returns the largest value of the
selected column.
Syntax : SELECT MAX (column_name) FROM table_name
WHERE condition;
SQL Commands
(MySQL Functions – Aggregate Function)
Ques : Display the details of the employee, getting MAX Salary.
Syntax : SELECT * FROM table_name
WHERE column_name=(SELECT MAX (column_name)
FROM table_name);
Nested Query
SQL Commands
(MySQL Functions – Aggregate Function)
MIN() : The MIN() function returns the smallest value of the
selected column.
Syntax : SELECT MIN (column_name) FROM table_name
WHERE condition;
SQL Commands
(MySQL Functions – Aggregate Function)
Ques : Display the details of the employee, getting MIN Salary.
Syntax : SELECT * FROM table_name
WHERE column_name=(SELECT MIN (column_name)
FROM table_name);
Nested Query
SQL Commands
(MySQL Functions – Aggregate Function)
COUNT() : The COUNT() function returns the number of rows that
matches a specified criterion.
Syntax : SELECT COUNT (column_name) FROM table_name
WHERE condition;
Returns Nos. of
Records/ Rows
in a Table.
Returns Nos. of
Records/ Rows who
have salary<100000.
SQL Commands
(MySQL Functions – Aggregate Function)
SUM() : The SUM() function returns the total sum of a numeric
column.
Syntax : SELECT SUM (column_name) FROM table_name
WHERE condition;
Sum of Salary of
employees, having,
Emp_Code BETWEEN
101 AND 103
Sum of Salary of all
employees.
SQL Commands
(ALTERNATE KEY)
ALTERNATE KEYS : is a column or group of columns in a table that
uniquely identify every row in that table.
 A table can have multiple choices for a primary key but only one
can be set as the primary key.
 All the keys which are not primary key are called an Alternate Key.
Example:
In this table, StudID, Roll No, Email are qualified to become a primary
key. But since StudID is the primary key, Roll No, Email becomes the
alternative key.
SQL Commands
(CANDIDATE KEY)
CANDIDATE KEYS : is a set of attributes that uniquely identify tuples in
a table.
The Primary key should be selected from the candidate keys.
Every table must have at least a single candidate key.
A table can have multiple candidate keys but only a single primary key.
Properties of Candidate key:
 It must contain unique values.
 Must not contain null values.
 Uniquely identify each record in a table.
SQL Commands
(ADD PRIMARY KEY)
ADD PRIMARY KEY : Creates Primary Key constraint on the table.
Syntax : mysql> ALTER TABLE table_name
ADD PRIMARY KEY (column_name);
SQL Commands
(REMOVE PRIMARY KEY)
DROP PRIMARY KEY : Removes Primary Key constraint from the
table.
Syntax : mysql> ALTER TABLE table_name DROP PRIMARY KEY;
SQL Commands
(DELETE RECORD/ROW/TUPLE)
DELETE : The DELETE statement is used to delete existing records
in a table.
Syntax : mysql> DELETE FROM table_name WHERE CONDITION;
Be careful when deleting records in a table! If you omit
the WHERE clause, all records in the table will be deleted!
DELETE FROM STUD;
QUERY WILL DELETE
ALL THE RECORDS AT
ONCE.
SQL Commands
(GROUP BY)
GROUP BY : GROUP BY clause is used to collect data from
multiple records and group the result by one or more column.
 It is generally used in a SELECT statement.
 We can also use some aggregate functions like COUNT, SUM,
MIN, MAX, AVG etc. on the grouped column.
Syntax : mysql> SELECT column(s), AGGREGATE function
FROM table_name
WHERE condition
GROUP BY column;
Continue……
SQL Commands
(GROUP BY)
Query : Count repetitive number of Employees’ names in
EMP_NAME column from database table EMP.
SQL Commands
(ORDER BY)
ORDER BY : Using the ORDER BY clause, we can sort the records
in ascending or descending order as per our requirement.
 The records will be sorted in ascending order whenever
the ASC keyword is used with ORDER BY clause.
 DESC keyword will sort the records in descending order.
If no keyword is specified after the column based on which we
have to sort the records, in that case, the sorting will be done by
default in the ascending order.
Syntax : mysql> SELECT Column_Name(s)
FROM Table_Name
ORDER BY Column_Name ASC/DESC;
Continue……
SQL Commands
(ORDER BY)
Query : Sort the records in the descending order by using sorting
on EMP_ID column from the EMP table.
SQL Commands
(GROUP BY VS. ORDER BY)
 The GROUP BY clause is applicable when we want to use
aggregate functions to more than one set of rows.
 The ORDER BY clause is applicable when we want to get the
data obtained by a query in the sorting order.

More Related Content

Similar to Lecture on DBMS & MySQL.pdf v. C. .

SQL_NOTES.pdf
SQL_NOTES.pdfSQL_NOTES.pdf
SQL_NOTES.pdf
AnshumanDwivedi14
 
Database COMPLETE
Database COMPLETEDatabase COMPLETE
Database COMPLETE
Abrar ali
 
Database Management System (DBMS).pptx
Database Management System (DBMS).pptxDatabase Management System (DBMS).pptx
Database Management System (DBMS).pptx
GevitaChinnaiah
 
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptxMy lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
EliasPetros
 
SQL2.pptx
SQL2.pptxSQL2.pptx
SQL2.pptx
RareDeath
 
Relational Database Language.pptx
Relational Database Language.pptxRelational Database Language.pptx
Relational Database Language.pptx
Sheethal Aji Mani
 
Introduction to dbms
Introduction to dbmsIntroduction to dbms
Introduction to dbms
Umamaheshwariv1
 
Sql server
Sql serverSql server
Sql server
Puja Gupta
 
Introduction to the Structured Query Language SQL
Introduction to the Structured Query Language SQLIntroduction to the Structured Query Language SQL
Introduction to the Structured Query Language SQL
Harmony Kwawu
 
Dbms Basics
Dbms BasicsDbms Basics
unit 1.pptx
unit 1.pptxunit 1.pptx
unit 1.pptx
GayathriPG3
 
12 SQL
12 SQL12 SQL
12 SQL
12 SQL12 SQL
SQL interview questions by jeetendra mandal - part 4
SQL interview questions by jeetendra mandal - part 4SQL interview questions by jeetendra mandal - part 4
SQL interview questions by jeetendra mandal - part 4
jeetendra mandal
 
Adbms
AdbmsAdbms
Adbms
jass12345
 
4.Database Management System.pdf
4.Database Management System.pdf4.Database Management System.pdf
4.Database Management System.pdf
Export Promotion Bureau
 
Introduction to sql server
Introduction to sql serverIntroduction to sql server
Introduction to sql server
Vinay Thota
 
Mysql
MysqlMysql
Mysql
TSUBHASHRI
 
2nd chapter dbms.pptx
2nd chapter dbms.pptx2nd chapter dbms.pptx
2nd chapter dbms.pptx
kavitha623544
 
SQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdfSQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdf
DraguClaudiu
 

Similar to Lecture on DBMS & MySQL.pdf v. C. . (20)

SQL_NOTES.pdf
SQL_NOTES.pdfSQL_NOTES.pdf
SQL_NOTES.pdf
 
Database COMPLETE
Database COMPLETEDatabase COMPLETE
Database COMPLETE
 
Database Management System (DBMS).pptx
Database Management System (DBMS).pptxDatabase Management System (DBMS).pptx
Database Management System (DBMS).pptx
 
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptxMy lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
 
SQL2.pptx
SQL2.pptxSQL2.pptx
SQL2.pptx
 
Relational Database Language.pptx
Relational Database Language.pptxRelational Database Language.pptx
Relational Database Language.pptx
 
Introduction to dbms
Introduction to dbmsIntroduction to dbms
Introduction to dbms
 
Sql server
Sql serverSql server
Sql server
 
Introduction to the Structured Query Language SQL
Introduction to the Structured Query Language SQLIntroduction to the Structured Query Language SQL
Introduction to the Structured Query Language SQL
 
Dbms Basics
Dbms BasicsDbms Basics
Dbms Basics
 
unit 1.pptx
unit 1.pptxunit 1.pptx
unit 1.pptx
 
12 SQL
12 SQL12 SQL
12 SQL
 
12 SQL
12 SQL12 SQL
12 SQL
 
SQL interview questions by jeetendra mandal - part 4
SQL interview questions by jeetendra mandal - part 4SQL interview questions by jeetendra mandal - part 4
SQL interview questions by jeetendra mandal - part 4
 
Adbms
AdbmsAdbms
Adbms
 
4.Database Management System.pdf
4.Database Management System.pdf4.Database Management System.pdf
4.Database Management System.pdf
 
Introduction to sql server
Introduction to sql serverIntroduction to sql server
Introduction to sql server
 
Mysql
MysqlMysql
Mysql
 
2nd chapter dbms.pptx
2nd chapter dbms.pptx2nd chapter dbms.pptx
2nd chapter dbms.pptx
 
SQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdfSQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdf
 

Recently uploaded

PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
AyyanKhan40
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
Dr. Shivangi Singh Parihar
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
Colégio Santa Teresinha
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
Scholarhat
 
Assessment and Planning in Educational technology.pptx
Assessment and Planning in Educational technology.pptxAssessment and Planning in Educational technology.pptx
Assessment and Planning in Educational technology.pptx
Kavitha Krishnan
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
mulvey2
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
Dr. Mulla Adam Ali
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
Celine George
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
TechSoup
 
How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
Celine George
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
Academy of Science of South Africa
 
Smart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICTSmart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICT
simonomuemu
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
Nguyen Thanh Tu Collection
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
Israel Genealogy Research Association
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
amberjdewit93
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
Celine George
 

Recently uploaded (20)

PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
 
Assessment and Planning in Educational technology.pptx
Assessment and Planning in Educational technology.pptxAssessment and Planning in Educational technology.pptx
Assessment and Planning in Educational technology.pptx
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
 
How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
 
Smart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICTSmart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICT
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
 

Lecture on DBMS & MySQL.pdf v. C. .

  • 1. LECTURE ON Introduction to DBMS & MySQL BY: ABHISHEK BHARDWAJ PGT- COMPUTER SCIENCE
  • 2. Introduction to DBMS DBMS RDBMS SQL Database Database is a collection of related data. Database System = Database + Software Data is stored in the form of rows and columns, i.e. in a table. Structured Query Language
  • 3. Why Database? Advantages of Database :  Data Security eg. Database of a banking system, Database of a Social Networking Site like Facebook.  Data is arranged in a specific order.  Data retrieval is too fast.  Data manipulation becomes very fast.  Minimized data inconsistency (anomaly or discrepancy) eg. Student name is saved as “John Asthana” on a main computer of school but on teacher registered system same student name is “J. Asthana”
  • 4. Relational Database Management System (RDBMS) RDBMS : In Relational Database Management System (RDBMS), data is stored in the form of rows and columns, i.e. in a table. Example: A table named ‘Student’ is shown below Roll No Name Class Gender 3204 Ram IX M 3205 Sita X F 3206 Mohan XI M Total Rows/ Tuples/ Cardinality : 03 Total Columns/ Degree : 04 Student Terms in Relational DB Ser Term Terminology in RDBMS 1. Table Relation 2. Rows Tuples 3. Columns Attribute 4. Pool of Values Domain NOTE : (i) Headings are not included in the counting of rows. (ii) For attribute Gender, character values F / M are called domain.
  • 5. MySQL Installation for Windows https://www.mysql.com/ : Copy this link in a Browser Click Here Click Here
  • 6. MySQL Installation for Windows Click Here Click Here
  • 7. MySQL Installation for Windows Click Here Download Double Click on downloaded file to run setup. Click Here
  • 8. Database Management System (DBMS) “A DBMS is a collection of programs that enables the users to create and maintain the database”.  Hence DBMS is a general-purpose software system that facilitates the processes of defining, constructing and manipulating databases for various applications.  Defining a database involves specifying the data types, structures and constraints for the data to be stored in the database.  Constructing is the process of storing the database itself on some storage medium that is controlled by the DBMS.  Manipulating includes such functions as querying the database to retrieve specific data, updating the database to reflect changes in the mini world, and generating reports from the data.
  • 10. Purpose/ Intended Uses of a DBMS Controlling Redundancy and removing Data Inconsistency : Data duplication is not possible in DBMS as data is stored at one place in the database and accessed through a unique key. It also controls the inconsistency of data i.e. multiple copies of same data. Restricting unauthorized access : Multiple users can share a database at a same time but all users will not be authorized to access all information in the database because of role of each user is already defined. Providing multiple user interface : Casual (random) users may interact using query language, application programmers uses programming language interface and menu driven interfaces or natural languages interface is used for standalone users.
  • 11. Purpose/ Intended Uses of a DBMS Enforcing integrity constraints : We can apply certain integrity constraints that must hold for the data. e.g. The value of ‘Name’ in STUDENT record must be an string of no more than 30 alphabetic characters. Backup and recovery : Provides facility for recovering from hardware or software failures.  The backup and recovery subsystem of a DBMS is responsible for recovery.
  • 12. SQL (Structured Query Language) SQL stands for Structured Query Language. It is used to create a database, which will be there in the form of rows and columns i.e. in a table. SQL is a collection of different commands & for every task we have a command. All the SQL commands are divided into four sections/Processing capabilities of SQL : (i) DDL (Data Definition Language) (ii) DML (Data Manipulation Language) (iii) TCL (Transaction Control Language) (iv) DCL (Data Control Language)
  • 13. SQL (Structured Query Language) DDL (Data Definition Language) :  DDL use commands to create or modify existing structure of database objects like create, alter, drop or truncate database objects in database. In SQL server following operations will come under DDL operations. CREATE – By using this operation we can create objects (like Tables, procedures, etc…) in database. ALTER – We can modify objects (like Tables, procedures, etc…) in database. DROP – We can drop or delete objects in database. TRUNCATE – It will delete all the records from table and it will reset identity of column to initial value. A database object is any defined object in a database that is used to store or reference data. Anything which we make from create command is known as Database Object.
  • 14. SQL (Structured Query Language) DML (Data Manipulation Language) :  DML use commands to perform multiple operations like insert, update, retrieve and delete data in database.  In SQL server following operations will come under DML operations. INSERT – By using this operation we can insert data in table. SELECT – We can get or retrieve data from table. DELETE – We can delete data from table. UPDATE – We can update data in the table.
  • 15. SQL (Structured Query Language) TCL (Transaction Control Language) :  TCL use commands to perform multiple transactional operations like commit, rollback, save transactions in database.  In SQL server following operations will come under TCL operations. COMMIT – By using this operation we can save work we done in transactions. ROLLBACK – We can rollback database to original state before COMMIT operation on transactions. SAVE TRANSACTION – We can set save point in transactions.
  • 16. SQL (Structured Query Language) DCL (Data Control Language) :  DCL use commands to secure database objects by creating roles, permissions using GRANT, REVOKE operations in database.  In SQL server following operations will come under DCL operations. GRANT – By using this operation we can create access permissions for users to database. REVOKE – We can rollback or take back user access permissions for database.
  • 17. Characteristics of SQL (i) SQL is easy to learn. (ii) SQL is used to access data from relational database management systems. (iii) SQL can execute queries against the database. (iv) SQL is used to describe the data. (v) SQL is used to define the data in the database and manipulate it when needed. (vi) SQL is used to create and drop the database and table. (vii) SQL is used to create a view, stored procedure, function in a database. (viii) SQL allows users to set permissions on tables, procedures, and views.
  • 18. Data Types of SQL Following are some important data types of SQL : char : char stores only fixed-length character string (1-255 characters) data types. Use this when the length of the characters are concise and known. varchar : varchar stores variable-length string where an upper limit of length (65535 characters) is specified. Use this when the data entries length is varying. integer : Stores integer value. decimal : Stores decimal value. date : Stores date in year, month, and day. time : Stores time in hour, minute, and second.
  • 19. SQL Constraints Constraints : Constraints are set of rules that are applied to a table. Constraints enforce limits to the data or type of data that can be inserted/updated/deleted from a table. The whole purpose of constraints is to maintain the data integrity during an update/delete/insert into a table. Some important SQL constraints are : (i) Primary Key (ii) Unique (iii) NOT NULL (iv) Default (v) Check (vi) Foreign Key
  • 20. SQL Constraints  Primary Key constraint states that a field/ attribute/ column cannot contain duplicate value and it can’t be left blank. It must uniquely identify each row. Employee  In Employee table Emp_Code is Primary Key and this field does not contain any duplicate value as well as it must not left with blank. Emp_Code Emp_Name Emp_Salary 101 Ram 20,000 102 Ravi 25,0000 103 Mohan 15,000 Primary Key = Unique + NOT NULL
  • 21. SQL Constraints  Unique constraint states that a field/ attribute/ column cannot contain duplicate value. UNIQUE constraint enforces a column or set of columns to have unique values. Employee  In Employee table Mobile_No. is Unique, now this field does not contain any duplicate value but can be left with blank (null values). Emp_Code Emp_Name Emp_Salary Mobile_No. 101 Ram 20,000 9925223311 102 Ravi 25,0000 null 103 Mohan 15,000 8906204482
  • 22. SQL Constraints  NOT NULL constraint states that a field/ attribute/ column cannot be left blank. It is used to ensure that a given column of a table is never assigned the null value. Employee  In Employee table if Salary is assigned as NOT NULL constraint, then this field can’t be left with blank (null values). Emp_Code Emp_Name Emp_Salary Mobile_No. 101 Ram 20,000 9925223311 102 Ravi 25,0000 null 103 Mohan 15,000 8906204482
  • 23. SQL Constraints  Default constraint states that a field/ attribute/ column may be given a default value when no values are specified for that column. Employee  In Employee table if Gender is assigned as Default constraint with value ‘M’, and if no other value is specified in any of the records then default value ‘M’ will be added to all new records. Emp_Code Emp_Name Emp_Salary Mobile_No. Gender 101 Ram 20,000 9925223311 M 102 Rashmi 25,0000 null F 103 Mohan 15,000 8906204482 M
  • 24. SQL Constraints  Check constraint states that a field/ attribute/ column can be checked for a particular condition before entering it into the table. It will allow only certain values for this column. Employee  In Employee table if Emp_Salary is assigned as Check constraint with a condition Emp_Salary > 10,000, then values <= 10,000 cannot be assigned to this particular field. Emp_Code Emp_Name Emp_Salary Mobile_No. Gender 101 Ram 20,000 9925223311 M 102 Rashmi 25,0000 null F 103 Mohan 15,000 8906204482 M
  • 25. SQL Constraints  Foreign Key : A Foreign Key is a field (or collection of fields) in one table, that refers to the Primary Key in another table. The table with the foreign key is called the child table, and the table with the primary key is called the referenced or parent table. The keyword used to create Foreign Key is called references. Employee Department  In Employee table Dept_Code is Non Primary Key, while in Department table Dept_Code is Primary Key. Dept_Code in Employee table will be treated as Foreign Key. Emp_Code Emp_Name Dept_Code 101 Ram 2001 102 Rashmi 2001 103 Mohan 2002 Dept_Code Dept_Name 2001 Computer 2002 Biology 2003 Maths
  • 26. SQL Commands (CREATE DATABASE) CREATE DATABASE : This command is used to create database. Remember that a database is a logical concept. eg. by using this command a database named employee will be created on a portion of our hard disk, on which we may create multiple tables related to this database. Syntax : mysql> CREATE DATABASE database_name;
  • 27. SQL Commands (USE Database) USE Database : This command is used to select a database. A database needs to be created only once, but must be selected for use each time, we begin a mysql session. eg. by using this command a database named employee will be selected. Syntax : mysql> USE database_name;
  • 28. SQL Commands (SHOW DATABASES) SHOW DATABASES : This command list all databases in mysql. Syntax : mysql> SHOW DATABASES;
  • 29. SQL Commands (CREATE TABLE) After creating database employee, now if we want to create table emp by the selecting data base employee, then we must decide the structure of table emp in advance. Emp_Code Emp_Name Emp_Designation Emp_Mobile Emp_Salary Emp_DOJ emp Creating a table means, creating the structure of the table with column names and its type of data along with their length, which particular column will hold. int varchar(50) varchar(40) char(10) decimal date
  • 30. SQL Commands (CREATE TABLE) CREATE TABLE : The statement is used to create a new table in a database. Syntax : mysql> CREATE TABLE table_name( column1 datatype contraint, column2 datatype contraint, column3 datatype contraint, ………. ); Constraint is optional. It may be added as per requirement.
  • 31. SQL Commands (CREATE TABLE) CREATE TABLE : The statement is used to create a new table in a database.
  • 32. SQL Commands (SHOW TABLES) SHOW TABLES : The statement is used to get a list of the tables in a mysql database. eg. In our previous example we have created a table emp under employee database, so after using this command list of all tables under employee database will be displayed. Syntax : mysql> SHOW TABLES;
  • 33. SQL Commands (INSERT INTO) INSERT INTO : The INSERT INTO statement is used to insert new records (row) in a table. It is possible to write the INSERT INTO statement in two ways: Syntax -1 : mysql> INSERT INTO table_name VALUES(value1, value2, value3,……..); Syntax-1 is used when, we have values for each field. If not so, use Syntax-2.
  • 34. SQL Commands (INSERT INTO) INSERT INTO : The INSERT INTO statement is used to insert new records (row) in a table. Syntax-2: mysql> INSERT INTO table_name (column1, column2,...) VALUES (value1, value2, ...); • In Syntax-2 select the columns/fields then assign values in the sequence of fields. • Only those fields can be left in Syntax-2 which do not have constraint NOT NULL.
  • 35. SQL Commands (UPDATE) UPDATE : The UPDATE statement is used to modify the existing records in a table. Syntax : mysql> UPDATE table_name SET field1=value1, field2=value2,…. WHERE condition; • WHERE clause is used because if, condition is not added, then, all employees having salary =70000 will be updated to salary=90000.
  • 36. SQL Commands (ALTER) ALTER : The ALTER statement is used to add, delete, or modify columns in an existing table.  The ALTER TABLE statement is also used to add and drop various constraints on an existing table Syntax to ADD column/field : mysql> ALTER TABLE table_name ADD column_name data type; • After ADDING column/ field, it is required to fill values with respect to that field in each record. • Data type char by default takes 1 character , so we may write it as char(1) or simply char, while executing query on SQL prompt.
  • 37. SQL Commands (ALTER) Syntax to ADD column/field : To add a column in a table. mysql> ALTER TABLE table_name ADD column_name data type; ADDING new column in existing table emp. UPDATING record wrt new column in existing table emp.
  • 38. SQL Commands (ALTER) Syntax to DROP column/field : To delete a column in a table. mysql> ALTER TABLE table_name DROP column_name; Column deleted after drop statement.
  • 39. SQL Commands (ALTER) Syntax to MODIFY column/field : To change the data type of a column in a table. mysql> ALTER TABLE table_name MODIFY column_name data type;
  • 40. SQL Commands (ALTER) Syntax to RENAME column/field for MySQL version 5.7 : mysql> ALTER TABLE table_name CHANGE old_column_name new_column_name data type; Syntax to RENAME Column in MySQL 8.0 : ALTER TABLE table_name RENAME COLUMN old_column_name TO new_column_name;
  • 41. SQL Commands (DESCRIBE) DESCRIBE/ DESC : The DESC is the short form of DESCRIBE command and used to display the information about a table like column names and constraints on column name. Syntax : mysql> DESC table_name; The DESCRIBE/ DESC command is equivalent to the following command : Syntax : mysql> SHOW COLUMS FROM table_name;
  • 42. SQL Commands (SELECT) SELECT : The SELECT statement is used to select data from a database. The data returned is stored in a result table, called the result-set. Syntax 1: mysql> SELECT * FROM table_name;
  • 43. SQL Commands (SELECT) SELECT : The SELECT statement is used to select data from a database. Here, column1, column2, ... are the field names of the table, we want to select data from. Syntax 2: mysql> SELECT column1, column2, … FROM table_name;
  • 44. SQL Commands (SELECT with WHERE clause) SELECT with WHERE clause : The WHERE clause is used to filter records. It is used to extract only those records that fulfill a specified condition. Syntax 3: mysql> SELECT * FROM table_name WHERE condition; WHERE clause is not only used in SELECT statements, it is also used in UPDATE, DELETE, etc.!
  • 45. SQL Commands (Examples of SELECT with WHERE clause)  Select the list of all the employees having salary >90000.
  • 46. SQL Commands (Examples of SELECT with WHERE clause)  Display the list of all the employees, who have joined before 2022.
  • 47. SQL Commands (Examples of SELECT with WHERE clause)  Display the list of all the employees, who have been appointed as Developer.
  • 48. SQL Commands (Examples of SELECT with WHERE clause)  Display the list of all the employees, who have joined before 2022 AND have salary<100000. MySQL logical AND operator compares two expressions and returns true if both of the expressions are true.
  • 49. SQL Commands (Examples of SELECT with WHERE clause)  Display the list of all the employees, who have joined before 2022 OR have salary<100000. MySQL logical OR operator compares two expressions and returns true if any of the expressions is true.
  • 50. SQL Commands (Examples of SELECT with WHERE clause)  Display the list of all the employees, who have salary in between 80000 - 100000.
  • 51. SQL Commands (SELECT DISTINCT) SELECT DISTINCT : The SELECT DISTINCT statement is used to return only distinct (different) values. Inside a table, a column often contains many duplicate values; and DISTINCT keyword list the different (distinct) values. Syntax: mysql> SELECT DISTINCT column1, column2, ... FROM table_name;
  • 52. SQL Commands (BETWEEN) BETWEEN : The BETWEEN operator selects values within a given range. The values can be numbers, text, or dates. The BETWEEN operator is inclusive : begin and end values are included. Syntax: mysql> SELECT column_name(s) FROM table_name WHERE column_name BETWEEN value1 AND value2;
  • 53. SQL Commands (IN Operator) IN : The IN operator allows you to specify multiple values in a WHERE clause. The IN operator is a shorthand for multiple OR conditions. Syntax : mysql> SELECT column_name(s) FROM table_name WHERE column_name IN (value1, value2, ...);
  • 54. SQL Commands (NOT IN Operator) NOT IN : The NOT operator negates the IN operator. Syntax : mysql> SELECT column_name(s) FROM table_name WHERE column_name NOT IN (value1, value2, ...);
  • 55. SQL Commands (Pattern Matching & LIKE Operator) SQL pattern matching enables us to use _ to match any single character and % to match an arbitrary number of characters (including zero characters). In MySQL, SQL patterns are case- insensitive by default. LIKE :The LIKE operator is used in a WHERE clause to search for a specified pattern in a column. There are two wildcards often used in conjunction with the LIKE operator: (a) The percent sign (%) represents zero, one, or multiple characters. (b) The underscore sign (_) represents one, single character The percent sign and the underscore can also be used in combinations! NOT LIKE : NOT operator negates the LIKE operator.
  • 56. SQL Commands (Pattern Matching & LIKE Operator) Syntax : mysql> SELECT * FROM table_name WHERE column LIKE pattern; Examples of LIKE Operator : LIKE Operator Description WHERE Emp_Name LIKE 'a%' Finds any values that start with "a" WHERE Emp_Name LIKE '%a' Finds any values that end with "a" WHERE Emp_Name LIKE '%or%' Finds any values that have "or" in any position WHERE Emp_Name LIKE '_r%' Finds any values that have "r" in the second position WHERE Emp_Name LIKE 'a_%' Finds any values that start with "a" and are at least 2 characters in length WHERE Emp_Name LIKE 'a_ _%' Finds any values that start with "a" and are at least 3 characters in length WHERE Emp_Name LIKE 'a%o' Finds any values that start with "a" and ends with "o"
  • 57. SQL Commands (Pattern Matching & LIKE Operator) After A here are 4 Underscores to match with Designation – Admin If there is no match in record, then it shows Empty Set as output.
  • 58. SQL Commands (Foreign Key Concept) Foreign Key : The foreign key is used to link one or more than one table together.  It is also known as the referencing key.  A foreign key matches the primary key field of another table.  It means a foreign key field in one table refers to the primary key field of the other table.  It identifies each row of another table uniquely that maintains the referential integrity in MySQL. MySQL defines the foreign key in two ways:  Using CREATE TABLE Statement  Using ALTER TABLE Statement
  • 59. SQL Commands (Foreign Key Theory Concept Not to be written in Exam) Using CREATE TABLE (Method-1) : Use it, when, we are declaring Foreign Key at the time of Creating New Table. E_Code E_Name E_Salary Dept_Code child Dept_Code Dept_Name Dept_HoD parent Foreign Key Primary Key Primary Key 1. Data type of Dept_Code field must be same in both tables i.e. here it is declared as INTEGER. 2. REFERENCES keyword is used in child table to make Dept_Code Foreign Key for parent table. 3. Dept_Code in child table REFERENCES Dept_Code in parent table (parent.Dept_Code) which creates a connection between two tables i.e. parent and child table.
  • 60. SQL Commands (Foreign Key Practical Concept For Exam Purpose) Using CREATE TABLE (Method-2) : Use it, when, we are declaring Foreign Key at the time of Creating New Table. E_Code E_Name E_Salary Dept_Code child Dept_Code Dept_Name Dept_HoD parent Foreign Key Primary Key Primary Key
  • 61. SQL Commands (Foreign Key Concept) Using ALTER TABLE : Use it, when, we have existing tables and want to ADD constraint Foreign Key. E_Code E_Name E_Salary Dept_Code children Dept_Code Dept_Name Dept_HoD parents Foreign Key Primary Key Primary Key
  • 62. SQL Commands (MySQL Functions) MySQL Functions : MySQL has many built-in functions. This reference contains string, numeric, date and time, functions in MySQL. 1. String / Char Function 2. Numeric Function 3. Date & Time Function
  • 63. SQL Commands (MySQL Functions – String / Char Function) CHAR() : MySQL CHAR() returns the character value of the given integer value according to the ASCII table. It ignores the NULL value. Example : SELECT CHAR(65); Output : A Example : SELECT CHAR(67,72,65,82); Output : CHAR
  • 64. SQL Commands (MySQL Functions – String / Char Function) CONCAT() : Adds two or more expressions together. Example : SELECT CONCAT(“MEERA”, “DESAI”); Output : MEERADESAI
  • 65. SQL Commands (MySQL Functions – String / Char Function) LOWER() / LCASE() : Converts a string to lower-case. Example : SELECT LCASE(“I LOVE MY COUNTRY”); Output : i love my country
  • 66. SQL Commands (MySQL Functions – String / Char Function) UPPER() / UCASE() : Converts a string to upper-case. Example : SELECT UCASE(“i love my country”); Output : I LOVE MY COUNTRY
  • 67. SQL Commands (MySQL Functions – String / Char Function) SUBSTR() : Extracts a substring from a string (starting at any position). Syntax : SUBSTRING(string, position, no_of_characters) Example : SELECT SUBSTR(“MOHAN”,3, 3 ); Output : HAN -3 will be counted from last character of the string i.e. N but after counting -3 from last character, 3 characters of substring will taken in sequence i.e. HAN
  • 68. SQL Commands (MySQL Functions – String / Char Function) LTRIM() : Removes leading spaces from a string. Syntax : LTRIM(string) Example : SELECT LTRIM(“ MOHAN” ); Output : MOHAN
  • 69. SQL Commands (MySQL Functions – String / Char Function) RTRIM() : Removes trailing spaces from a string. Syntax : RTRIM(string) Example : SELECT RTRIM(“MOHAN ” ); Output : MOHAN
  • 70. SQL Commands (MySQL Functions – String / Char Function) TRIM() : Removes leading and trailing spaces from a string. Syntax : TRIM(string) Example : SELECT TRIM(“ MOHAN ” ); Output : MOHAN Removing Leading Character “X” from the String. Removing Trailing Character “X” from the String. Removing Trailing & Leading Character “X” from the String.
  • 71. SQL Commands (MySQL Functions – String / Char Function) INSTR() : Returns the position of the first occurrence of a string in another string. If string2 is not found, this function returns 0. Syntax : INSTR(string1, string2) Example : SELECT INSTR(“MOHAN”, “HAN” ); Output : 3
  • 72. SQL Commands (MySQL Functions – String / Char Function) LENGTH() : Returns the length of a string (in bytes). Syntax : LENGTH(string) Example : SELECT LENGTH(“MOHAN” ); Output : 5
  • 73. SQL Commands (MySQL Functions – String / Char Function) LEFT() : Extracts a number of characters from a string (starting from left). Syntax : LEFT(string, number_of_chars) Example : SELECT LEFT(“MOHAN”, 4 ); Output : MOHA If this parameter is larger than the number of characters in string, this function will return string.
  • 74. SQL Commands (MySQL Functions – String / Char Function) RIGHT() : Extracts a number of characters from a string (starting from right). Syntax : RIGHT(string, number_of_chars) Example : SELECT RIGHT(“MOHAN”, 4 ); Output : OHAN If this parameter is larger than the number of characters in string, this function will return string.
  • 75. SQL Commands (MySQL Functions – String / Char Function) MID() : Extracts a substring from a string (starting at any position) Syntax : MID(string, start_pos, number_of_chars) Example : SELECT MID(“MOHAN”, 2, 3 ); Output : OHA The start position, Can be both a positive or negative number. If it is a positive number, this function extracts from the beginning of the string. If it is a negative number, this function extracts from the end of the string
  • 76. SQL Commands (MySQL Functions – Numeric Function) MOD() : Returns the remainder of a number divided by another number. Syntax : MOD(x, y) Example : SELECT MOD(5, 2); Output : 1 If the divisor is zero, The MOD (dividend, 0) returns NULL.
  • 77. SQL Commands (MySQL Functions – Numeric Function) POWER()/POW() : Returns the value of a number raised to the power of another number. Syntax : POW(x, y) Example : SELECT POW(5, 2); Output : 25
  • 78. SQL Commands (MySQL Functions – Numeric Function) ROUND() : Rounds a number to a specified number of decimal places. Syntax : ROUND(number, decimal_places) Example : SELECT ROUND(15.567, 2); Output : 15.57 Nearest TENS Nearest HUNDRED Nearest THOUSAND
  • 79. SQL Commands (MySQL Functions – Numeric Function) SIGN() : Returns the sign of a number. If number > 0, it returns 1 If number = 0, it returns 0 If number < 0, it returns -1 Syntax : SIGN(number) Example : SELECT SIGN(15); Output : 1
  • 80. SQL Commands (MySQL Functions – Numeric Function) SQRT() : Return the square root of a number Syntax : SQRT(number) Example : SELECT SQRT(64); Output : 8
  • 81. SQL Commands (MySQL Functions – Numeric Function) TRUNCATE() : The TRUNCATE() function truncates (to make something shorter) a number to the specified number of decimal places. Syntax : TRUNCATE(number, decimals) Example : SELECT TRUNCATE(15.565); Output : 15.56 Nearest TENS Nearest HUNDRED Nearest THOUSAND
  • 82. SQL Commands (MySQL Functions – Numeric Function) Implementation of TRUNCATE() on a Table Column : TRUNCATE() can be used with other function like AVG(), which will calculate the AVERAGE SALARY of a particular department . Also TRUNCATE() function can be used to view records of numeric data to the specified number of decimal places.
  • 83. SQL Commands (MySQL Functions – Date & Time Function) CURDATE()/ CURRENT_DATE() : Returns the current date. Syntax : CURDATE() /CURRENT_DATE() Example : SELECT CURDATE(); Output : 2022-03-18 The date is returned as "YYYY-MM-DD" (string) or as YYYYMMDD (numeric) format depending on whether numeric or string is used in the function. * Result is depending upon current System date. * Result is depending upon current System date.
  • 84. SQL Commands (MySQL Functions – Date & Time Function) Ques : Display the date after 10 days from the Current Date. Ques : Display the date before 10 days from the Current Date. Syntax : SELECT DATE_ADD(DATE, INTERVAL N DAY); Syntax : SELECT DATE_SUB(DATE, INTERVAL N DAY);
  • 85. SQL Commands (MySQL Functions – Date & Time Function) DATE() : Extracts the date part from a date-time expression. Returns NULL if expression is not a date or a date-time. Syntax : DATE() Example : SELECT DATE(“2022-03-18 10:50:00”); Output : 2022-03-18 In database many entries are done in date and time stamp format. This format is used to extract date from that format.
  • 86. SQL Commands (MySQL Functions – Date & Time Function) MONTH() : Returns the month part for a given date. Syntax : MONTH() Example : SELECT MONTH(“2022-03-18”); SELECT MONTH(CURDATE()); Output : 3
  • 87. SQL Commands (MySQL Functions – Date & Time Function) MONTHNAME() : The MONTHNAME() function returns the name of the month for a given date. Syntax : MONTHNAME() Example : SELECT MONTHNAME(“2022-03-18”); SELECT MONTHNAME(CURDATE()); Output : MARCH
  • 88. SQL Commands (MySQL Functions – Date & Time Function) DAY() : Return the day of the month for a date. Syntax : DAY() Example : SELECT DAY(“2022-03-18”); SELECT DAY(CURDATE()); Output : 18
  • 89. SQL Commands (MySQL Functions – Date & Time Function) DAYNAME() : Returns the weekday name for a given date. Syntax : DAYNAME() Example : SELECT DAYNAME(“2022-03-18”); SELECT DAYNAME(CURDATE()); Output : FRIDAY
  • 90. SQL Commands (MySQL Functions – Date & Time Function) YEAR() : Returns the year part for a given date. Syntax : YEAR() Example : SELECT YEAR(“1983-02-08”); SELECT YEAR(CURDATE()); Output : 1983, 2022
  • 91. SQL Commands (MySQL Functions – Date & Time Function) DAYOFMONTH() : Returns the day of the month for a given date. Syntax : DAYOFMONTH() Example : SELECT DAYOFMONTH(“2022-03-18”); Output : 18 DAY() and DAYOFMONTY() both returns the Day of a given date, but the difference is DAY() returns the Day of a particular date, while DAYOFMONTH() returns the day in terms of ‘nth ‘ day of the month.
  • 92. SQL Commands (MySQL Functions – Date & Time Function) DAYOFWEEK() : Returns the weekday index for a given date. Syntax : DAYOFWEEK() Example : SELECT DAYOFWEEK(“2022-03-18”); Output : 6 1ST DAY OF WEEK IS SUNDAY.
  • 93. SQL Commands (MySQL Functions – Date & Time Function) DAYOFYEAR() : Returns the day of the year for a given date. Syntax : DAYOFYEAR() Example : SELECT DAYOFYEAR(“2022-03-18”); Output : 77
  • 94. SQL Commands (MySQL Functions – Date & Time Function) NOW() : Returns the current date and time. Syntax : NOW() Example : SELECT NOW(); Output : 2022-03-18 11:50:00
  • 95. SQL Commands (MySQL Functions – Date & Time Function) SYSDATE() : Return the current date and time. Syntax : SYSDATE() Example : SELECT SYSDATE(); Output : 2022-03-18 11:52:50
  • 96. SQL Commands (MySQL Functions – Date & Time Function) Difference between NOW() and SYSDATE() : The output of both of them depends upon the execution time.  NOW() function returns a steady (fix) time that indicates the time at which the particular statement began to execute.  SYSDATE() function returns the accurate time at which the statement executes.
  • 97. SQL Commands (Two Types of SQL Functions) Functions Multiple- row functions Single- row functions String Function Numeric Function Date Function Aggregate Function • Single-row functions operate on single row only and return one result per row. • Multiple-row functions can manipulate groups of rows to give one result per group of rows. These functions are also known as group functions.
  • 98. SQL Commands (MySQL Functions – Aggregate Function) AVG() : The AVG() function returns the average value of a numeric column. Syntax : SELECT AVG (column_name) FROM table_name WHERE condition;
  • 99. SQL Commands (MySQL Functions – Aggregate Function) MAX() : The MAX() function returns the largest value of the selected column. Syntax : SELECT MAX (column_name) FROM table_name WHERE condition;
  • 100. SQL Commands (MySQL Functions – Aggregate Function) Ques : Display the details of the employee, getting MAX Salary. Syntax : SELECT * FROM table_name WHERE column_name=(SELECT MAX (column_name) FROM table_name); Nested Query
  • 101. SQL Commands (MySQL Functions – Aggregate Function) MIN() : The MIN() function returns the smallest value of the selected column. Syntax : SELECT MIN (column_name) FROM table_name WHERE condition;
  • 102. SQL Commands (MySQL Functions – Aggregate Function) Ques : Display the details of the employee, getting MIN Salary. Syntax : SELECT * FROM table_name WHERE column_name=(SELECT MIN (column_name) FROM table_name); Nested Query
  • 103. SQL Commands (MySQL Functions – Aggregate Function) COUNT() : The COUNT() function returns the number of rows that matches a specified criterion. Syntax : SELECT COUNT (column_name) FROM table_name WHERE condition; Returns Nos. of Records/ Rows in a Table. Returns Nos. of Records/ Rows who have salary<100000.
  • 104. SQL Commands (MySQL Functions – Aggregate Function) SUM() : The SUM() function returns the total sum of a numeric column. Syntax : SELECT SUM (column_name) FROM table_name WHERE condition; Sum of Salary of employees, having, Emp_Code BETWEEN 101 AND 103 Sum of Salary of all employees.
  • 105. SQL Commands (ALTERNATE KEY) ALTERNATE KEYS : is a column or group of columns in a table that uniquely identify every row in that table.  A table can have multiple choices for a primary key but only one can be set as the primary key.  All the keys which are not primary key are called an Alternate Key. Example: In this table, StudID, Roll No, Email are qualified to become a primary key. But since StudID is the primary key, Roll No, Email becomes the alternative key.
  • 106. SQL Commands (CANDIDATE KEY) CANDIDATE KEYS : is a set of attributes that uniquely identify tuples in a table. The Primary key should be selected from the candidate keys. Every table must have at least a single candidate key. A table can have multiple candidate keys but only a single primary key. Properties of Candidate key:  It must contain unique values.  Must not contain null values.  Uniquely identify each record in a table.
  • 107. SQL Commands (ADD PRIMARY KEY) ADD PRIMARY KEY : Creates Primary Key constraint on the table. Syntax : mysql> ALTER TABLE table_name ADD PRIMARY KEY (column_name);
  • 108. SQL Commands (REMOVE PRIMARY KEY) DROP PRIMARY KEY : Removes Primary Key constraint from the table. Syntax : mysql> ALTER TABLE table_name DROP PRIMARY KEY;
  • 109. SQL Commands (DELETE RECORD/ROW/TUPLE) DELETE : The DELETE statement is used to delete existing records in a table. Syntax : mysql> DELETE FROM table_name WHERE CONDITION; Be careful when deleting records in a table! If you omit the WHERE clause, all records in the table will be deleted! DELETE FROM STUD; QUERY WILL DELETE ALL THE RECORDS AT ONCE.
  • 110. SQL Commands (GROUP BY) GROUP BY : GROUP BY clause is used to collect data from multiple records and group the result by one or more column.  It is generally used in a SELECT statement.  We can also use some aggregate functions like COUNT, SUM, MIN, MAX, AVG etc. on the grouped column. Syntax : mysql> SELECT column(s), AGGREGATE function FROM table_name WHERE condition GROUP BY column; Continue……
  • 111. SQL Commands (GROUP BY) Query : Count repetitive number of Employees’ names in EMP_NAME column from database table EMP.
  • 112. SQL Commands (ORDER BY) ORDER BY : Using the ORDER BY clause, we can sort the records in ascending or descending order as per our requirement.  The records will be sorted in ascending order whenever the ASC keyword is used with ORDER BY clause.  DESC keyword will sort the records in descending order. If no keyword is specified after the column based on which we have to sort the records, in that case, the sorting will be done by default in the ascending order. Syntax : mysql> SELECT Column_Name(s) FROM Table_Name ORDER BY Column_Name ASC/DESC; Continue……
  • 113. SQL Commands (ORDER BY) Query : Sort the records in the descending order by using sorting on EMP_ID column from the EMP table.
  • 114. SQL Commands (GROUP BY VS. ORDER BY)  The GROUP BY clause is applicable when we want to use aggregate functions to more than one set of rows.  The ORDER BY clause is applicable when we want to get the data obtained by a query in the sorting order.