SlideShare une entreprise Scribd logo
1  sur  54
Getting Started With
MySQL I
What is Database?
• A database is a structured collection of data. Here are some
typical examples of databases:
• An online store database that stores product details, customer
details and orders
• A database for a web forum that stores members, forums, topics
and posts
• A database for a blog system, such as WordPress, that stores
users, blog posts, categories, tags, and comments
2
What is Relational Database Management
System?
A Relational DataBase Management System (RDBMS) is a software that:
• Enables you to implement a database with tables, columns and indexes.
• Guarantees the Referential Integrity between rows of various tables.
• Updates the indexes automatically.
• Interprets an SQL query and extracts information from various tables
based on SQL query
We use Relational Database Management Systems (RDBMS) to store and
manage huge volume of data. This is called relational database because all
the data is stored into different tables and relations are established using
primary keys or other keys known as foreign keys.
3
RDBMS Terminology
4
Database is a collection of tables, with related data.
Table is a matrix with data. A table in a database looks like a simple spreadsheet.
Column
One column (data element) contains data of one and the same kind, for
example the column postcode.
Row
(= tuple, entry or record) is a group of related data, for example the data of
one subscription.
Redundancy Storing data twice, redundantly to make the system faster.
Primary Key
is unique. A key value can not occur twice in one table. With a given key,
you can find at most one row.
Foreign Key
is the linking pin between two tables.
Compound
Key
(composite key) is a key that consists of multiple columns, because one
column is not sufficiently unique.
Index in a database resembles an index at the back of a book.
Referential
Integrity
makes sure that a foreign key value always points to an existing row.
Introduction to MySQL
MySQL Database:
MySQL is a fast, easy-to-use RDBMS being used for many small and big businesses.
MySQL is developed, marketed, and supported by MySQL AB, which is a Swedish
company.
Key Advantages over other Databases:
• MySQL is released under an open-source license. So you have nothing to pay to use
it.
• MySQL is a very powerful program in its own right. It handles a large subset of the
functionality of the most expensive and powerful database packages.
• MySQL uses a standard form of the well-known SQL data language.
• MySQL works on many operating systems and with many languages including PHP,
PERL, C, C++, JAVA, R etc.
• MySQL data can be called in R for data analysis
5
MySQL Architecture
6
How to Install MySQL
• Download the files from below link for installation of MySQL.
https://dev.mysql.com/downloads/mysql/
Use the appropriate archive file for download 32-bit or 64-bit.
• For Excel connection go to below link-
https://dev.mysql.com/downloads/windows/
− Click on "MySQL for Excel“
− Copy both the installation file in one folder then start the installer community
Run both the setups in their respective order
Use MySQL Workbench for working with MySQL. It gets downloaded and installed
during the above process.
MySQL Workbench is a visual database design tool that integrates SQL
development, administration, database design, creation and maintenance into a
single integrated development environment for the MySQL database system.
7
MySQL Workbench
8
SQL query panel
Output (results)
from statements
Log of executed
statements
Executes the SQL statement
Or
Press ‘ctrl + Enter’ to execute
the statements
Creation of Database Overview
In MySQL, a database is a collection of objects that are used to store and
manipulate data such as tables, database views, triggers, stored procedures, etc.
Syntax:
CREATE DATABASE [IF NOT EXISTS] database_name;
Displaying a Database
Syntax:
SHOW DATABASES;
Selecting a database to work with
Syntax:
USE database_name;
Removing Databases
Syntax:
DROP DATABASE [IF EXISTS] database_name;
The IF NOT EXISTS is an optional clause of the statement. The IF NOT EXISTS
clause prevents you from an error of creating a new database that already exists in
the database server. You cannot have 2 databases with the same name in a MySQL
database server.
* 9
Creation of Database Overview
‘Student’ database created
10
CREATE DATABASE student;
SHOW DATABASES;
Drop database student;
SHOW DATABASES;
‘Student’ database dropped
SQL Statements – DDL and DML
DDL is short name of Data Definition Language. These statements are used to define
and modify a database or table structure and schema.
DML is short name of Data Manipulation Language. These statements affect records
in a table. These are used to perform basic operations on data such as selecting a few
records from a table, inserting new records, deleting unnecessary records and
updating/modifying existing records.
11
SQL Statements
DDL:
CREATE
ALTER
DROP
DML:
SELECT
INSERT
UPDATE
DELETE
DDL Statements - CREATE
Create tables (note that database is made up of tables which are like
data frames in R)
The table creation command requires:
• Name of the table
• Names of fields
• Definitions for each field
Syntax:
Here is generic SQL syntax to create a MySQL table:
CREATE TABLE table_name (column_name column_type);
12
DDL Statements - CREATE
Create tutorials_tbl in student database.
13
Use student
Create table tutorials_tbl(
tutorial_id INT NOT NULL AUTO_INCREMENT,
tutorial_title VARCHAR(100) NOT NULL,
tutorial_author VARCHAR(40) NOT NULL,
submission_date DATE,
PRIMARY KEY ( tutorial_id ) );
select * from tutorials_tbl;
INT, VARCHAR, DATE are data
types
This command returns all the
fields of table
DDL Statements - ALTER
Alter tables:
The ALTER TABLE statement allows you to add a column, drop a column,
change the data type of column, add primary key, rename table, and many
more.
Syntax:
ALTER TABLE table_name action1[,action2,…]
Using MySQL ALTER TABLE statement to add a new column into a table
ALTER TABLE table_name
ADD COLUMN column_name DECIMAL(2,1) NULL
AFTER column_name;
14
DDL Statements - ALTER
Add a new column to tutorials_tbl
15
ALTER TABLE tutorials_tbl
ADD COLUMN tutorial_fee DECIMAL(2,1) NULL
AFTER tutorial_author;
select * from tutorials_tbl;
DDL Statements - ALTER
Using MySQL ALTER TABLE to drop a column from a table.
ALTER TABLE table_name
DROP COLUMN column_name;
16
ALTER TABLE tutorials_tbl
DROP COLUMN tutorial_fee;
select * from tutorials_tbl;
Renaming table using MySQL ALTER TABLE statement
ALTER TABLE table_name
RENAME TO new_table_name;
DDL Statements - DROP
It is very easy to drop an existing MySQL table, but you need to be
very careful while deleting any existing table because data lost will
not be recovered after deleting a table.
Syntax:
Here is generic SQL syntax to drop a MySQL table:
DROP TABLE table_name;
17
DDL Statements - DROP
Delete tutorials_tbl table
18
DROP TABLE tutorials_tbl;
DML Statements - INSERT
To insert data into MySQL table, you would need to use SQL INSERT INTO
command. You can insert data into MySQL table by using mysql> prompt or
by using any script like PHP.
Syntax:
Here is generic SQL syntax of INSERT INTO command to insert data into
MySQL table:
INSERT INTO table_name ( field1, field2,...fieldN )
VALUES ( value1, value2,...valueN );
To insert string data types, it is required to keep all the values in double or
single quote, for example:- "value".
19
DML Statements - INSERT
Insert 3 records into tutorials_tbl.
20
INSERT INTO tutorials_tbl (tutorial_title, tutorial_author,
submission_date)
VALUES ("Learn PHP", "John Poul", NOW());
INSERT INTO tutorials_tbl (tutorial_title, tutorial_author,
submission_date)
VALUES ("Learn MySQL", "Abdul S", NOW());
INSERT INTO tutorials_tbl (tutorial_title, tutorial_author,
submission_date)
VALUES ("JAVA Tutorial", "Sanjay", '2007-05-06');
Here, we have not provided tutorial_id because at the time of table creation, we had
given AUTO_INCREMENT option for this field. So MySQL takes care of inserting these IDs
automatically.
NOW() is a MySQL function, which returns current date and time.
DML Statements – INSERT and UPDATE
Insert or Update in MySQL using ON DUPLICATE KEY UPDATE
INSERT ON DUPLICATE KEY UPDATE is a MySQL extension to the INSERT
statement. If you specify the ON DUPLICATE KEY UPDATE option in the
INSERT statement,the new row causes a duplicate value in the UNIQUE or
PRIMARY KEY index and MySQL performs an UPDATE to the old row based
on the new values.
Syntax:
INSERT INTO table(column_list)
VALUES(value_list)
ON DUPLICATE KEY UPDATE column_1 = new_value_1, column_2 =
new_value_2, …;
21
DML Statements – UPDATE
We use the UPDATE statement to update existing data in a table.
We can use the UPDATE statement to change column values of a single row,
a group of rows, or all rows in a table.
Syntax:
UPDATE table_name
SET
column_name1 = expr1,
column_name2 = expr2,
...
WHERE
condition;
22
DML Statements – UPDATE
23
update tutorials_tbl
set tutorial_author = 'Anand'
where tutorial_id = 1;
DML Statements – DELETE
MySQL DELETE statement allows you to remove records from not only one
table but also multiple tables using a single DELETE statement.
Syntax:
DELETE FROM table
[WHERE conditions]
24
Delete from tutorials_tbl
where tutorial_id = 3;
DML Statements – SELECT
The SQL SELECT command is used to fetch data from MySQL database. You
can use this command at mysql> prompt as well as in any script like PHP.
Syntax:
Here is generic SQL syntax of SELECT command to fetch data from MySQL
table:
SELECT field1, field2,...fieldN
FROM table_name1, table_name2...
[WHERE Clause] [OFFSET M ][LIMIT N]
25
DML Statements – SELECT
You can use one or more tables separated by comma to include various
conditions using a WHERE clause, but WHERE clause is an optional part of
SELECT command.
You can fetch one or more fields in a single SELECT command.
You can specify:
• star (*) in place of fields. In this case, SELECT will return all the fields.
Eg. SELECT * from tutorials_tbl ;
• any condition using WHERE clause.
• an offset using OFFSET from where SELECT will start returning records. By
default offset is zero.
• use LIMIT attribute to limit the number of returns 26
DML Statements – SELECT
27
use world;
select code, name, continent, region, population
from country;
DML Statements – SELECT with WHERE
clause
28
use world;
select code, name, continent, region, population from country
where continent = 'Asia';
DML Statements – SELECT with ORDER BY
clause
29
The ORDER BY clause allows you to:
• Sort a result set by a single column or multiple columns.
• Sort a result set by different columns in ascending or descending order.
Syntax:
SELECT column1, column2,...
FROM tbl
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC],...
DML Statements – SELECT with ORDER BY
clause
30
use world;
select code, name, continent, region, population
from country
order by name asc;
DML Statements – SELECT with ORDER BY
clause
31
use world;
select code, name, continent, region, population
from country
order by name desc;
DML Statements – SELECT with DISTINCT
and WHERE clause
32
In order to remove duplicate rows, you use the DISTINCT clause in the Select
Statement
Syntax:
SELECT DISTINCT columns
FROM table_name;
The WHERE clause allows you to specify exact rows to select based on a
particular filtering expression or condition.
Syntax:
SELECT columns
FROM table_name
WHERE
where_conditions;
DML Statements – SELECT with DISTINCT
and WHERE clause
33
use world;
select distinct continent from country where
population>100000;
DML Statements – SELECT with UNION
operator
34
MySQL UNION operator allows you to combine two or more result sets from
multiple tables into a single result set.
Syntax:
SELECT column1, column2
UNION [DISTINCT | ALL]
SELECT column1, column2
UNION [DISTINCT | ALL]
There are some rules that you need to follow in order to use the UNION operator:
• The number of columns appears in the corresponding SELECT statements
must be equal.
• The columns appear in the corresponding positions of each SELECT
statement must have the same data type or, at least, convertible data type.
DML Statements – SELECT with alias (for
columns)
35
MySQL supports two kinds of aliases which are known as column alias and table
alias.
MySQL alias for columns
Sometimes the column names are so technical which makes the query’s output
very difficult to understand. To give a column a descriptive name, you use a
column alias.
Syntax:
SELECT
[column_1 | expression] AS descriptive_name
FROM table_name;
If the alias contains space, you must quote it as the following:
SELECT
[column_1 | expression] AS `descriptive name`
FROM table_name;
DML Statements – SELECT with alias (for
columns)
36
use employees;
SELECT
CONCAT_WS(', ', “lastName”, “firstname”)
FROM employees;
SELECT
CONCAT_WS(', ', “lastName”, “firstname”) AS `Full name`
FROM employees;
CONCAT_WS function is used to concatenate first name and last name.
Using Alias we can make the column heading more readable.
DML Statements – SELECT with alias (for
columns)
37
DML Statements – SELECT with alias (for
tables)
38
MySQL alias for tables
You assign a table an alias by using the AS keyword as the following syntax:
table_name AS table_alias
You often use the table alias in the statement that contains INNER JOIN, LEFT
JOIN, self join clauses, and in subqueries.
INNER JOIN
39
Inner Joins
The MySQL INNER JOIN clause matches rows in one table with rows in other tables and
allows you to query rows that contain columns from both tables.
Before using MySQL INNER JOIN clause, you have to specify the following criteria:
• First, you have to specify the main table that appears in the FROM clause.
• Second, you need to specify the table that you want to join with the main table,
which appears in the INNER JOIN clause. Theoretically, you can join a table with
many tables. However, for better query performance, you should limit the number
of tables to join.
• Third, you need to specify the join condition or join predicate. The join condition
appears after the keyword ON of the INNER JOIN clause. The join condition is the
rule for matching rows between the main table and the other tables.
INNER JOIN
40
Syntax:
SELECT column_list
FROM t1
INNER JOIN t2 ON join_condition1
INNER JOIN t3 ON join_condition2
...
WHERE where_conditions;
For each row in the T1 table, the MySQL INNER JOIN clause compares it with
each row of the T2 table to check if both of them satisfy the join condition. When
the join condition is matched, it will return the row that combine columns in both
T1 and T2 tables.
Notice that the rows in both T1 and T2 tables have to be matched based on the join
condition. If no match found, the query will return an empty result set. This logic is also
applied if we join more than 2 tables.
INNER JOIN
41
The following Venn diagram illustrates how the MySQL INNER JOIN clause
works. The rows in the result set must appear in both tables: T1 and T2.
LEFT JOIN
42
The MySQL LEFT JOIN clause allows you to query data from two or more
database tables. The LEFT JOIN clause is an optional part of the Select
Statement, which appears after the FROM clause.
Syntax:
SELECT
T1.c1, T1.c2, T2.c1, T2.c2
FROM
T1
LEFT JOIN
T2 ON T1.c1 = T2.c1;
LEFT JOIN
43
LEFT JOIN clause allows you to select rows from the both left and right tables
that are matched, plus all rows from the left table ( T1 ) even there is no
match found for them in the right table ( T2 ).
LEFT JOIN
44
Example: In the example below, in database world though details for
Afghanistan do not exist in the city table, still that row is displayed in output
due to the Left Join keyword. In INNER JOINS this row would not have
appeared.
45
DML Statements – SELECT with GROUP
BY clause
46
The GROUP BY clause, which is an optional part of the SELECT statement,
groups a set of rows into a set of summary rows by values of columns or
expressions.
The GROUP BY clause returns one row for each group. In other words, it
reduces the number of rows in the result set.
Syntax:
SELECT
c1, c2,..., cn, aggregate_function(ci)
FROM
table
WHERE
where_conditions
GROUP BY c1 , c2,...,cn;
DML Statements – SELECT with GROUP
BY clause
47
use world;
Execute the highlighted Select command to see the impact of aggregate
function
DML Statements – SELECT with GROUP
BY and HAVING clause
48
The MySQL HAVING clause is often used with the GROUP BY clause. When
using with the GROUP BY clause, we can apply a filter condition to the
columns that appear in the GROUP BY clause. If the GROUP BY clause is
omitted, the HAVING clause behaves like the WHERE clause.
Eg.
SELECT
ordernumber,
SUM(quantityOrdered) AS itemsCount,
SUM(priceeach) AS total
FROM
orderdetails
GROUP BY ordernumber
HAVING total > 1000;
DML Statements – SELECT with GROUP
BY and HAVING clause
49
Execute the below SELECT command in world database.
DML Statements – SELECT with GROUP
BY and HAVING clause
50
Execute the below SELECT command in world database.
DML Statements – Subquery
51
A MySQL subquery is a query that is nested inside another query such as SELECT,
INSERT, UPDATE or DELETE. In addition, a MySQL subquery can be nested inside
another subquery.
A MySQL subquery is also called an inner query while the query that contains the
subquery is called an outer query.
MySQL subquery with IN and NOT IN operators
If a subquery returns more than one value, you can use other operators such as IN or
NOT IN operator in the WHERE clause.
MySQL subquery with EXISTS and NOT EXISTS
When a subquery is used with EXISTS or NOT EXISTS operator, a subquery returns a
Boolean value of TRUE or FALSE. The subquery acts as an existence check.
DML Statements – Subquery
52
SELECT customerNumber,checkNumber,amount
FROM payments
WHERE amount = (
SELECT MAX(amount)
FROM payments
);
SELECT customerName
FROM customers
WHERE EXISTS (
SELECT priceEach * quantityOrdered
FROM orderdetails
WHERE priceEach * quantityOrdered > 10000
GROUP BY orderNumber
);
DML Statements – Subquery
53
MySQL subquery in FROM clause:
When you use a subquery in the FROM clause, the result set returned from a
subquery is used as a table. This table is referred to as a derived table or
materialized subquery.
SELECT max(items),
min(items),
floor(avg(items))
FROM
(SELECT orderNumber,
count(orderNumber) AS items
FROM orderdetails
GROUP BY orderNumber) AS lineitems;
THANK YOU!
54

