You are on page 1of 90

MySQL

eXenium Technologies
MySQL

 RDBMS
 Faster Than File System
 Easy to Query
 Download Exercise Files
 http://www.mediafire.com/download/aufy14p0gmi3zvg/SQL.zip

eXenium
Technologies
Creating and Deleting Database

 Creating a DB
 CREATE DATABASE myDB
 Deleting a DB
 DROP DATABASE myDB

eXenium
Technologies
Creating Table

create table student(


id integer not null auto_increment primary key,
name varchar(255),
address varchar(255),
section varchar(255),
state char(2),
zip char(10)
);

eXenium
Technologies
Deleting Table

drop table student;

eXenium
Technologies
Importing sql

 Start mysql
 find mysql.exe in xampp folder
 Then type
 Mysql
 It starts
 See Databases
 show Databases;
 Importing
 mysql -u root -p < /home/shahriar/Desktop/world-mysql.sql
 Skip password because no password is used for root

eXenium
Technologies
Using IDE

 Execute Query
 A cross platform IDE for SQL
 Need a JDBC driver to connect to Database
 Fast and auto suggestion will provide
 Download
 http://executequery.org/download

eXenium
Technologies
Configure Execute Query

 Start the MySQL server


 Open Execute Query
 Follow the next steps

eXenium
Technologies
Configure Execute Query(Cont.)
Click on New Connection

eXenium
Technologies
Configure Execute Query(Cont.)
• In Connection Name any name
• User Name is must be choose as like the user name exist in the
MySQL DB
• Password field will contain the password for the specific user of
the username provided
• Host Name will be localhost because the server is running on
your own computer
• Port is 3306 for MySQL database
• Data Source is the name of the database from which you want to
manipulate data
• JDBC URL should like that jdbc:mysql://[host_name]:
[port_number]/[name_of_the database]
• In this case our database is world so the url is
jdbc:mysql://localhost:3306/world
• But now we need to select a JDBC Driver
• To add new driver please click on New Driver and follow next
slides

eXenium
Technologies
Configure Execute Query(Cont.)
• In the Driver Name just put any name
• In Description Put some description which is
not a must
• Now Database Drop Down Select MySQL
Database
• Now Click Add Library in this step we add
mysql drive which is a jar file provided in
the execute query folder and the go into lib
folder.
• See the next slide

eXenium
Technologies
Configure Execute Query(Cont.)

Just Click Select You will Just Click save

eXenium
Technologies
Configure Execute Query(Cont.)

Click Find and select the following the click


ok Its Done!

eXenium
Technologies
Configure Execute Query(Cont.)

Click Connect
eXenium
Technologies
Configure Execute Query(Cont.)
You will see a text pane where you can write queries and when you click run
button you will see the output
eXenium
Technologies
Select Statement

 Entering into a db
 use <name of db>;
 Ex. use test;
 See tables
 show tables;
 Select the whole table
 SELECT * FROM <Table Name>;
 Ex. SELECT * FROM item;

eXenium
Technologies
Select Statement (Cont.)

 Simple from

SELECT ‘Hello, World’;


 It doesn't querying a dB just show the values

 Show every thing of a table


 SELECT * FROM Country;
 * means all the columns
 Using functions with Select
 SELECT COUNT(*) FROM Country;

eXenium
Technologies
Select Statement (Cont.)

KEYWORD DESCRIPTION

SELECT Fundamental Statement For Queries

FROM Provides Table for Select Statement

COUNT() Function - COUNT()s values

eXenium
Technologies
Select Statement (Cont.)

 Show specific columns of a table


 SELECT Name, LifeExpectancy FROM Country;
 Showing specific columns of a table changing there heading
 SELECT Name As Country, LifeExpectancy As ‘Life Expectancy ’ FROM Country;
 ‘Life Expectancy ’ (Here ‘’ is needed because this name include space. MySQL may
thing that Expectancy is another statement)

