0% found this document useful (0 votes)
59 views

mysql-ppt

basics of my SQL

Uploaded by

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

mysql-ppt

basics of my SQL

Uploaded by

masterbong00
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 169

®

CAREERER
A
A Warm Welcome To Careerera Family
®

CAREERER
A

DBMS USING MYSQL


WHAT IS DATABASE MANAGEMENT
SYSTEM(DBMS)?
INTRODUCTION TO DBMS

• A Database Management System (DBMS) is defined as the


software system that allows users to define, create, maintain
and control access to the database.
• DBMS makes it possible for end users to create, read, update
and delete data in database.
• A DBMS serves as an interface between an end-user.
• DBMS Examples:- MySQL, Microsoft Access, SQL Server, FileMaker,
Oracle, RDBMS.
WHERE IS DATABASE MANAGEMENT SYSTEM (DBMS) BEING USED?

• Airlines: reservations, schedules, etc


• Telecom: calls made, customer details, network usage, etc
• Universities: registration, results, grades, etc
• Sales: products, purchases, customers, etc
• Banking: all transactions etc
ADVANTAGES OF DBMS

• Better Data Transferring


• Better Data Security
• Better data integration
• Better decision making
• Increased end-user productivity
• Simple
RELATIONAL DATABASE(RDMS)
AN INTRODUCTION TO RELATIONAL DATABASE

• A relational database organizes data into tables which can be


linked—or related—based on data common to each.
• This capability enables you to retrieve an entirely new table
from data in one or more tables with a single query.
• Data is represented in the terms of rows/records and columns.
• In a relational database, each row in the table is a record with a
unique ID called the key.
WHAT IS A TABLE?

• The RDBMS database uses tables to store data. A table is a


collection of related data entries and contains rows and
columns to store data.
WHAT IS A NULL VALUE?

• A NULL value in a table is a value in a field that appears to be


blank, which means a field with a NULL value is a field with
no value.
• It is very important to understand that a NULL value is
different than a zero value or a field that contains spaces. A
field with a NULL value is the one that has been left blank
during a record creation.
WHAT IS SQL?

• SQL is a programming language for Relational Databases. It is


designed over relational algebra and tuple relational calculus.
SQL comes as a package with all major distributions of
RDBMS.

• SQL comprises both data definition and data manipulation


languages. Using the data definition properties of SQL, one
can design and modify database schema, whereas data
manipulation properties allows SQL to store and retrieve data
from Database.
SEMICOLON AFTER SQL STATEMENTS
• Some database systems require a semicolon at the end of each SQL
statement.

• Semicolon is the standard way to separate each SQL statement in


database systems that allow more than one SQL statement to be
executed in the same call to the server.

• In this tutorial, we will use semicolon at the end of each SQL


statement.
ADVANTAGES OF SQL

1.No programming needed


2. High-Speed Query Processing
3. Standardized Language
4. Portability
5. Interactive language
6. More than one Data View
WHAT IS DATA DEFINITION LANGUAGE?

• DDL stands for data definition language.


• DDL Commands deal with the schema, i.e., the table in which our
data isExample:
stored.
CREATE DATABASE DatabaseName;
• All the structural changes such as creation, deletion and
alteration on the table can be carried with the DDL commands
in SQL.
• Commands covered under DDL are:
1. CREATE
2. ALTER
3. DROP
4. TRUNCATE
5. RENAME
1.CREATE Command

In SQL, whenever we wish to create a new database or a table in

a database, we use CREATE command.

Syntax to create a new database:


CREATE DATABASE DatabaseName;

Example to create a new database:


CREATE DATABASE employee;
2.ALTER Command

In SQL, whenever we wish to alter the table structure, we will use the ALTER
command.

Syntax of ALTER command to add a new column:


ALTER TABLE table_name ADD column_name;

Example :
ALTER TABLE table_name DROP COLUMN column_name;
ALTER TABLE table_name RENAME COLUMN old_column_
name TO new_column_name;
3. DROP Command

• DROP command is used to remove or delete the table's records and the
table's structure from the database.

Syntax :
DROP TABLE table_name;

Example :
Write a query to delete the school table from the SCHOOL database.
DROP TABLE school;
4.TRUNCATE Command

A TRUNCATE command is used to delete the table's records, but the table's
structure will remain unaffected in the database.

Syntax:
TRUNCATE TABLE table_name;

Example :
TRUNCATE TABLE t_school;
5.RENAME Command

Rename COMMAND is used to give a new name to an existing table.

Syntax to rename a table:


RENAME TABLE old_table_name TO new_table_name;

Example :
RENAME TABLE student TO top_student;
WHAT IS DATA MANIPULATION LANGUAGE?

• DML stands for Data Manipulation Language. Using DML


commands in SQL, we can make changes in the data present in
tables.
• DML commands in SQL will change the data, such as inserting
new records, deleting or updating existing records from the SQL
tables. We can also retrieve all the data from SQL tables according
to our requirements.
Commands covered under DDL are:
1. INSERT
2. SELECT
3. UPDATE
4. DELETE
1.INSERT Command
• INSERT command is used to insert records in a table. We can
insert a single as well as multiple records for a single table at
the same time.
Syntax:
INSERT INTO table_name VALUES (column_1
value,column_1value);
2.SELECT Command

A SELECT command is used to retrieve the records from the


table. According to our requirements, we can retrieve all the
records or some specific records from the table.

Syntax to retrieve all the records:


SELECT *FROM table_name;
Syntax to retrieve some specific records:
SELECT *FROM table_name WHERE condition;
3.UPDATE Command

UPDATE command works for the values present in the table.Whenever


we wish to update a value for any record present in a table, we will
use the UPDATE command in SQL.