Contenu connexe

Tendances (20)

Sql
SqlSql
Sql
 
SQL : introduction
SQL : introductionSQL : introduction
SQL : introduction
 
SQL - DML and DDL Commands
SQL - DML and DDL CommandsSQL - DML and DDL Commands
SQL - DML and DDL Commands
 
MS-SQL SERVER ARCHITECTURE
MS-SQL SERVER ARCHITECTUREMS-SQL SERVER ARCHITECTURE
MS-SQL SERVER ARCHITECTURE
 
MySql:Introduction
MySql:IntroductionMySql:Introduction
MySql:Introduction
 
Oracle Database Overview
Oracle Database OverviewOracle Database Overview
Oracle Database Overview
 
Presentation slides of Sequence Query Language (SQL)
Presentation slides of Sequence Query Language (SQL)Presentation slides of Sequence Query Language (SQL)
Presentation slides of Sequence Query Language (SQL)
 
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with ExamplesDML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
 
Basic SQL and History
 Basic SQL and History Basic SQL and History
Basic SQL and History
 
10 Creating Triggers
10 Creating Triggers10 Creating Triggers
10 Creating Triggers
 
MySQL for beginners
MySQL for beginnersMySQL for beginners
MySQL for beginners
 
MySQL Basics
MySQL BasicsMySQL Basics
MySQL Basics
 