eXenium
Technologies
Select Statement (Cont.)

 Using where
 SELECT Name, Continent, Region FROM Country WHERE Continent = 'Europe';

KEYWORD DESCRIPTION

SELECT Fundamental Statement For Queries

FROM Provides Table for Select Statement

WHERE Provides Filter Condition for SELECT


eXenium
Technologies
Select Statement (Cont.)

 Counting all the rows of a table


 SELECT COUNT(*) FROM Country;
 Counting all the rows of a specific column
 SELECT COUNT(IndepYear) FROM Country;
 Check IndepYear Column
 SELECT IndepYear FROM Country;
 Counting The Countries in Each continent
 SELECT Continent, count(Name) AS Countries FROM Country GROUP BY
Continent;

eXenium
Technologies
Select Statement (Cont.)
KEYWORD DESCRIPTION

SELECT Fundamental Statement For Queries

FROM Provides Table for Select Statement

WHERE Provides Filter Condition for SELECT

COUNT() Function - COUNT()s values

AS Alias Operator

GROUP BY Groups rows for aggregate Functions

eXenium
Technologies
DATABASES AND TABLES

 DATABASES: A collection of tables


 TABLES: A set of data, organized in rows and columns
 Tables may have relationships to other tables

eXenium
Technologies
SQL SYNTEX
 Vendor specific
 SQL Quires consists of clauses an expressions

eXenium
Technologies
SQL SYNTEX(Cont.)

eXenium
Technologies
Inserting DATA

 Insert a record
INSERT INTO
customer
(name, address, city, state, zip )
VALUES
('Shahriar Robbani', 'Shantibag', 'DH', 'DH', '1219');
 Show the customers
 SELECT * FROM customer;

eXenium
Technologies
Join Query

 A Complex Query
SELECT c.Name AS Country, c.Continent, ct.Name AS Capital
FROM Country AS c
JOIN City AS ct
ON ct.ID = c.Capital
ORDER BY Country;

eXenium
Technologies
Join Query

 An Older way to JOIN


SELECT c.Name AS Country, c.Continent, ct.Name AS Capital
FROM Country AS c, City AS ct
WHERE ct.ID = c.Capital
ORDER BY Country;

eXenium
Technologies
Different SQL JOINs

 INNER JOIN: Returns all rows when there is at least one match in BOTH tables

 LEFT JOIN: Return all rows from the left table, and the matched rows from the right table

 RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table

 FULL JOIN: Return all rows when there is a match in ONE of the tables

eXenium
Technologies
SQL INNER JOIN
 SQL INNER JOIN Keyword
 The INNER JOIN keyword selects all rows from both tables as long as there is a match between
the columns in both tables.
 SQL INNER JOIN Syntax
 SELECT column_name(s)
SELECT Customers.CustomerName,
FROM table1
INNER JOIN table2
Orders.OrderID
ON table1.column_name=table2.column_name;
 or: FROM Customers
 SELECT column_name(s)
INNER JOIN Orders
FROM table1
JOIN table2
ON Customers.CustomerID=Orders.CustomerID
ON table1.column_name=table2.column_name;
 INNER JOIN is the same as JOIN. ORDER BY Customers.CustomerName;
eXenium
Technologies
SQL LEFT JOIN
 The LEFT JOIN keyword returns all rows from the left table (table1), with the matching rows in the
right table (table2). The result is NULL in the right side when there is no match.
 SQL LEFT JOIN Syntax
 SELECT column_name(s)
SELECT Customers.CustomerName,
FROM table1
LEFT JOIN table2 Orders.OrderID
ON table1.column_name=table2.column_name;
FROM Customers
 or:
LEFT JOIN Orders
 SELECT column_name(s)
ON Customers.CustomerID=Orders.CustomerID
FROM table1
LEFT OUTER JOIN table2 ORDER BY Customers.CustomerName;
ON table1.column_name=table2.column_name;
  In some databases LEFT JOIN is called LEFT OUTER JOIN.