Syntax:
UPDATE table_name SET column_name = value
WHERE condition;
4.DELETE Command

• DELETE command is used to remove records from a table.


Syntax:
DELETE FROM table_name;
WHAT IS DCL Command?
• DCL stands for Data Control Language.
• Whenever we want to control the access to the data present
in SQL tables, we will use DCL commands in SQL. Only the
authorized users can access the data stored in the tables.

There are two types of DCL Commands:-

1. GRANT
Access privileges can be assigned to a user for the databases and
tables using the GRANT command.
2. REVOKE
All the access privileges which are already assigned to the user can
be revoked by using the REVOKE command.
WHAT IS TCL COMMANDS?

• TCL stands for Transaction Control Language. TCL commands


are generally used in transactions.
• Using TCL commands in SQL, we can save our transactions to
the database and roll them back to a specific point in our
transaction. We can also save a particular portion of our
transaction using the SAVEPOINT command.
Commands covered under TCL are:
1. COMMIT:
To save all the operations executed in a particular transaction,
we need to execute a commit command just after the
transaction completion.

2. ROLLBACK
Using the rollback command in SQL, you can roll to the last
saved state of a transaction.
3. SAVEPOINT
Using the SAVEPOINT command, you can assign a name to a
specific part of the transaction.
WHAT IS DATA QUERY LANGUAGE?

1.No programming needed


2. High-Speed Query Processing
3. Standardized Language
4. Portability
5. Interactive language
6. More than one Data View
MYSQL CREATE USER

• The MySQL user is a record in the USER table of the MySQL


server that contains the login information, account privileges,
and the host information for MySQL account. It is essential to
create a user in MySQL for accessing and managing the
databases.
• Create User statement allows us to create a new user account
in the database server. It provides authentication, SSL/TLS,
resource-limit, role, and password management properties
for the new accounts. It also enables us to control the
accounts that should be initially locked or unlocked.
WHY DID USERS REQUIRE IN MYSQL SERVER?

• When the MySQL server installation completes, it has a ROOT user


account only to access and manage the databases. But, sometimes,
you want to give the database access to others without granting
them full control. In that case, you will create a non-root user and
grant them specific privileges to access and modify the database.
• Syntax
The following syntax is used to create a user in the database
server.

CREATE USER [IF NOT EXISTS] account_name IDENTIFIED BY 'password'


;
CREATE USER EXAMPLE

• Step 1: Open the MySQL server by using the mysql client tool.
• Step 2: Enter the password for the account and press Enter.
Enter Password: ****
• Step 3: Execute the following command to show all users in the
current MySQL server.
MySQL> select user from MySQL. User;
GRANT PRIVILEGES TO THE MYSQL NEW USER

MySQL server provides multiple types of privileges to a new user account.


Some of the most commonly used privileges are given below:
1. ALL PRIVILEGES: It permits all privileges to a new user account.
2. CREATE: It enables the user account to create databases and tables.
3. DROP: It enables the user account to drop databases and tables.
4. DELETE: It enables the user account to delete rows from a specific table.
5. INSERT: It enables the user account to insert rows into a specific table.
6. SELECT: It enables the user account to read a database.
7. UPDATE: It enables the user account to update table rows.
GRANT PRIVILEGES TO THE MYSQL NEW
USER
DROP USER
• The Drop User statement allows us to remove one or more user
accounts and their privileges from the database server. If the
account does not exist in the database server, it gives an error.
• If you want to use the Drop User statement, it is required to
have a global privilege of Create User statement or
the DELETE privilege for the MySQL system schema.
Syntax
• The following syntax is used to delete the user accounts from
the database server completely.
DROP USER 'account_name';
DROP USER EXAMPLE

• The following are the step required to delete an existing user


from the MySQL server database.
• Step 1: Open the MySQL server by using the mysql client
tool.
• Step 2: Enter the password for the account and press Enter.
Enter Password: ********
• Step 3: Execute the following command to show all users in
the current MySQL server.
mysql> select user from MySQL.User;
SHOW USERS/LIST ALL USERS
• In that case, we need to see the list of all user's
accounts in a database. Most times, we assume that
there is a SHOW USERS command similar to SHOW
DATABASES, SHOW TABLES, etc. for displaying the list of
all users available in the database server.
• Unfortunately, MySQL database does not have a SHOW
USERS command to display the list of all users in the
MySQL server. We can use the following query to see
the list of all user in the database server:
-Select user from mysql.user;
SHOW USERS/LIST ALL USERS
• we want to see more information on the user table,
SHOW USERS/LIST ALL USERS
• To get the selected information like as hostname, password
expiration status, and account locking, execute the query as
below:
-SELECT user, host FROM user;
SHOW CURRENT USER
• We can get information of the current user by using
the user() or current_user() function
SHOW CURRENT LOGGED USER

-
mysql> SELECT user, host, db, command FROM information_schema.processlist;
CHANGE USER PASSWORD
• To change the password of any user account, you must have to
keep this information in your mind:
-The details of the user account that you want to change.
-An application used by the user whose password you want
to change. If you reset the user account password without
changing an application connection string, then the application
cannot connect with the database server.
• MySQL allows us to change the user account password in three
different ways, which are given below:
1. UPDATE Statement
2. SET PASSWORD Statement
CHANGE USER ACCOUNT PASSWORD USING THE UPDATE STATEMENT

1. USE mysql;
2. UPDATE user SET password = PASSWORD('jtp12345') WHERE
user = 'peter' AND host = 'localhost';
3. FLUSH PRIVILEGES;
CHANGE USER ACCOUNT PASSWORD USING SET PASSWORD STATEMENT

1. USE mysql;
2. UPDATE user SET password = PASSWORD('jtp12345') WHERE
user = 'peter' AND host = 'localhost';
3. FLUSH PRIVILEGES;
CREATE DATABASE