Sql
SqlSql
Sql
 
NoSQL databases
NoSQL databasesNoSQL databases
NoSQL databases
 
SQL
SQLSQL
SQL
 
Ms sql-server
Ms sql-serverMs sql-server
Ms sql-server
 
Sql ppt
Sql pptSql ppt
Sql ppt
 
SQL Queries
SQL QueriesSQL Queries
SQL Queries
 
Learning sql from w3schools
Learning sql from w3schoolsLearning sql from w3schools
Learning sql from w3schools
 
SQL for interview
SQL for interviewSQL for interview
SQL for interview
 

Similaire à Getting Started with MySQL I

SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowPavithSingh
 
Database COMPLETE
Database COMPLETEDatabase COMPLETE
Database COMPLETEAbrar ali
 
mysqlanditsbasiccommands-150226033905-conversion-gate02.pdf
mysqlanditsbasiccommands-150226033905-conversion-gate02.pdfmysqlanditsbasiccommands-150226033905-conversion-gate02.pdf
mysqlanditsbasiccommands-150226033905-conversion-gate02.pdfpradnyamulay
 
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfytxjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfytWrushabhShirsat3
 
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptxMy lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptxEliasPetros
 
05 Create and Maintain Databases and Tables.pptx
05 Create and Maintain Databases and Tables.pptx05 Create and Maintain Databases and Tables.pptx
05 Create and Maintain Databases and Tables.pptxMohamedNowfeek1
 
hjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptx
hjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptxhjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptx
hjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptxEliasPetros
 
SQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdfSQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdfDraguClaudiu
 
SQL Complete Tutorial. All Topics Covered
SQL Complete Tutorial. All Topics CoveredSQL Complete Tutorial. All Topics Covered
SQL Complete Tutorial. All Topics CoveredDanish Mehraj
 
Chapter – 6 SQL Lab Tutorial.pdf
Chapter – 6 SQL Lab Tutorial.pdfChapter – 6 SQL Lab Tutorial.pdf
Chapter – 6 SQL Lab Tutorial.pdfTamiratDejene1
 

Similaire à Getting Started with MySQL I (20)

SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good know
 
Database COMPLETE
Database COMPLETEDatabase COMPLETE
Database COMPLETE
 
lovely
lovelylovely
lovely
 
MySQL and its basic commands
MySQL and its basic commandsMySQL and its basic commands
MySQL and its basic commands
 
mysqlanditsbasiccommands-150226033905-conversion-gate02.pdf
mysqlanditsbasiccommands-150226033905-conversion-gate02.pdfmysqlanditsbasiccommands-150226033905-conversion-gate02.pdf
mysqlanditsbasiccommands-150226033905-conversion-gate02.pdf
 
unit-ii.pptx
unit-ii.pptxunit-ii.pptx
unit-ii.pptx
 
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfytxjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
 
Module02
Module02Module02
Module02
 
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptxMy lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
 
LECTURE NOTES.pdf
LECTURE NOTES.pdfLECTURE NOTES.pdf
LECTURE NOTES.pdf
 
LECTURE NOTES.pdf
LECTURE NOTES.pdfLECTURE NOTES.pdf
LECTURE NOTES.pdf
 
MySQL Essential Training
MySQL Essential TrainingMySQL Essential Training
MySQL Essential Training
 
05 Create and Maintain Databases and Tables.pptx
05 Create and Maintain Databases and Tables.pptx05 Create and Maintain Databases and Tables.pptx
05 Create and Maintain Databases and Tables.pptx
 
hjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptx
hjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptxhjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptx
hjkjlboiupoiuuouoiuoiuoiuoiuoiuoippt.pptx
 
SQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdfSQL -Beginner To Intermediate Level.pdf
SQL -Beginner To Intermediate Level.pdf
 
Mysql
MysqlMysql
Mysql
 
Data base
Data baseData base
Data base
 
SQL Complete Tutorial. All Topics Covered
SQL Complete Tutorial. All Topics CoveredSQL Complete Tutorial. All Topics Covered
SQL Complete Tutorial. All Topics Covered
 
chapter 8 SQL.ppt
chapter 8 SQL.pptchapter 8 SQL.ppt
chapter 8 SQL.ppt
 
Chapter – 6 SQL Lab Tutorial.pdf
Chapter – 6 SQL Lab Tutorial.pdfChapter – 6 SQL Lab Tutorial.pdf
Chapter – 6 SQL Lab Tutorial.pdf
 

Plus de Sankhya_Analytics

Plus de Sankhya_Analytics (9)

Getting Started with Python
Getting Started with PythonGetting Started with Python
Getting Started with Python
 
Data Management in Python
Data Management in PythonData Management in Python
Data Management in Python
 
Basic Analysis using Python
Basic Analysis using PythonBasic Analysis using Python
Basic Analysis using Python
 
Getting Started with MySQL II
Getting Started with MySQL IIGetting Started with MySQL II
Getting Started with MySQL II
 
Getting Started with R
Getting Started with RGetting Started with R
Getting Started with R
 
Data Management in R
Data Management in RData Management in R
Data Management in R
 
Basic Analysis using R
Basic Analysis using RBasic Analysis using R
Basic Analysis using R
 
R Get Started II
R Get Started IIR Get Started II
R Get Started II
 
R Get Started I
R Get Started IR Get Started I
R Get Started I
 

Dernier

Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...
Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...
Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...amitlee9823
 
Call Girls In Attibele ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Attibele ☎ 7737669865 🥵 Book Your One night StandCall Girls In Attibele ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Attibele ☎ 7737669865 🥵 Book Your One night Standamitlee9823
 
Call Girls In Bellandur ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bellandur ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bellandur ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bellandur ☎ 7737669865 🥵 Book Your One night Standamitlee9823
 
Call Girls In Doddaballapur Road ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Doddaballapur Road ☎ 7737669865 🥵 Book Your One night StandCall Girls In Doddaballapur Road ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Doddaballapur Road ☎ 7737669865 🥵 Book Your One night Standamitlee9823
 
👉 Amritsar Call Girl 👉📞 6367187148 👉📞 Just📲 Call Ruhi Call Girl Phone No Amri...
👉 Amritsar Call Girl 👉📞 6367187148 👉📞 Just📲 Call Ruhi Call Girl Phone No Amri...👉 Amritsar Call Girl 👉📞 6367187148 👉📞 Just📲 Call Ruhi Call Girl Phone No Amri...
👉 Amritsar Call Girl 👉📞 6367187148 👉📞 Just📲 Call Ruhi Call Girl Phone No Amri...karishmasinghjnh
 
5CL-ADBA,5cladba, Chinese supplier, safety is guaranteed
5CL-ADBA,5cladba, Chinese supplier, safety is guaranteed5CL-ADBA,5cladba, Chinese supplier, safety is guaranteed
5CL-ADBA,5cladba, Chinese supplier, safety is guaranteedamy56318795
 
➥🔝 7737669865 🔝▻ Mathura Call-girls in Women Seeking Men 🔝Mathura🔝 Escorts...
➥🔝 7737669865 🔝▻ Mathura Call-girls in Women Seeking Men  🔝Mathura🔝   Escorts...➥🔝 7737669865 🔝▻ Mathura Call-girls in Women Seeking Men  🔝Mathura🔝   Escorts...
➥🔝 7737669865 🔝▻ Mathura Call-girls in Women Seeking Men 🔝Mathura🔝 Escorts...amitlee9823
 
➥🔝 7737669865 🔝▻ Ongole Call-girls in Women Seeking Men 🔝Ongole🔝 Escorts S...
➥🔝 7737669865 🔝▻ Ongole Call-girls in Women Seeking Men  🔝Ongole🔝   Escorts S...➥🔝 7737669865 🔝▻ Ongole Call-girls in Women Seeking Men  🔝Ongole🔝   Escorts S...
➥🔝 7737669865 🔝▻ Ongole Call-girls in Women Seeking Men 🔝Ongole🔝 Escorts S...amitlee9823
 