eXenium
Technologies
SQL RIGHT JOIN
 The RIGHT JOIN keyword returns all rows from the right table (table2), with the matching rows
in the left table (table1). The result is NULL in the left side when there is no match.
 SQL RIGHT JOIN Syntax
SELECT Orders.OrderID, Employees.FirstName
 SELECT column_name(s)
FROM table1 FROM Orders
RIGHT JOIN table2 RIGHT JOIN Employees
ON table1.column_name=table2.column_name;
ON Orders.EmployeeID=Employees.EmployeeID
 or:
ORDER BY Orders.OrderID;
 SELECT column_name(s)
FROM table1
RIGHT OUTER JOIN table2
ON table1.column_name=table2.column_name;
 In some databases RIGHT JOIN is called RIGHT OUTER JOIN.

eXenium
Technologies
Full Outer Join
 The FULL OUTER JOIN keyword returns all rows from the left table (table1) and from the right
table (table2).
 The FULL OUTER JOIN keyword combines the result of both LEFT and RIGHT joins.
 SQL FULL OUTER JOIN Syntax
 SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name=table2.column_name; SELECT Customers.CustomerName,
Orders.OrderID
FROM Customers
FULL OUTER JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
eXenium
Technologies
Filtering data with WHERE

 A simple example
SELECT CountryCode, Name, Population
FROM City
WHERE CountryCode = 'GBR';
 Another example
SELECT CountryCode, Name, Population
FROM City
WHERE Population >= 5000000;

eXenium
Technologies
Filtering data with LIKE

 Another
SELECT CountryCode, Name, Population
FROM City
WHERE Name LIKE 'Z%';
 It Can Be Like that
SELECT CountryCode, Name, Population
FROM City
WHERE Name LIKE '%Z';

eXenium
Technologies
Filtering data with IN

 It also Can Be Like that


SELECT CountryCode, Name, Population
FROM City
WHERE Name LIKE '%Z%';
 A query that Compares a list
SELECT CountryCode, Name, Population
FROM City
WHERE CountryCode IN ( 'USA', 'CAN', 'MAX' );

eXenium
Technologies
Filtering data with IN

 Adding more specification


SELECT CountryCode, Name, Population
FROM City
WHERE CountryCode IN ( 'USA', 'CAN', 'MAX' )
AND Population >= 5000000;

eXenium
Technologies
Removing duplicates with DISTINCT

 See this first


SELECT GovernmentForm, HeadOfState FROM Country WHERE HeadOfState
LIKE 'Elis%‘;
 Showin result without duplicates
SELECT DISTINCT GovernmentForm, HeadOfState FROM Country WHERE
HeadOfState LIKE 'Elis%';
 Showing all results
SELECT ALL GovernmentForm, HeadOfState FROM Country WHERE
HeadOfState LIKE 'Elis%'

eXenium
Technologies
Some KEYWORDs
KEYWORD DESCRIPTION

SELECT Fundamental Statement For Queries

FROM Provides Table for Select Statement

WHERE Provides Filter Condition for SELECT

Wildcard string operator for where


LIKE
clause
Used with SELECT to remove
DISTINCT
duplications from query
Default behavior, show all duplicates.
ALL
Using ALL has no significances.

eXenium
Technologies
Sorting with ORDER BY

 See that
SELECT Name, District
FROM City
WHERE CountryCode = 'USA';
 Sort the result
SELECT Name, District
FROM City
WHERE CountryCode = 'USA'
ORDER BY Name;

eXenium
Technologies
Sorting with ORDER BY

 Multi level sorting


SELECT Name, District
FROM City
WHERE CountryCode = 'USA'
ORDER BY District, Name;

eXenium
Technologies
Updating Data

 See this
SELECT * FROM track WHERE id = 16;
 Removing the extra character by updating data