• MySQL implements a database as a directory that stores all


files in the form of a table.
• It allows us to create a database mainly in two ways:
1.MySQL Command Line Client
We can create a new database in MySQL by using the CREATE
DATABASE statement with the below syntax:
CREATE DATABASE [IF NOT EXISTS] database_name
[CHARACTER SET charset_name]
[COLLATE collation_name];
2. MySQL Workbench
2.Using Workbench
PARAMETER EXPLANATION
The parameter descriptions of the
above syntax are as follows:

Parameter Description

database_name It is the name of a new database


that should be unique in the
MySQL server instance. The IF
NOT EXIST clause avoids an
error when we create a database
that already exists.
charset_name It is optional. It is the name of the
character set to store every
character in a string. MySQL
database server supports many
character sets. If we do not
provide this in the statement,
MySQL takes the default
character set.
collation_name It is optional that compares
characters in a particular
character set.
CREATE DATABASE
• CREATE DATABASE employee;
• Show databases;
SELECT DATABASE
• SELECT Database is used in MySQL to select a particular
database to work with. This query is used when multiple
databases are available with MySQL Server.
• You can use SQL command USE to select a particular
database.
• Syntax:
USE database_name;
For example;
DROP DATABASE

• We can drop/delete/remove a MySQL database quickly with


the MySQL DROP DATABASE command. It will delete the
database along with all the tables, indexes, and constraints
permanently.
• Therefore, we should have to be very careful while
removing the database in MySQL because we will lose all
the data available in the database.
• If the database is not available in the MySQL server, the
DROP DATABASE statement throws an error.
DROP DATABASE
• We can drop an existing database in MySQL by using the
DROP DATABASE statement with the below syntax:
1. DROP DATABASE [IF EXISTS] database_name;
• In MySQL, we can also use the below syntax for deleting the
database. It is because the schema is the synonym for the
database, so we can use them interchangeably.
1. DROP SCHEMA [IF EXISTS] database_name;
DROP DATABASE
Parameter Explanation
The parameter descriptions of the above syntax are as
follows:
Parameter Description
database_name It is the name of an
existing database that we
want to delete from the
server. It should be unique
in the MySQL server
instance.
IF EXISTS It is optional. It is used to
prevent from getting an
error while removing a
database that does not
exist.
DROP DATABASE
• SHOW DATABASES;

• DROP DATABASE careerera;


For example:
CREATE TABLE

• A table is used to organize data in the form of rows and


columns and used for both storing and displaying records in
the structure format. It is similar to worksheets in the
spreadsheet application.
• A table creation command requires three things:
i. Name of the table
ii. Names of fields
iii. Definitions for each field
CREATE TABLE
• MySQL allows us to create a table into the database by using
the CREATE TABLE command.
• SYNTAX:
CREATE TABLE [IF NOT EXISTS] table_name(
column_definition1,
column_definition2,
........,
table_constraints
);
CREATE TABLE
• CREATE TABLE employees (
NAME VARCHAR (20),
ID VARCHAR(15),
ADDRESS VARCHAR(50)
);
For example:
CREATE TABLE

• SHOW TABLES;
• DESCRIBE employee;
ALTER TABLE

• MySQL ALTER statement is used when you want to change


the name of your table or any table field. It is also used to
add or delete an existing column in a table.
• The ALTER statement is always used with "ADD", "DROP" and
"MODIFY" commands according to the situation.
Syntax for adding single column:
ALTER TABLE table_name
ADD new_column_name column_definition
[ FIRST | AFTER column_name ];
ADD MULTIPLE COLUMNS IN THE TABLE

• SYNTAX:
ALTER TABLE table_name
ADD new_column_name column_definition
[ FIRST | AFTER column_name ],
ADD new_column_name column_definition
[ FIRST | AFTER column_name ], ... ;
For example:
MODIFY COLUMN IN THE TABLE

• The MODIFY command is used to change the column


definition of the table.
• SYNTAX:
1. ALTER TABLE table_name
2. MODIFY column_name column_definition
3. [ FIRST | AFTER column_name ];
• For example:-
DROP COLUMN IN TABLE

• SYNTAX:
1. ALTER TABLE table_name
2. DROP COLUMN column_name;
• For example:-
RENAME COLUMN IN TABLE
• SYNTAX:
1. ALTER TABLE table_name
2. CHANGE COLUMN old_name new_name
3. column_definition
4. [ FIRST | AFTER column_name ]
• For Example:-
RENAME TABLE
• SYNTAX:
1. ALTER TABLE table_name
2. RENAME TO new_table_name;
For example:-
TRUNCATE TABLE

• The TRUNCATE statement in MySQL removes the complete


data without removing its structure. It is a part of DDL or
data definition language command.
• Generally, we use this command when we want to delete an
entire data from a table without removing the table
structure.
SYNTAX:-
1.TRUNCATE [TABLE] table_name;
TRUNCATE TABLE
•We cannot use the WHERE clause with this command so that
filtering of records is not possible.

•We cannot rollback the deleted data after executing this


command because the log is not maintained while performing
this operation.

•We cannot use the truncate statement when a table is


referenced by a foreign key or participates in an indexed view.

•The TRUNCATE command doesn't fire


DELETE triggers associated with the table that is being truncated
because it does not operate on individual rows.
DESCRIBE TABLE
• DESCRIBE means to show the information in detail.
• DESCRIBE command to show the structure of our table, such
as column names, constraints on column names, etc.
The DESC command is a short form of the DESCRIBE
command. Both DESCRIBE and DESC command are equivalent
and case sensitive.
• Syntax
{DESCRIBE | DESC} table_name;
For example:-
DROP TABLE
• MYSQL uses a Drop Table statement to delete the existing table.
This statement removes the complete data of a table along with
the whole structure or definition permanently from the database.
Syntax:
DROP TABLE table_name;
OR,
DROP TABLE schema_name.table_name;
For example:-
CONSTRAINTS