➥🔝 7737669865 🔝▻ Dindigul Call-girls in Women Seeking Men 🔝Dindigul🔝 Escor...
➥🔝 7737669865 🔝▻ Dindigul Call-girls in Women Seeking Men  🔝Dindigul🔝   Escor...➥🔝 7737669865 🔝▻ Dindigul Call-girls in Women Seeking Men  🔝Dindigul🔝   Escor...
➥🔝 7737669865 🔝▻ Dindigul Call-girls in Women Seeking Men 🔝Dindigul🔝 Escor...amitlee9823
 
Just Call Vip call girls Bellary Escorts ☎️9352988975 Two shot with one girl ...
Just Call Vip call girls Bellary Escorts ☎️9352988975 Two shot with one girl ...Just Call Vip call girls Bellary Escorts ☎️9352988975 Two shot with one girl ...
Just Call Vip call girls Bellary Escorts ☎️9352988975 Two shot with one girl ...gajnagarg
 
SAC 25 Final National, Regional & Local Angel Group Investing Insights 2024 0...
SAC 25 Final National, Regional & Local Angel Group Investing Insights 2024 0...SAC 25 Final National, Regional & Local Angel Group Investing Insights 2024 0...
SAC 25 Final National, Regional & Local Angel Group Investing Insights 2024 0...Elaine Werffeli
 