UPDATE track SET title = ‘Blue Suede Shoes’ WHERE id = 16;

eXenium
Technologies
Deleting Data

 See this
SELECT * FROM track WHERE id = 70;
 Delete the row
DELETE FROM track WHERE id = 70;

eXenium
Technologies
Creating relationships between tables

eXenium
Technologies
Creating relationships between tables

eXenium
Technologies
Joins

 See that
SELECT SUM(quantity) As Quantity, i.name AS Item
FROM sale AS s
JOIN item AS i ON s.item_id = i.id
GROUP BY i.id;
 Right Join
SELECT SUM(quantity) As Quantity, i.name AS Item
FROM sale AS s
RIGHT JOIN item AS i ON s.item_id = i.id
GROUP BY i.id;
eXenium
Technologies
Joins

 Grouping it
SELECT SUM(quantity) As Quantity, i.name AS Item
FROM sale AS s
RIGHT JOIN item AS i ON s.item_id = i.id
GROUP BY i.id
ORDER BY Quantity;

eXenium
Technologies
Joins

 How many sell to customers and what price?


SELECT s.date, c.name AS Customer, i.name AS Item, s.quantity, s.price
FROM sale AS s
JOIN item AS i ON s.item_id = i.id
JOIN customer AS c ON s.customer_id = c.id
ORDER BY s.date;

eXenium
Technologies
Index

eXenium
Technologies
Index

 Customer Table primery key


CREATE TABLE customer (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
address VARCHAR(255),
city VARCHAR(255),
state CHAR(2),
zip CHAR(10)
);

eXenium
Technologies
Index

 Customer Table with additional index


CREATE TABLE customer (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
address VARCHAR(255),
city VARCHAR(255),
state CHAR(2),
zip CHAR(10),
INDEX(name),
INDEX(zip)
);

eXenium
Technologies
About the string functions

 Simple String
SELECT 'Hellow, World' AS String;
 Another example
SELECT 'helo''s' AS String;
 Concatenating Strings By Function (platform dependent)
SELECT CONCAT('Hello,','World;') AS String;

eXenium
Technologies
Finding the length of a string

 See it
SELECT LENGTH('What is your name?') AS Length;
 Another Example
SELECT title, LENGTH(title) AS 'Length of title' FROM album;

eXenium
Technologies
Substring

 Example 1:
SELECT SUBSTR('Hello, World',1,5) AS String;
 Example 2:
SELECT RIGHT('Hello, World',5) AS String;
 Example 3:
SELECT LEFT('Hello, World',5) AS String;

eXenium
Technologies
Some Keyword

eXenium
Technologies
Trim Function

 See that
SELECT ' four spaces from both side ' AS String;
 Delete all the spaces
SELECT TRIM(' four spaces from both side ') AS String;

eXenium
Technologies
Making strings UPPERCASE and
lowercase
 See that
SELECT title FROM album;
 Now make all of them uppercase
SELECT UPPER(title) AS Title FROM album;
 Now make all of them lowercase
SELECT LOWER(title) AS Title FROM album;

eXenium
Technologies
Some Keys

eXenium
Technologies
When to use numeric functions

 See that
SELECT ABS(-12) AS Absolute;
 Also works with string
SELECT ABS('-12') AS Absolute;
 Undefined Result
SELECT ABS('-x12') AS Absolute;

eXenium
Technologies
Rounding numbers

 Round
SELECT ROUND(5.48,1) AS Rounded_Nimber;
 A Practical Example
SELECT Region, AVG(LifeExpectancy) AS AvgLE,
ROUND(AVG(LifeExpectancy),0) AS RndLE
FROM Country
WHERE LifeExpectancy
GROUP BY Region
ORDER BY AvgLE;

eXenium
Technologies
Integer Divisions and reminders

 Showing album title, track title and duration(number of seconds)


SELECT a.title AS Album, t.title AS Track, t.duration AS Duration
FROM album AS a
JOIN track AS t ON t.album_id = a.id;
 Seconds to time
