54
Getting Started With MySQL I

Getting Started with MySQL I

Embed Size (px)

Citation preview

Page 1: Getting Started with MySQL I

Getting Started With MySQL I

Page 2: 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

Page 3: Getting Started with MySQL I

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

Page 4: Getting Started with MySQL I

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.

ColumnOne 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 Keyis unique. A key value can not occur twice in one table. With a given key,

you can find at most one row.

Foreign Keyis 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.

Page 5: Getting Started with MySQL I

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 analysis5

Page 6: Getting Started with MySQL I

MySQL Architecture

6

Page 7: Getting Started with MySQL I

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

Page 8: Getting Started with MySQL I

MySQL Workbench

8

SQL query panel

Output (results) from statements

Log of executed statements

Executes the SQL statementOr Press ‘ctrl + Enter’ to execute the statements

Page 9: Getting Started with MySQL I

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 DatabaseSyntax:SHOW DATABASES;

Selecting a database to work withSyntax:USE database_name;

Removing DatabasesSyntax: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

Page 10: Getting Started with MySQL I

Creation of Database Overview

‘Student’ database created

10

CREATE DATABASE student;SHOW DATABASES;

Drop database student;SHOW DATABASES;

‘Student’ database dropped

Page 11: Getting Started with MySQL I

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

Page 12: Getting Started with MySQL I

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

Page 13: Getting Started with MySQL I

DDL Statements - CREATE

Create tutorials_tbl in student database.

13

Use studentCreate 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

Page 14: Getting Started with MySQL I

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_nameADD COLUMN column_name DECIMAL(2,1) NULLAFTER column_name;

14

Page 15: Getting Started with MySQL I

DDL Statements - ALTER

Add a new column to tutorials_tbl

15

ALTER TABLE tutorials_tblADD COLUMN tutorial_fee DECIMAL(2,1) NULL AFTER tutorial_author;

select * from tutorials_tbl;

Page 16: Getting Started with MySQL I

DDL Statements - ALTER

Using MySQL ALTER TABLE to drop a column from a table.

ALTER TABLE table_nameDROP COLUMN column_name;

16

ALTER TABLE tutorials_tblDROP COLUMN tutorial_fee;

select * from tutorials_tbl;

Renaming table using MySQL ALTER TABLE statement

ALTER TABLE table_nameRENAME TO new_table_name;

Page 17: Getting Started with MySQL I

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

Page 18: Getting Started with MySQL I

DDL Statements - DROP

Delete tutorials_tbl table

18

DROP TABLE tutorials_tbl;

Page 19: Getting Started with MySQL I

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

Page 20: Getting Started with MySQL I

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.

Page 21: Getting Started with MySQL I

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

Page 22: Getting Started with MySQL I

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_nameSET

column_name1 = expr1,column_name2 = expr2,...

WHEREcondition;

22

Page 23: Getting Started with MySQL I

DML Statements – UPDATE

23

update tutorials_tblset tutorial_author = 'Anand' where tutorial_id = 1;

Page 24: Getting Started with MySQL I

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_tblwhere tutorial_id = 3;

Page 25: Getting Started with MySQL I

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,...fieldNFROM table_name1, table_name2...[WHERE Clause] [OFFSET M ][LIMIT N]

25

Page 26: Getting Started with MySQL I

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 returns26

Page 27: Getting Started with MySQL I

DML Statements – SELECT

27

use world;select code, name, continent, region, population from country;

Page 28: Getting Started with MySQL I

DML Statements – SELECT with WHERE clause

28

use world;select code, name, continent, region, population from country where continent = 'Asia';

Page 29: Getting Started with MySQL I

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 tblORDER BY column1 [ASC|DESC], column2 [ASC|DESC],...

Page 30: Getting Started with MySQL I

DML Statements – SELECT with ORDER BY clause

30

use world;select code, name, continent, region, population from country order by name asc;

Page 31: Getting Started with MySQL I

DML Statements – SELECT with ORDER BY clause

31

use world;select code, name, continent, region, population from country order by name desc;

Page 32: Getting Started with MySQL I

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 columnsFROM table_name;

The WHERE clause allows you to specify exact rows to select based on a

particular filtering expression or condition.

Syntax:

SELECT columnsFROM table_nameWHEREwhere_conditions;

Page 33: Getting Started with MySQL I

DML Statements – SELECT with DISTINCT and WHERE clause

33

use world;select distinct continent from country where population>100000;

Page 34: Getting Started with MySQL I

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, column2UNION [DISTINCT | ALL]SELECT column1, column2UNION [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.

Page 35: Getting Started with MySQL I

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_nameFROM table_name;

If the alias contains space, you must quote it as the following:SELECT [column_1 | expression] AS `descriptive name`FROM table_name;

Page 36: Getting Started with MySQL I

DML Statements – SELECT with alias (for columns)

36

use employees;SELECTCONCAT_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.

Page 37: Getting Started with MySQL I

DML Statements – SELECT with alias (for columns)

37

Page 38: Getting Started with MySQL I

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.

Page 39: Getting Started with MySQL I

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.

Page 40: Getting Started with MySQL I

INNER JOIN

40

Syntax:

SELECT column_listFROM t1INNER JOIN t2 ON join_condition1INNER 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.

Page 41: Getting Started with MySQL I

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.

Page 42: Getting Started with MySQL I

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

FROMT1

LEFT JOINT2 ON T1.c1 = T2.c1;

Page 43: Getting Started with MySQL I

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 ).

Page 44: Getting Started with MySQL I

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.

Page 45: Getting Started with MySQL I

45

Page 46: Getting Started with MySQL I

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)

FROMtable

WHEREwhere_conditions

GROUP BY c1 , c2,...,cn;

Page 47: Getting Started with MySQL I

DML Statements – SELECT with GROUP BY clause

47

use world;

Execute the highlighted Select command to see the impact of aggregate

function

Page 48: Getting Started with MySQL I

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

FROMorderdetails

GROUP BY ordernumberHAVING total > 1000;

Page 49: Getting Started with MySQL I

DML Statements – SELECT with GROUP BY and HAVING clause

49

Execute the below SELECT command in world database.

Page 50: Getting Started with MySQL I

DML Statements – SELECT with GROUP BY and HAVING clause

50

Execute the below SELECT command in world database.

Page 51: Getting Started with MySQL I

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.

Page 52: Getting Started with MySQL I

DML Statements – Subquery

52

SELECT customerNumber,checkNumber,amountFROM paymentsWHERE amount = (SELECT MAX(amount)

FROM payments);

SELECT customerNameFROM customersWHERE EXISTS (

SELECT priceEach * quantityOrderedFROM orderdetailsWHERE priceEach * quantityOrdered > 10000GROUP BY orderNumber

);

Page 53: Getting Started with MySQL I

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 itemsFROM orderdetailsGROUP BY orderNumber) AS lineitems;

Page 54: Getting Started with MySQL I

THANK YOU!

54