• SQL constraints are used to specify rules for the data in a table.
• Constraints are used to limit the type of data that can go into a table.
This ensures the accuracy and reliability of the data in the table. If
there is any violation between the constraint and the data action, the
action is aborted.
• Constraints can be column level or table level. Column level
constraints apply to a column, and table level constraints apply to
the whole table.
CONSTRAINTS
The following are the most common constraints used in the
MySQL:

• NOT NULL
• CHECK
• DEFAULT
• PRIMARY KEY
• AUTO_INCREMENT
• UNIQUE
• INDEX
• ENUM
• FOREIGN KEY
NOT NULL CONSTRAINT
• By default, a column can hold NULL values.
• This constraint specifies that the column cannot have NULL
or empty values. The below statement creates a table with
NOT NULL constraint.

NOT NULL on CREATE TABLE:


UNIQUE CONSTRAINT
• The UNIQUE constraint ensures that all values in a column are
different.
• Both the UNIQUE and PRIMARY KEY constraints provide a
guarantee for uniqueness for a column or set of columns.
• A PRIMARY KEY constraint automatically has
a UNIQUE constraint.
• However, you can have many UNIQUE constraints per table,
but only one PRIMARY KEY constraint per table.
UNIQUE CONSTRAINT ON CREATE TABLE:
PRIMARY KEY CONSTRAINT

• The PRIMARY KEY constraint uniquely identifies each record


in a table.
• Primary keys must contain UNIQUE values, and cannot
contain NULL values.
• A table can have only ONE primary key; and in the table, this
primary key can consist of single or multiple columns (fields).
PRIMARY KEY of CREATE TABLE:
PRIMARY KEY CONSTRAINT

• PRIMARY KEY on ALTER TABLE : To create a PRIMARY


KEY constraint on the "ID" column when the table is already
created ;

• DROP A PRIMARY KEY CONSTRAINT


To drop a PRIMARY KEY constraint, use the following SQL:
FOREIGN KEY CONSTRAINT

• The FOREIGN KEY constraint is used to prevent actions that


would destroy links between tables.

• 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.
CHECK CONSTRAINT
• The following SQL creates a CHECK constraint on the "Age"
column when the "Persons" table is created.
The CHECK constraint ensures that the age of a person must
be 18, or older:
CHECK CONSTRAINT
CHECK ON ALTER TABLE
To create a CHECK constraint on the "Age" column when the
table is already created, use the following SQL:
ALTER TABLE Persons
ADD CHECK (Age>=18);
DEFAULT CONSTRAINT
• The DEFAULT constraint is used to set a default value for a
column.
• The default value will be added to all new records, if no other
value is specified
DEFAULT ON CREATE TABLE:
The following SQL sets a DEFAULT value for the "City" column when the
"Persons" table is created:
CREATE INDEX STATEMENT
The CREATE INDEX statement is used to create indexes in
tables.
Indexes are used to retrieve data from the database more
quickly than otherwise. The users cannot see the indexes, they
are just used to speed up searches/queries.

CREATE INDEX Syntax


Creates an index on a table. Duplicate values are allowed:
CREATE INDEX index_name
ON table_name (column1, column2, ...);

CREATE UNIQUE INDEX Syntax


Creates a unique index on a table. Duplicate values are not
allowed:
CREATE UNIQUE INDEX index_name
ON table_name (column1, column2, ...);
CREATE INDEX STATEMENT
Example :-

DROP INDEX Statement


The DROP INDEX statement is used to delete an index in a
table.
ALTER TABLE table_name
DROP INDEX index_name;
INSERT STATEMENT
• MySQL INSERT statement is used to store or add data in
MySQL table within the database.
• We can perform insertion of records in two ways using a
single query in MySQL:
1. Insert record in a single row
2. Insert record in multiple rows
INSERT RECORD IN A SINGLE ROW
Syntax:
INSERT INTO table_name ( field1, field2,...fieldN )
VALUES( value1, value2,...valueN );
INSERT STATEMENT

• If we want to store records without giving all fields, we use


the following partial field statements. In such case, it is
mandatory to specify field names.
SELECT STATEMENT
• The SELECT statement in MySQL is used to fetch data from
one or more tables. We can retrieve records of all fields or
specified fields that match specified criteria using this
statement.

• SELECT STATEMENT SYNTAX


SELECT field_name1, field_name 2,... field_nameN
FROM table_name1, table_name2...
[WHERE condition]
[GROUP BY field_name(s)]
[HAVING condition]
[ORDER BY field_name(s)]
[OFFSET M ][LIMIT N];
PARAMETER EXPLANATION
Parameter Name Descriptions
field_name(s) or * It is used to specify one or more columns to returns in the result set.
The asterisk (*) returns all fields of a table.

table_name(s) It is the name of tables from which we want to fetch data.

WHERE It is an optional clause. It specifies the condition that returned the


matched records in the result set.

GROUP BY It is optional. It collects data from multiple records and grouped them
by one or more columns.

HAVING It is optional. It works with the GROUP BY clause and returns only
those rows whose condition is TRUE.

ORDER BY It is optional. It is used for sorting the records in the result set.

OFFSET It is optional. It specifies to which row returns first. By default, It starts


with zero.
LIMIT It is optional. It is used to limit the number of returned records in the
result set.
SELECT STATEMENT

• If we want to retrieve a single column from the table, we


need to execute the below query:
SELECT STATEMENT

• If we want to query multiple columns from the table, we