SELECT a.title AS Album, t.title AS Track, SEC_TO_TIME(t.duration) AS
Duration
FROM album AS a
JOIN track AS t ON t.album_id = a.id;

eXenium
Technologies
Integer Divisions and reminders

 Making a custom function


SELECT a.title AS Album, t.title AS Track,
CONCAT(
t.duration DIV 60,
':',
LPAD ( t.duration MOD 60,2,'0' )
) AS Duration
FROM album AS a
JOIN track AS t ON t.album_id = a.id;
 Some terms
 DIV – integer division
 /-
 MOD returns the remainder
 LPAD is used for padding characters

eXenium
Technologies
Keywords

eXenium
Technologies
Dates and times

eXenium
Technologies
Dates and times

 See Date
SELECT CURDATE() AS Date;
 See Time
SELECT CURTIME() AS Date;
 See Time and Date by NOW()
SELECT NOW() AS Date;
 Adding Dates
SELECT NOW() AS Now, DATE_ADD( NOW(), INTERVAL 2 WEEK ) AS Later;

eXenium
Technologies
Dates and times

 Subtract Dates
SELECT NOW() AS Now, DATE_SUB( NOW(), INTERVAL 2 WEEK ) AS Earlier;

eXenium
Technologies
How aggregates work

 See
SELECT COUNT(*) FROM Country;
Gives You the number of all rows
SELECT COUNT(*) AS Count
FROM Country;
• Gives You the number of all rows in each group of region
SELECT Region, COUNT(*) AS Count
FROM Country
GROUP BY Region
ORDER BY Count, Region;

eXenium
Technologies
Exercise
Region Count
Micronesia/Caribbean 1
British Islands 2
Baltic Countries 3
Antarctica 5

Australia and New Zealand 5


Melanesia 5
North America 5
Southern Africa 5
Micronesia 7
Nordic Countries 7
Northern Africa 7
Central America 8
Eastern Asia 8
Central Africa 9
Western Europe 9
Eastern Europe 10
Polynesia 10
Southeast Asia 11
South America 14

Southern and Central Asia 14


Southern Europe 15
Western Africa 17
Middle East 18
Eastern Africa 20
Caribbean 24
eXenium
Technologies
How aggregates work (Exercise)

eXenium
Technologies
How aggregates work (Solution)

 ANS
SELECT al.title AS Album, COUNT(tr.track_number) Number_of_Tracks FROM
album AS al
JOIN track AS tr ON al.id = tr.album_id
GROUP BY al.title
ORDER BY Number_of_Tracks, Album;

eXenium
Technologies
HAVING

 Using Having
SELECT al.title AS Album, COUNT(tr.track_number) Number_of_Tracks FROM
album AS al
JOIN track AS tr ON al.id = tr.album_id
GROUP BY al.title
HAVING Number_of_Tracks >= 10
ORDER BY Number_of_Tracks, Album;

eXenium
Technologies
How aggregates work

 Aggregates works in group rows rather than individual rows

eXenium
Technologies
Removing duplicates with DISTINCT

 Count the Headofstate


SELECT COUNT(HeadOfState) AS 'Number of HeadOfState' FROM Country;
 Ignoring Duplicates
SELECT COUNT( DISTINCT HeadOfState ) AS 'Number of HeadOfState' FROM
Country;

eXenium
Technologies
Key Words

eXenium
Technologies
Useful Aggregate Functions

 Sum all the values


SELECT SUM(duration) FROM track;
 Second to time
SELECT SEC_TO_TIME(SUM(duration)) FROM track;

eXenium
Technologies
Exercise

eXenium
Technologies
Solution

SELECT a.title Album, SUM(t.duration) AS Duration FROM album AS a