Just Call Vip call girls Erode Escorts ☎️9352988975 Two shot with one girl (E...
Just Call Vip call girls Erode Escorts ☎️9352988975 Two shot with one girl (E...Just Call Vip call girls Erode Escorts ☎️9352988975 Two shot with one girl (E...
Just Call Vip call girls Erode Escorts ☎️9352988975 Two shot with one girl (E...gajnagarg
 
Call Girls In Shivaji Nagar ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Shivaji Nagar ☎ 7737669865 🥵 Book Your One night StandCall Girls In Shivaji Nagar ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Shivaji Nagar ☎ 7737669865 🥵 Book Your One night Standamitlee9823
 
Digital Advertising Lecture for Advanced Digital & Social Media Strategy at U...
Digital Advertising Lecture for Advanced Digital & Social Media Strategy at U...Digital Advertising Lecture for Advanced Digital & Social Media Strategy at U...
Digital Advertising Lecture for Advanced Digital & Social Media Strategy at U...Valters Lauzums
 
Call Girls Bommasandra Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Bommasandra Just Call 👗 7737669865 👗 Top Class Call Girl Service B...Call Girls Bommasandra Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Bommasandra Just Call 👗 7737669865 👗 Top Class Call Girl Service B...amitlee9823
 
Call Girls In Hsr Layout ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Hsr Layout ☎ 7737669865 🥵 Book Your One night StandCall Girls In Hsr Layout ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Hsr Layout ☎ 7737669865 🥵 Book Your One night Standamitlee9823
 
Vip Mumbai Call Girls Marol Naka Call On 9920725232 With Body to body massage...
Vip Mumbai Call Girls Marol Naka Call On 9920725232 With Body to body massage...Vip Mumbai Call Girls Marol Naka Call On 9920725232 With Body to body massage...
Vip Mumbai Call Girls Marol Naka Call On 9920725232 With Body to body massage...amitlee9823
 
DATA SUMMIT 24 Building Real-Time Pipelines With FLaNK
DATA SUMMIT 24  Building Real-Time Pipelines With FLaNKDATA SUMMIT 24  Building Real-Time Pipelines With FLaNK
DATA SUMMIT 24 Building Real-Time Pipelines With FLaNKTimothy Spann
 

Dernier (20)

Abortion pills in Jeddah | +966572737505 | Get Cytotec
Abortion pills in Jeddah | +966572737505 | Get CytotecAbortion pills in Jeddah | +966572737505 | Get Cytotec
Abortion pills in Jeddah | +966572737505 | Get Cytotec
 
Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...
Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...
Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...
 
Call Girls In Attibele ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Attibele ☎ 7737669865 🥵 Book Your One night StandCall Girls In Attibele ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Attibele ☎ 7737669865 🥵 Book Your One night Stand
 
Call Girls In Bellandur ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bellandur ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bellandur ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bellandur ☎ 7737669865 🥵 Book Your One night Stand
 
Call Girls In Doddaballapur Road ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Doddaballapur Road ☎ 7737669865 🥵 Book Your One night StandCall Girls In Doddaballapur Road ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Doddaballapur Road ☎ 7737669865 🥵 Book Your One night Stand
 
👉 Amritsar Call Girl 👉📞 6367187148 👉📞 Just📲 Call Ruhi Call Girl Phone No Amri...
👉 Amritsar Call Girl 👉📞 6367187148 👉📞 Just📲 Call Ruhi Call Girl Phone No Amri...👉 Amritsar Call Girl 👉📞 6367187148 👉📞 Just📲 Call Ruhi Call Girl Phone No Amri...
👉 Amritsar Call Girl 👉📞 6367187148 👉📞 Just📲 Call Ruhi Call Girl Phone No Amri...
 
5CL-ADBA,5cladba, Chinese supplier, safety is guaranteed
5CL-ADBA,5cladba, Chinese supplier, safety is guaranteed5CL-ADBA,5cladba, Chinese supplier, safety is guaranteed
5CL-ADBA,5cladba, Chinese supplier, safety is guaranteed
 
➥🔝 7737669865 🔝▻ Mathura Call-girls in Women Seeking Men 🔝Mathura🔝 Escorts...
➥🔝 7737669865 🔝▻ Mathura Call-girls in Women Seeking Men  🔝Mathura🔝   Escorts...➥🔝 7737669865 🔝▻ Mathura Call-girls in Women Seeking Men  🔝Mathura🔝   Escorts...
➥🔝 7737669865 🔝▻ Mathura Call-girls in Women Seeking Men 🔝Mathura🔝 Escorts...
 
➥🔝 7737669865 🔝▻ Ongole Call-girls in Women Seeking Men 🔝Ongole🔝 Escorts S...
➥🔝 7737669865 🔝▻ Ongole Call-girls in Women Seeking Men  🔝Ongole🔝   Escorts S...➥🔝 7737669865 🔝▻ Ongole Call-girls in Women Seeking Men  🔝Ongole🔝   Escorts S...
➥🔝 7737669865 🔝▻ Ongole Call-girls in Women Seeking Men 🔝Ongole🔝 Escorts S...
 
➥🔝 7737669865 🔝▻ Dindigul Call-girls in Women Seeking Men 🔝Dindigul🔝 Escor...
➥🔝 7737669865 🔝▻ Dindigul Call-girls in Women Seeking Men  🔝Dindigul🔝   Escor...➥🔝 7737669865 🔝▻ Dindigul Call-girls in Women Seeking Men  🔝Dindigul🔝   Escor...
➥🔝 7737669865 🔝▻ Dindigul Call-girls in Women Seeking Men 🔝Dindigul🔝 Escor...
 
Just Call Vip call girls Bellary Escorts ☎️9352988975 Two shot with one girl ...
Just Call Vip call girls Bellary Escorts ☎️9352988975 Two shot with one girl ...Just Call Vip call girls Bellary Escorts ☎️9352988975 Two shot with one girl ...
Just Call Vip call girls Bellary Escorts ☎️9352988975 Two shot with one girl ...
 
SAC 25 Final National, Regional & Local Angel Group Investing Insights 2024 0...
SAC 25 Final National, Regional & Local Angel Group Investing Insights 2024 0...SAC 25 Final National, Regional & Local Angel Group Investing Insights 2024 0...
SAC 25 Final National, Regional & Local Angel Group Investing Insights 2024 0...
 
Just Call Vip call girls Erode Escorts ☎️9352988975 Two shot with one girl (E...
Just Call Vip call girls Erode Escorts ☎️9352988975 Two shot with one girl (E...Just Call Vip call girls Erode Escorts ☎️9352988975 Two shot with one girl (E...
Just Call Vip call girls Erode Escorts ☎️9352988975 Two shot with one girl (E...
 
Call Girls In Shivaji Nagar ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Shivaji Nagar ☎ 7737669865 🥵 Book Your One night StandCall Girls In Shivaji Nagar ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Shivaji Nagar ☎ 7737669865 🥵 Book Your One night Stand
 
Digital Advertising Lecture for Advanced Digital & Social Media Strategy at U...
Digital Advertising Lecture for Advanced Digital & Social Media Strategy at U...Digital Advertising Lecture for Advanced Digital & Social Media Strategy at U...
Digital Advertising Lecture for Advanced Digital & Social Media Strategy at U...
 
Call Girls Bommasandra Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Bommasandra Just Call 👗 7737669865 👗 Top Class Call Girl Service B...Call Girls Bommasandra Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Bommasandra Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
 
Call Girls In Hsr Layout ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Hsr Layout ☎ 7737669865 🥵 Book Your One night StandCall Girls In Hsr Layout ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Hsr Layout ☎ 7737669865 🥵 Book Your One night Stand
 
Call Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts Service
Call Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts ServiceCall Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts Service
Call Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts Service
 
Vip Mumbai Call Girls Marol Naka Call On 9920725232 With Body to body massage...
Vip Mumbai Call Girls Marol Naka Call On 9920725232 With Body to body massage...Vip Mumbai Call Girls Marol Naka Call On 9920725232 With Body to body massage...
Vip Mumbai Call Girls Marol Naka Call On 9920725232 With Body to body massage...
 
DATA SUMMIT 24 Building Real-Time Pipelines With FLaNK
DATA SUMMIT 24  Building Real-Time Pipelines With FLaNKDATA SUMMIT 24  Building Real-Time Pipelines With FLaNK
DATA SUMMIT 24 Building Real-Time Pipelines With FLaNK
 

Getting Started with MySQL I

  • 2. What is Database? • A database is a structured collection of data. Here are some typical examples of databases: • An online store database that stores product details, customer details and orders • A database for a web forum that stores members, forums, topics and posts • A database for a blog system, such as WordPress, that stores users, blog posts, categories, tags, and comments 2
  • 3. What is Relational Database Management System? A Relational DataBase Management System (RDBMS) is a software that: • Enables you to implement a database with tables, columns and indexes. • Guarantees the Referential Integrity between rows of various tables. • Updates the indexes automatically. • Interprets an SQL query and extracts information from various tables based on SQL query We use Relational Database Management Systems (RDBMS) to store and manage huge volume of data. This is called relational database because all the data is stored into different tables and relations are established using primary keys or other keys known as foreign keys. 3
  • 4. RDBMS Terminology 4 Database is a collection of tables, with related data. Table is a matrix with data. A table in a database looks like a simple spreadsheet. Column One column (data element) contains data of one and the same kind, for example the column postcode. Row (= tuple, entry or record) is a group of related data, for example the data of one subscription. Redundancy Storing data twice, redundantly to make the system faster. Primary Key is unique. A key value can not occur twice in one table. With a given key, you can find at most one row. Foreign Key is the linking pin between two tables. Compound Key (composite key) is a key that consists of multiple columns, because one column is not sufficiently unique. Index in a database resembles an index at the back of a book. Referential Integrity makes sure that a foreign key value always points to an existing row.
  • 5. Introduction to MySQL MySQL Database: MySQL is a fast, easy-to-use RDBMS being used for many small and big businesses. MySQL is developed, marketed, and supported by MySQL AB, which is a Swedish company. Key Advantages over other Databases: • MySQL is released under an open-source license. So you have nothing to pay to use it. • MySQL is a very powerful program in its own right. It handles a large subset of the functionality of the most expensive and powerful database packages. • MySQL uses a standard form of the well-known SQL data language. • MySQL works on many operating systems and with many languages including PHP, PERL, C, C++, JAVA, R etc. • MySQL data can be called in R for data analysis 5
  • 7. How to Install MySQL • Download the files from below link for installation of MySQL. https://dev.mysql.com/downloads/mysql/ Use the appropriate archive file for download 32-bit or 64-bit. • For Excel connection go to below link- https://dev.mysql.com/downloads/windows/ − Click on "MySQL for Excel“ − Copy both the installation file in one folder then start the installer community Run both the setups in their respective order Use MySQL Workbench for working with MySQL. It gets downloaded and installed during the above process. MySQL Workbench is a visual database design tool that integrates SQL development, administration, database design, creation and maintenance into a single integrated development environment for the MySQL database system. 7
  • 8. MySQL Workbench 8 SQL query panel Output (results) from statements Log of executed statements Executes the SQL statement Or Press ‘ctrl + Enter’ to execute the statements
  • 9. Creation of Database Overview In MySQL, a database is a collection of objects that are used to store and manipulate data such as tables, database views, triggers, stored procedures, etc. Syntax: CREATE DATABASE [IF NOT EXISTS] database_name; Displaying a Database Syntax: SHOW DATABASES; Selecting a database to work with Syntax: USE database_name; Removing Databases Syntax: DROP DATABASE [IF EXISTS] database_name; The IF NOT EXISTS is an optional clause of the statement. The IF NOT EXISTS clause prevents you from an error of creating a new database that already exists in the database server. You cannot have 2 databases with the same name in a MySQL database server. * 9
  • 10. Creation of Database Overview ‘Student’ database created 10 CREATE DATABASE student; SHOW DATABASES; Drop database student; SHOW DATABASES; ‘Student’ database dropped
  • 11. SQL Statements – DDL and DML DDL is short name of Data Definition Language. These statements are used to define and modify a database or table structure and schema. DML is short name of Data Manipulation Language. These statements affect records in a table. These are used to perform basic operations on data such as selecting a few records from a table, inserting new records, deleting unnecessary records and updating/modifying existing records. 11 SQL Statements DDL: CREATE ALTER DROP DML: SELECT INSERT UPDATE DELETE
  • 12. DDL Statements - CREATE Create tables (note that database is made up of tables which are like data frames in R) The table creation command requires: • Name of the table • Names of fields • Definitions for each field Syntax: Here is generic SQL syntax to create a MySQL table: CREATE TABLE table_name (column_name column_type); 12
  • 13. DDL Statements - CREATE Create tutorials_tbl in student database. 13 Use student Create table tutorials_tbl( tutorial_id INT NOT NULL AUTO_INCREMENT, tutorial_title VARCHAR(100) NOT NULL, tutorial_author VARCHAR(40) NOT NULL, submission_date DATE, PRIMARY KEY ( tutorial_id ) ); select * from tutorials_tbl; INT, VARCHAR, DATE are data types This command returns all the fields of table
  • 14. DDL Statements - ALTER Alter tables: The ALTER TABLE statement allows you to add a column, drop a column, change the data type of column, add primary key, rename table, and many more. Syntax: ALTER TABLE table_name action1[,action2,…] Using MySQL ALTER TABLE statement to add a new column into a table ALTER TABLE table_name ADD COLUMN column_name DECIMAL(2,1) NULL AFTER column_name; 14
  • 15. DDL Statements - ALTER Add a new column to tutorials_tbl 15 ALTER TABLE tutorials_tbl ADD COLUMN tutorial_fee DECIMAL(2,1) NULL AFTER tutorial_author; select * from tutorials_tbl;
  • 16. DDL Statements - ALTER Using MySQL ALTER TABLE to drop a column from a table. ALTER TABLE table_name DROP COLUMN column_name; 16 ALTER TABLE tutorials_tbl DROP COLUMN tutorial_fee; select * from tutorials_tbl; Renaming table using MySQL ALTER TABLE statement ALTER TABLE table_name RENAME TO new_table_name;
  • 17. DDL Statements - DROP It is very easy to drop an existing MySQL table, but you need to be very careful while deleting any existing table because data lost will not be recovered after deleting a table. Syntax: Here is generic SQL syntax to drop a MySQL table: DROP TABLE table_name; 17
  • 18. DDL Statements - DROP Delete tutorials_tbl table 18 DROP TABLE tutorials_tbl;
  • 19. DML Statements - INSERT To insert data into MySQL table, you would need to use SQL INSERT INTO command. You can insert data into MySQL table by using mysql> prompt or by using any script like PHP. Syntax: Here is generic SQL syntax of INSERT INTO command to insert data into MySQL table: INSERT INTO table_name ( field1, field2,...fieldN ) VALUES ( value1, value2,...valueN ); To insert string data types, it is required to keep all the values in double or single quote, for example:- "value". 19
  • 20. DML Statements - INSERT Insert 3 records into tutorials_tbl. 20 INSERT INTO tutorials_tbl (tutorial_title, tutorial_author, submission_date) VALUES ("Learn PHP", "John Poul", NOW()); INSERT INTO tutorials_tbl (tutorial_title, tutorial_author, submission_date) VALUES ("Learn MySQL", "Abdul S", NOW()); INSERT INTO tutorials_tbl (tutorial_title, tutorial_author, submission_date) VALUES ("JAVA Tutorial", "Sanjay", '2007-05-06'); Here, we have not provided tutorial_id because at the time of table creation, we had given AUTO_INCREMENT option for this field. So MySQL takes care of inserting these IDs automatically. NOW() is a MySQL function, which returns current date and time.
  • 21. DML Statements – INSERT and UPDATE Insert or Update in MySQL using ON DUPLICATE KEY UPDATE INSERT ON DUPLICATE KEY UPDATE is a MySQL extension to the INSERT statement. If you specify the ON DUPLICATE KEY UPDATE option in the INSERT statement,the new row causes a duplicate value in the UNIQUE or PRIMARY KEY index and MySQL performs an UPDATE to the old row based on the new values. Syntax: INSERT INTO table(column_list) VALUES(value_list) ON DUPLICATE KEY UPDATE column_1 = new_value_1, column_2 = new_value_2, …; 21
  • 22. DML Statements – UPDATE We use the UPDATE statement to update existing data in a table. We can use the UPDATE statement to change column values of a single row, a group of rows, or all rows in a table. Syntax: UPDATE table_name SET column_name1 = expr1, column_name2 = expr2, ... WHERE condition; 22
  • 23. DML Statements – UPDATE 23 update tutorials_tbl set tutorial_author = 'Anand' where tutorial_id = 1;
  • 24. DML Statements – DELETE MySQL DELETE statement allows you to remove records from not only one table but also multiple tables using a single DELETE statement. Syntax: DELETE FROM table [WHERE conditions] 24 Delete from tutorials_tbl where tutorial_id = 3;
  • 25. DML Statements – SELECT The SQL SELECT command is used to fetch data from MySQL database. You can use this command at mysql> prompt as well as in any script like PHP. Syntax: Here is generic SQL syntax of SELECT command to fetch data from MySQL table: SELECT field1, field2,...fieldN FROM table_name1, table_name2... [WHERE Clause] [OFFSET M ][LIMIT N] 25
  • 26. DML Statements – SELECT You can use one or more tables separated by comma to include various conditions using a WHERE clause, but WHERE clause is an optional part of SELECT command. You can fetch one or more fields in a single SELECT command. You can specify: • star (*) in place of fields. In this case, SELECT will return all the fields. Eg. SELECT * from tutorials_tbl ; • any condition using WHERE clause. • an offset using OFFSET from where SELECT will start returning records. By default offset is zero. • use LIMIT attribute to limit the number of returns 26
  • 27. DML Statements – SELECT 27 use world; select code, name, continent, region, population from country;
  • 28. DML Statements – SELECT with WHERE clause 28 use world; select code, name, continent, region, population from country where continent = 'Asia';
  • 29. DML Statements – SELECT with ORDER BY clause 29 The ORDER BY clause allows you to: • Sort a result set by a single column or multiple columns. • Sort a result set by different columns in ascending or descending order. Syntax: SELECT column1, column2,... FROM tbl ORDER BY column1 [ASC|DESC], column2 [ASC|DESC],...
  • 30. DML Statements – SELECT with ORDER BY clause 30 use world; select code, name, continent, region, population from country order by name asc;
  • 31. DML Statements – SELECT with ORDER BY clause 31 use world; select code, name, continent, region, population from country order by name desc;
  • 32. DML Statements – SELECT with DISTINCT and WHERE clause 32 In order to remove duplicate rows, you use the DISTINCT clause in the Select Statement Syntax: SELECT DISTINCT columns FROM table_name; The WHERE clause allows you to specify exact rows to select based on a particular filtering expression or condition. Syntax: SELECT columns FROM table_name WHERE where_conditions;
  • 33. DML Statements – SELECT with DISTINCT and WHERE clause 33 use world; select distinct continent from country where population>100000;
  • 34. DML Statements – SELECT with UNION operator 34 MySQL UNION operator allows you to combine two or more result sets from multiple tables into a single result set. Syntax: SELECT column1, column2 UNION [DISTINCT | ALL] SELECT column1, column2 UNION [DISTINCT | ALL] There are some rules that you need to follow in order to use the UNION operator: • The number of columns appears in the corresponding SELECT statements must be equal. • The columns appear in the corresponding positions of each SELECT statement must have the same data type or, at least, convertible data type.
  • 35. DML Statements – SELECT with alias (for columns) 35 MySQL supports two kinds of aliases which are known as column alias and table alias. MySQL alias for columns Sometimes the column names are so technical which makes the query’s output very difficult to understand. To give a column a descriptive name, you use a column alias. Syntax: SELECT [column_1 | expression] AS descriptive_name FROM table_name; If the alias contains space, you must quote it as the following: SELECT [column_1 | expression] AS `descriptive name` FROM table_name;
  • 36. DML Statements – SELECT with alias (for columns) 36 use employees; SELECT CONCAT_WS(', ', “lastName”, “firstname”) FROM employees; SELECT CONCAT_WS(', ', “lastName”, “firstname”) AS `Full name` FROM employees; CONCAT_WS function is used to concatenate first name and last name. Using Alias we can make the column heading more readable.
  • 37. DML Statements – SELECT with alias (for columns) 37
  • 38. DML Statements – SELECT with alias (for tables) 38 MySQL alias for tables You assign a table an alias by using the AS keyword as the following syntax: table_name AS table_alias You often use the table alias in the statement that contains INNER JOIN, LEFT JOIN, self join clauses, and in subqueries.
  • 39. INNER JOIN 39 Inner Joins The MySQL INNER JOIN clause matches rows in one table with rows in other tables and allows you to query rows that contain columns from both tables. Before using MySQL INNER JOIN clause, you have to specify the following criteria: • First, you have to specify the main table that appears in the FROM clause. • Second, you need to specify the table that you want to join with the main table, which appears in the INNER JOIN clause. Theoretically, you can join a table with many tables. However, for better query performance, you should limit the number of tables to join. • Third, you need to specify the join condition or join predicate. The join condition appears after the keyword ON of the INNER JOIN clause. The join condition is the rule for matching rows between the main table and the other tables.
  • 40. INNER JOIN 40 Syntax: SELECT column_list FROM t1 INNER JOIN t2 ON join_condition1 INNER JOIN t3 ON join_condition2 ... WHERE where_conditions; For each row in the T1 table, the MySQL INNER JOIN clause compares it with each row of the T2 table to check if both of them satisfy the join condition. When the join condition is matched, it will return the row that combine columns in both T1 and T2 tables. Notice that the rows in both T1 and T2 tables have to be matched based on the join condition. If no match found, the query will return an empty result set. This logic is also applied if we join more than 2 tables.
  • 41. INNER JOIN 41 The following Venn diagram illustrates how the MySQL INNER JOIN clause works. The rows in the result set must appear in both tables: T1 and T2.
  • 42. LEFT JOIN 42 The MySQL LEFT JOIN clause allows you to query data from two or more database tables. The LEFT JOIN clause is an optional part of the Select Statement, which appears after the FROM clause. Syntax: SELECT T1.c1, T1.c2, T2.c1, T2.c2 FROM T1 LEFT JOIN T2 ON T1.c1 = T2.c1;
  • 43. LEFT JOIN 43 LEFT JOIN clause allows you to select rows from the both left and right tables that are matched, plus all rows from the left table ( T1 ) even there is no match found for them in the right table ( T2 ).
  • 44. LEFT JOIN 44 Example: In the example below, in database world though details for Afghanistan do not exist in the city table, still that row is displayed in output due to the Left Join keyword. In INNER JOINS this row would not have appeared.
  • 45. 45
  • 46. DML Statements – SELECT with GROUP BY clause 46 The GROUP BY clause, which is an optional part of the SELECT statement, groups a set of rows into a set of summary rows by values of columns or expressions. The GROUP BY clause returns one row for each group. In other words, it reduces the number of rows in the result set. Syntax: SELECT c1, c2,..., cn, aggregate_function(ci) FROM table WHERE where_conditions GROUP BY c1 , c2,...,cn;
  • 47. DML Statements – SELECT with GROUP BY clause 47 use world; Execute the highlighted Select command to see the impact of aggregate function
  • 48. DML Statements – SELECT with GROUP BY and HAVING clause 48 The MySQL HAVING clause is often used with the GROUP BY clause. When using with the GROUP BY clause, we can apply a filter condition to the columns that appear in the GROUP BY clause. If the GROUP BY clause is omitted, the HAVING clause behaves like the WHERE clause. Eg. SELECT ordernumber, SUM(quantityOrdered) AS itemsCount, SUM(priceeach) AS total FROM orderdetails GROUP BY ordernumber HAVING total > 1000;
  • 49. DML Statements – SELECT with GROUP BY and HAVING clause 49 Execute the below SELECT command in world database.
  • 50. DML Statements – SELECT with GROUP BY and HAVING clause 50 Execute the below SELECT command in world database.
  • 51. DML Statements – Subquery 51 A MySQL subquery is a query that is nested inside another query such as SELECT, INSERT, UPDATE or DELETE. In addition, a MySQL subquery can be nested inside another subquery. A MySQL subquery is also called an inner query while the query that contains the subquery is called an outer query. MySQL subquery with IN and NOT IN operators If a subquery returns more than one value, you can use other operators such as IN or NOT IN operator in the WHERE clause. MySQL subquery with EXISTS and NOT EXISTS When a subquery is used with EXISTS or NOT EXISTS operator, a subquery returns a Boolean value of TRUE or FALSE. The subquery acts as an existence check.
  • 52. DML Statements – Subquery 52 SELECT customerNumber,checkNumber,amount FROM payments WHERE amount = ( SELECT MAX(amount) FROM payments ); SELECT customerName FROM customers WHERE EXISTS ( SELECT priceEach * quantityOrdered FROM orderdetails WHERE priceEach * quantityOrdered > 10000 GROUP BY orderNumber );
  • 53. DML Statements – Subquery 53 MySQL subquery in FROM clause: When you use a subquery in the FROM clause, the result set returned from a subquery is used as a table. This table is referred to as a derived table or materialized subquery. SELECT max(items), min(items), floor(avg(items)) FROM (SELECT orderNumber, count(orderNumber) AS items FROM orderdetails GROUP BY orderNumber) AS lineitems;