need to execute the below query:
SELECT STATEMENT

• If we want to fetch data from all columns of the table, we


need to use all column's names with the select statement.
Specifying all column names is not convenient to the user, so
MySQL uses an asterisk (*) to retrieve all column data as
follows:
WHERE CLAUSE
• MySQL WHERE Clause is used with SELECT, INSERT, UPDATE and
DELETE clause to filter the results. It specifies a specific position
where you have to do the operation.
• Syntax:
WHERE conditions;
Parameter:
conditions: It specifies the conditions that must be fulfilled for
records to be selected.
WHERE CLAUSE WITH SINGLE CONDITION

SELECT *
FROM EMPLOYEE
WHERE NAME = ’PETER';
WHERE CLAUSE WITH AND CONDITION

• In this example, we are retrieving data from the table


"officers" with AND condition.
SELECT *
FROM officers
WHERE NAME = ’PETER'
AND WORKING_HOURS>10;
WHERE CLAUSE WITH OR CONDITION

SELECT *
FROM officers
WHERE WORKING_DATE =“2020-10-04”
OR WORKING_HOURS >=10;
WHERE CLAUSE WITH COMBINATION OF AND & OR
CONDITIONS

SELECT *
FROM officers
WHERE (OCCUPATION = ’ACTOR' AND WORKING_DATE = ’2020-10-04')
OR (WORKING_HOURS>= 13);
ORDER BY CLAUSE

• The MYSQL ORDER BY Clause is used to sort the records in


ascending or descending order.
Syntax:
SELECT expressions
FROM tables
[WHERE conditions]
ORDER BY expression [ ASC | DESC ];
ORDER BY CLAUSE

Parameters
1. expressions: It specifies the columns that you want to retrieve.
2. tables: It specifies the tables, from where you want to retrieve
records. There must be at least one table listed in the FROM
clause.
3. WHERE conditions: It is optional. It specifies conditions that
must be fulfilled for the records to be selected.
4. ASC: It is optional. It sorts the result set in ascending order by
expression (default, if no modifier is provider).
5. DESC: It is also optional. It sorts the result set in descending
order by expression.
ORDER BY: WITHOUT USING ASC/DESC
ATTRIBUTE
• If you use MySQL ORDER BY clause without specifying the ASC
and DESC modifier then by default you will get the result in
ascending order.
syntax
SELECT *
FROM officers
WHERE address = 'Lucknow'
ORDER BY officer_name;
ORDER BY: WITH ASC ATTRIBUTE

• Example to retrieve the data in ascending order.


SELECT *
FROM EMPLOYEE
WHERE WORKING_HOURS >=9
ORDER BY NAME ASC;
ORDER BY: WITH DESC ATTRIBUTE

SELECT *
FROM EMPLOYEE
WHERE WORKING_DATE= ’2020-10-04'
ORDER BY NAME DESC;
ORDER BY: USING BOTH ASC AND DESC ATTRIBUTES

SELECT NAME,OCCUPATION
FROM EMPLOYEE
WHERE WORKING_HOURS >10
ORDER BY NAME DESC, OCCUPATION ASC;
GROUP BY CLAUSE
• The 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.
• You can also use some aggregate functions like COUNT, SUM,
MIN, MAX, AVG etc. on the grouped column.
• Syntax:
SELECT expression1, expression2, ... expression_n,
aggregate_function (expression)
FROM tables
[WHERE conditions]
GROUP BY expression1, expression2, ... expression_n;
GROUP BY CLAUSE WITH COUNT FUNCTION

• Let's count repetitive number of WORKING_HOURS in the column


WORKING_HOURS.
SELECT WORKING_HOURS, COUNT(*)
FROM EMPLOYEE
GROUP BY WORKING_HOURS;
GROUP BY CLAUSE WITH SUM FUNCTION

• Now, the following query will GROUP BY the example using the
SUM function and return the emp_name and total working hours
of each employee.
SELECT emp_name, SUM(working_hours) AS "Total working hours"
FROM employees
GROUP BY emp_name;
GROUP BY CLAUSE WITH MIN FUNCTION

The following example specifies the minimum working hours of


the employees form the table "employees".
Syntax:
SELECT emp_name, MIN(working_hours) AS "Minimum working hour"
FROM employees
GROUP BY emp_name;
GROUP BY CLAUSE WITH MIN FUNCTION

• The following example specifies the minimum working hours of the


employees form the table "employees".
• Execute the following query:
SELECT emp_name, MIN(working_hours) AS "Minimum working hour"
FROM employees
GROUP BY emp_name;
GROUP BY CLAUSE WITH MAX FUNCTION

• The following example specifies the maximum working hours of the


employees form the table "employees".
SELECT emp_name, MAX (working_hours) AS "Minimum working hour"
FROM employees
GROUP BY emp_name;
GROUP BY CLAUSE WITH AVG FUNCTION
• The following example specifies the average working hours of
the employees form the table "employees".
• Syntax:
SELECT emp_name, AVG(working_hours) AS
"Average working hour"
FROM employees
GROUP BY emp_name;
JOINS

JOINS are used with SELECT statement. It is used to retrieve


data
from multiple tables. It is performed whenever you need to
fetch
records from two or more tables.
• There are three types of MYSQL joins:
1. MySQL INNER JOIN (or sometimes called simple join)
2. MySQL LEFT OUTER JOIN (or sometimes called LEFT JOIN)
3. MySQL RIGHT OUTER JOIN (or sometimes called RIGHT
JOIN)
INNER JOIN (SIMPLE JOIN)

Inner Join Syntax:


• The Inner Join keyword is used with the SELECT
statement and must be written after the FROM clause.
SELECT columns
FROM table1
INNER JOIN table2 ON condition1
INNER JOIN table3 ON condition2 ...;
INNER JOIN (SIMPLE JOIN)
Example:
Let us first create two tables "students" and "technologies" that
contains the following data:
INNER JOIN (SIMPLE JOIN)

To select records from both tables, execute the following query:


SELECT STUDENT.STUDENT_FNAME, STUDENT.STUDENT_LNAME,
STUDENT.CITY, TECHNOLOGY.TECHNOLOGY
FROM STUDENT
INNER JOIN TECHNOLOGY
ON STUDENTS.STUDENT_ID = TECHNOLOGY.TECH_ID;
INNER JOIN WITH GROUP BY CLAUSE

• The Inner Join can also be used with the GROUP BY clause.
SELECT STUDENTS.STUDENT_ID, TECHNOLOGY.INST_NAME, STUDENTS.CIT
Y, TECHNOLOGY.TECHNOLOGY
FROM STUDENT
INNER JOIN TECHNOLOGY
ON STUDENTS.STUDENT_ID = TECHNOLOGY.TECH_ID GROUP BY INST_NA
ME;
INNER JOIN WITH WHERE CLAUSE

• The WHERE clause enables you to return the filter result. The
following example illustrates this clause with Inner Join:
SELECT TECH_ID, INST_NAME, CITY, TECHNOLOGY
FROM STUDENTS
INNER JOIN TECHNOLOGY
USING (STUDENT_ID) WHERE TECHNOLOGY = "JAVA";
LEFT JOIN
• The Left Join in MySQL is used to query records from multiple tables.
This clause is similar to the Inner Join clause that can be used with a
SELECT statement immediately after the FROM keyword.
• When we use the Left Join clause, it will return all the records from
the first (left-side) table, even no matching records found from the
second (right side) table. If it will not find any matches record from
the right side table, then returns null.
• We can understand it with the following visual representation where
Left Joins returns all records from the left-hand table and only the
matching records from the right side table:
LEFT JOIN

LEFT JOIN Syntax


• The following syntax explains the Left Join clause to
join the two or more tables:
SELECT columns
FROM table1
LEFT [OUTER] JOIN table2
ON Join_Condition;
LEFT JOIN

• LEFT JOIN Example


• LEFT JOIN clause for joining two tables
• we are going to create two tables "customers" and
"orders" that contains the following data:
LEFT JOIN WITH GROUP BY CLAUSE

The Left Join can also be used with the GROUP BY clause. The following
statement returns customer id, customer name, qualification, price,
and date using the Left Join clause with the GROUP BY clause.
RIGHT JOIN
• The Right Join is used to joins two or more tables and returns all rows
from the right-hand table, and only those results from the other table
that fulfilled the join condition.
• If it finds unmatched records from the left side table, it returns Null
value. It is similar to the Left Join, except it gives the reverse result of
the join tables. It is also known as Right Outer Join. So, Outer is the
optional clause used with the Right Join.
• We can understand it with the following visual representation where
Right Outer Join returns all records from the left-hand table and only
the matching records from the other table:
RIGHT JOIN

• RIGHT JOIN Syntax


SELECT column_list
FROM Table1
RIGHT [OUTER] JOIN Table2
ON join_condition;
RIGHT JOIN

RIGHT JOIN clause for joining two tables


• Here, we are going to create two tables "customers" and
"orders" that contains the following data:
RIGHT JOIN
RIGHT JOIN clause for joining two tables
RIGHT JOIN WITH WHERE CLAUSE

• MySQL uses the WHERE clause to provide the filter result from
the table. The following example illustrates this with the Right
Join clause:
CROSS JOIN
• CROSS JOIN is used to combine all possibilities of the two or more
tables and returns the result that contains every row from all
contributing tables.
• The CROSS JOIN is also known as CARTESIAN JOIN, which provides
the Cartesian product of all associated tables. The Cartesian product
can be explained as all rows present in the first table multiplied by
all rows present in the second table. It is similar to the Inner Join,
where the join condition is not available with this clause.
• We can understand it with the following visual representation where
CROSS JOIN returns all the records from table1 and table2, and each
row is the combination of rows of both tables.
CROSS JOIN
• The CROSS JOIN keyword is always used with the SELECT
statement and must be written after the FROM clause.

CROSS JOIN Syntax:


1. SELECT column-lists
2. FROM table1
3. CROSS JOIN table2;
CROSS JOIN

• CROSS JOIN clause for joining two tables


• Here,we are going to create two
tables "customers" and "contacts" that contains the following
data:
CROSS JOIN
• CROSS JOIN clause for joining two tables
SELF JOIN

• A SELF JOIN is a join that is used to join a table with itself.


• There is a need to combine data with other data in the same
table itself.
SELF JOIN Syntax:
SELECT s1.col_name, s2.col_name...
FROM table1 s1, table1 s2
WHERE s1.common_col_name = s2.common_col_name;
SELF JOIN
Example:
create a table "student" in a database that contains the following
data:
UNION OPERATOR

• The UNION operator is used to combine the result-set of


two or more SELECT statements.
1. Every SELECT statement within UNION must have the
same number of columns
2. The columns must also have similar data types
3. The columns in every SELECT statement must also be in
the same order

UNION Syntax:
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
UNION OPERATOR

UNION ALL Syntax:


The UNION operator selects only distinct values by
default. To allow duplicate values, use UNION ALL:
SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;
UNION OPERATOR
• UNION Example
• The following SQL statement returns the cities (only distinct
values) from both the "Customers" and the "Suppliers" table:
UNION OPERATOR

Example:

Note: If some customers or suppliers have the same city, each


city will only be listed once, because UNION selects only
distinct values. Use UNION ALL to also select duplicate values!
UNION OPERATOR

UNION ALL Example:


• The following SQL statement returns the cities (duplicate values
also) from both the "Customers" and the "Suppliers" table:
UNION OPERATOR
UNION With WHERE:
The following SQL statement returns the German cities (only
distinct values) from both the "Customers" and the "Suppliers“
table:
UNION OPERATOR
UNION ALL With WHERE:
The following SQL statement returns the German cities
(duplicate values also) from both the "Customers" and the
"Suppliers" table:
AGGREGATE FUNCTIONS
• MySQL's aggregate function is used to perform calculations
on multiple values and return the result in a single value like
the average of all values, the sum of all values, and maximum
& minimum value among certain groups of values.
• We mostly use the aggregate functions with
SELECT statements in the data query languages.
Syntax:
The following are the syntax to use aggregate functions
in MySQL:
function_name (DISTINCT | ALL expression)
AGGREGATE FUNCTIONS
There are various aggregate functions available in MySQL. Some
of the most commonly used aggregate functions are
summarised in the below table:
COUNT() FUNCTION
• MySQL count() function returns the total number of values in the
expression. This function produces all rows or only some rows of the
table based on a specified condition, and its return type is BIGINT.
• It returns zero if it does not find any matching rows. It can work with
both numeric and non-numeric data types.
• Suppose we want to get the total number of employees in the
employee table, we need to use the count() function as shown in the
following query:
• Syntax:
SELECT COUNT(name) FROM employee;
COUNT() FUNCTION
Example
SUM() FUNCTION
• The MySQL sum() function returns the total summed (non-
NULL) value of an expression. It returns NULL if the result set
does not have any rows. It works with numeric data type
only.
• Suppose we want to calculate the total number of working
hours of all employees in the table, we need to use the sum()
function as shown in the following query:
SYNTAX:
SELECT SUM(working_hours) AS "Total working hours"
FROM employee;
AVG() FUNCTION
• MySQL AVG() function calculates the average of the
values specified in the column. Similar to the SUM() function,
it also works with numeric data type only.
• Suppose we want to get the average working hours of all
employees in the table, we need to use the AVG() function as
shown in the following query:
Syntax:
SELECT AVG(working_hours) AS "Average working hour
" FROM employee;
MIN() FUNCTION
• MySQL MIN() function returns the minimum (lowest) value of
the specified column. It also works with numeric data type only.
• Suppose we want to get minimum working hours of an
employee available in the table, we need to use the MIN()
function as shown in the following query:
Syntax:
SELECT MIN(working_hours) AS Minimum_working_hours
FROM employee;
MAX() FUNCTION
• MySQL MAX() function returns the maximum (highest)
value of the specified column. It also works with numeric
data type only.
• Suppose we want to get maximum working hours of an
employee available in the table, we need to use the MAX()
function as shown in the following query:
Syntax:
SELECT MAX(working_hours) AS Maximum_working_hours FR
OM employee;
FIRST() FUNCTION
• This function returns the first value of the specified column.
To get the first value of the column, we must have to use
the LIMIT clause. It is because FIRST() function only supports
in MS Access.
• Suppose we want to get the first working date of an
employee available in the table, we need to use the following
query:
Syntax:
SELECT working_date FROM employee LIMIT 1;
LAST() FUNCTION
• This function returns the last value of the specified column. To get
the last value of the column, we must have to use the ORDER BY
and LIMIT clause. It is because the LAST() function only supports
in MS Access.
• Suppose we want to get the last working hour of an employee
available in the table, we need to use the following query:
Syntax:
SELECT working_hours FROM employee ORDER BY name
DESC LIMIT 1;
SUBQUERY
• A subquery in MySQL is a query, which is nested into another
SQL query and embedded with SELECT, INSERT, UPDATE or
DELETE statement along with the various operators.
• We can also nest the subquery with another subquery. A
subquery is known as the inner query, and the query that
contains subquery is known as the outer query.

• The inner query executed first gives the result to the outer
query, and then the main/outer query will be
performed. MySQL allows us to use subquery anywhere, but it
must be closed within parenthesis.
SUBQUERY
The following are the rules to use subqueries:
• Subqueries should always use in parentheses.
• If the main query does not have multiple columns for
subquery, then a subquery can have only one column in the
SELECT command.
• We can use various comparison operators with the subquery,
such as >, <, =, IN, ANY, SOME, and ALL. A multiple-row
operator is very useful when the subquery returns more than
one row.
• We cannot use the ORDER BY clause in a subquery, although it
can be used inside the main query.
• If we use a subquery in a set function, it cannot be
immediately enclosed in a set function.
SUBQUERY
The following are the advantages of using subqueries:
• The subqueries make the queries in a structured form that
allows us to isolate each part of a statement.
• The subqueries provide alternative ways to query the data from
the table; otherwise, we need to use complex joins and unions.
• The subqueries are more readable than complex join or union
statements.
SUBQUERY SYNTAX:
1.SELECT column_list (s) FROM table_name
2.WHERE column_name OPERATOR
3.SELECT column_list (s) FROM table_name [WHERE])
SUBQUERY
Subquery Example:
Suppose we have a table named “customer" that contains the
following data:
SUBQUERY

• Following is a simple SQL statement that returns


the employee detail whose id matches in a subquery:
SUBQUERY WITH COMPARISON OPERATOR
• A comparison operator is an operator used to compare values
and returns the result, either true or false. The following
comparison operators are used in MySQL <, >, =, <>, <=>, etc.
• Following is a simple SQL statement that returns
the customer detail whose income is more than 20000 with
the help of subquery:
SUBQUERY WITH COMPARISON OPERATOR

• find employee details with maximum income using a