JOIN track AS t ON t.album_id = a.id
GROUP BY Album;
Showing in hr min sec
SELECT a.title Album, SEC_TO_TIME(SUM(t.duration)) AS Duration FROM
album AS a
JOIN track AS t ON t.album_id = a.id
GROUP BY Album;

eXenium
Technologies
AVG

 Making average
SELECT a.title Album, SEC_TO_TIME(AVG(t.duration)) AS Duration FROM
album AS a
JOIN track AS t ON t.album_id = a.id
GROUP BY Album;

eXenium
Technologies
MIN

 Showing Minimum
SELECT a.title Album, SEC_TO_TIME(MIN(t.duration)) AS Duration FROM album
AS a
JOIN track AS t ON t.album_id = a.id
GROUP BY Album;

eXenium
Technologies
MAX

 Showing Minimum
SELECT a.title Album, SEC_TO_TIME(MAX(t.duration)) AS Duration FROM
album AS a
JOIN track AS t ON t.album_id = a.id
GROUP BY Album

eXenium
Technologies
Exercise

eXenium
Technologies
Solution

SELECT c.Name AS Country, cl.Language FROM Country AS c


JOIN CountryLanguage AS cl ON cl.CountryCode = c.Code
ORDER BY Country;

eXenium
Technologies
Keys

eXenium
Technologies
Functions

 Calculating
SELECT 320 / 60;
 Calculating (Only Integer part)
SELECT 320 DIV 60;
 Calculating (Only Decimal Part)
SELECT 320 MOD 60;

eXenium
Technologies
Another Example

 Numeric Functions
SELECT CONCAT_WS(':', duration DIV 60, LPAD(duration MOD 60, 2, '0') )
FROM track;
 Converting Decimal to Hex
SELECT CONV( 125, 10, 16);
 Converting Binary to Decimal
SELECT CONV( 1011110, 2, 10);

eXenium
Technologies
CRC32

 Finding CRC32
SELECT CRC32('Hello, World');
 Covert it to Hex
SELECT HEX(CRC32('Hello, World'));
 Making crc32 of all the header
SELECT title, HEX(CRC32(title)) FROM track;

eXenium
Technologies
Other Functions

 Trigonometric Functions
SELECT PI();
SELECT DEGREES(PI());
SELECT RADIANS(180);
SELECT FORMAT(1000000000,2);
SELECT POW(16,2);
SELECT RAND();
SELECT RAND(5);
SELECT Name, Region FROM Country ORDER BY RAND() LIMIT 10;

eXenium
Technologies
Date and Time

1. SELECT NOW(), UTC_TIMESTAMP();


2. SELECT NOW(), UTC_TIMESTAMP(),NOW()-UTC_TIMESTAMP();
3. SELECT NOW(), UTC_TIMESTAMP(), TIME(NOW()-UTC_TIMESTAMP());
4. SELECT DATEDIFF(NOW(), '2014,9,19');
5. SELECT DATE_FORMAT(NOW(), '%W, %D, %M, %Y');

eXenium
Technologies
Contacting Group Values

1. SELECT Region, GROUP_CONCAT(Name) FROM Country GROUP BY Region;


2. SELECT Region, GROUP_CONCAT(Name ORDER BY Name) FROM Country
GROUP BY Region;
3. SELECT Region, GROUP_CONCAT(Name ORDER BY Name SEPARATOR ' / ')
FROM Country GROUP BY Region;

eXenium
Technologies
Natural Search

CREATE TABLE test.airticles (


id INT AUTO_INCREMENT NOT NULL PRIMARY KEY,
title VARCHAR(255) NOT NULL,
body TEXT NOT NULL,
FULLTEXT(title,body)
);
INSERT INTO airticles (title, body) VALUES ('MYSQL','A database management');
INSERT INTO airticles (title, body) VALUES ('HSQL','A portable java database
management');
INSERT INTO airticles (title, body) VALUES ('DerbySQL','A portable java database
management attacthed with jdk');

eXenium
Technologies

You might also like