subquery.
SUBQUERY WITH IN OR NOT-IN OPERATOR
• If the subquery produces more than one value, we need to
use the IN or NOT IN operator with the WHERE clause.
• Suppose we have a table
named "Student1" and "Student2" that contains the
following data:
SUBQUERY WITH IN OR NOT-IN OPERATOR

• The following subquery with NOT IN operator returns


the student1 detail who does not belong to Los Angeles
City from both tables as follows:
SUBQUERY IN THE FROM CLAUSE
• If we use a subquery in the FROM clause, MySQL will return
the output from a subquery is used as a temporary table. We
called this table as a derived table, inline views, or
materialized subquery.
• The following subquery returns the maximum, minimum, and
average number of items in the order table:
CORRELATED SUBQUERIES
• A correlated subquery in MySQL is a subquery that depends on the outer
query.
• It uses the data from the outer query or contains a reference to a parent
query that also appears in the outer query. MySQL evaluates it once from
each row in the outer query.
EXAMPLE:
We select an customer name and city whose income is higher
than the average income of all employees in each city.
SUBQUERIES WITH EXISTS OR NOT EXISTS

• The EXISTS operator is a Boolean operator that returns either


true or false result. It is used with a subquery and checks the
existence of data in a subquery.
• If a subquery returns any record at all, this operator returns
true. Otherwise, it will return false.
• The NOT EXISTS operator used for negation that gives true
value when the subquery does not return any row.
Otherwise, it returns false. Both EXISTS and NOT EXISTS used
with correlated subqueries.
SUBQUERIES WITH EXISTS OR NOT EXISTS

• Suppose we have a table customer and order that contains


the data as follows:
SUBQUERIES WITH EXISTS OR NOT EXISTS

• The below SQL statements uses EXISTS operator to find the


name, occupation, and Qualification of the customer who has
placed at least one order.
SUBQUERIES WITH EXISTS OR NOT EXISTS

• This statement uses NOT EXISTS operator that returns the


customer details who have not placed an order.
SUBQUERIES WITH ALL, ANY, AND SOME

• We can use a subquery which is followed by the keyword ALL,


ANY, or SOME after a comparison operator. The following are
the syntax to use subqueries with ALL, ANY, or SOME:
1. operand comparison_operator ANY (subquery)
2. operand comparison_operator ALL (subquery)
3. operand comparison_operator SOME (subquery)
• The ALL keyword compares values with the value returned by
a subquery. Therefore, it returns TRUE if the comparison is
TRUE for ALL of the values returned by a subquery.
• The ANY keyword returns TRUE if the comparison is TRUE for
ANY of the values returned by a subquery. The ANY and
SOME keywords are the same because they are the alias of
each other.
SUBQUERIES WITH ALL, ANY, AND SOME

• ANY OPERATOR
SUBQUERIES WITH ALL, ANY, AND SOME

• ALL OPERATOR
WHAT IS ETL?
ETL, which stands for extract, transform and load, is a data
integration process that combines data from multiple
data sources into a single, consistent data store that is
loaded into a data warehouse or other target system.
INTRODUCTION TO ETL

• ETL is a type of data integration that refers to the three steps


(extract, transform, load) used to blend data from multiple
sources. It's often used to build a data warehouse .
• During this process, data is taken (extracted) from a source
system, converted (transformed) into a format that can be
analyzed, and stored (loaded) into a data warehouse or other
system. Extract, load, transform (ELT) is an alternate but
related approach designed to push processing down to the
database for improved performance.
WHY ETL IS IMPORTANT ?
• When used with an enterprise data warehouse (data at rest), ETL
provides deep historical context for the business.
• By providing a consolidated view, ETL makes it easier for business
users to analyze and report on data relevant to their initiatives.
• ETL can improve data professionals’ productivity because it
codifies and reuses processes that move data without requiring
technical skills to write code or scripts.
• ETL has evolved over time to support emerging integration
requirements for things like streaming data.
• Organizations need both ETL and ELT to bring data together,
maintain accuracy and provide the auditing typically required for
data warehousing, reporting and analytics.
HOW ETL WORKS

1. Extract
During data extraction, raw data is copied or exported from
source locations to a staging area. Data management teams
can extract data from a variety of data sources, which can be
structured or unstructured.
Those sources include but are not limited to:
• SQL or NoSQL servers
• CRM and ERP systems
• Flat files
• Email
• Web pages
HOW ETL WORKS
2. Transform
In the staging area, the raw data undergoes data processing. Here, the data is
transformed and consolidated for its intended analytical use case.
This phase can involve the following tasks:
• Filtering, cleansing, de-duplicating, validating, and authenticating the data.
• Performing calculations, translations, or summarizations based on the raw
data. This can include changing row and column headers for consistency,
converting currencies or other units of measurement, editing text strings, and
more.
• Conducting audits to ensure data quality and compliance
• Removing, encrypting, or protecting data governed by industry or
governmental regulators
• Formatting the data into tables or joined tables to match the schema of the
target data warehouse.
HOW ETL WORKS

3. Load
In this last step, the transformed data is moved from the staging
area into a target data warehouse.
•Typically, this involves an initial loading of all data, followed by
periodic loading of incremental data changes and, less often,
full refreshes to erase and replace data in the warehouse.
• For most organizations that use ETL, the process is automated,
well-defined, continuous and batch-driven.
•Typically, ETL takes place during off-hours when traffic on the
source systems and the data warehouse is at its lowest.
THANK YOU !!!
(USA) (INDIA)
2-Industrial Park Drive, E-
Waldorf, MD, 20602, B-44, Sector-
United States 59, Noida
Uttar
(USA) Pradesh
+1-844-889-4054 201301
(Singapore)
3 Temasek Avenue, Singapore (INDIA)
039190 +91-92-5000-
[email protected] 4000
www.careerera.com

You might also like