SQL

85
SQL USING MYSQL By Shahriar Robbani

description

MYSQL and SQL Language

Transcript of SQL

Page 1: SQL

SQLUSING MYSQL

By Shahriar Robbani

Page 2: SQL

MySQL

• RDBMS• Faster Than File System• Easy to Query• Download Exercise Files– http://

www.mediafire.com/download/aufy14p0gmi3zvg/SQL.zip

Page 3: SQL

Creating and Deleting Database

• Creating a DB– CREATE DATABASE myDB

• Deleting a DB– DROP DATABASE myDB

Page 4: SQL

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

Page 5: SQL

Deleting Table

drop table student;

Page 6: SQL

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

Page 7: SQL

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

Page 8: SQL

Configure Execute Query

• Start the MySQL server• Open Execute Query• Follow the next steps

Page 9: SQL

Configure Execute Query(Cont.)Click on New Connection

Page 10: SQL

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

Page 11: SQL

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

Page 12: SQL

Configure Execute Query(Cont.)

Just Click Select You will Just Click save

Page 13: SQL

Configure Execute Query(Cont.)Click Find and select the following the click ok Its Done!

Page 14: SQL

Configure Execute Query(Cont.)

Click Connect

Page 15: SQL

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

Page 16: SQL

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;

Page 17: SQL

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;

Page 18: SQL

Select Statement (Cont.)

KEYWORD DESCRIPTION

SELECT Fundamental Statement For Queries

FROM Provides Table for Select Statement

COUNT() Function - COUNT()s values

Page 19: SQL

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)

Page 20: SQL

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

Page 21: SQL

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;

Page 22: SQL

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

Page 23: SQL

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

Page 24: SQL

SQL SYNTEX• Vendor specific• SQL Quires consists of clauses an expressions

Page 25: SQL

SQL SYNTEX(Cont.)

Page 26: SQL

Inserting DATA

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

Page 27: SQL

Join Query

• A Complex QuerySELECT 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;

Page 28: SQL

Join Query

• An Older way to JOINSELECT 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;

Page 29: SQL

Filtering data with WHERE

• A simple exampleSELECT CountryCode, Name, Population

FROM City WHERE CountryCode = 'GBR';• Another exampleSELECT CountryCode, Name, Population

FROM City WHERE Population >= 5000000;

Page 30: SQL

Filtering data with LIKE

• AnotherSELECT CountryCode, Name, Population

FROM City WHERE Name LIKE 'Z%';• It Can Be Like thatSELECT CountryCode, Name, Population

FROM City WHERE Name LIKE '%Z';

Page 31: SQL

Filtering data with IN

• It also Can Be Like thatSELECT CountryCode, Name, Population

FROM City WHERE Name LIKE '%Z%';• A query that Compares a listSELECT CountryCode, Name, Population

FROM City WHERE CountryCode IN ( 'USA', 'CAN', 'MAX' );

Page 32: SQL

Filtering data with IN

• Adding more specificationSELECT CountryCode, Name, Population

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

Page 33: SQL

Removing duplicates with DISTINCT

• See this firstSELECT GovernmentForm, HeadOfState FROM Country WHERE HeadOfState LIKE 'Elis%‘;• Showin result without duplicatesSELECT DISTINCT GovernmentForm, HeadOfState FROM Country WHERE HeadOfState LIKE 'Elis%';• Showing all resultsSELECT ALL GovernmentForm, HeadOfState FROM Country WHERE HeadOfState LIKE 'Elis%'

Page 34: SQL

Some KEYWORDs

KEYWORD DESCRIPTION

SELECT Fundamental Statement For Queries

FROM Provides Table for Select Statement

WHERE Provides Filter Condition for SELECT

LIKE Wildcard string operator for where clause

DISTINCT Used with SELECT to remove duplications from query

ALL Default behavior, show all duplicates. Using ALL has no significances.

Page 35: SQL

Sorting with ORDER BY

• See thatSELECT Name, District

FROM City WHERE CountryCode = 'USA';• Sort the resultSELECT Name, District

FROM City WHERE CountryCode = 'USA' ORDER BY Name;

Page 36: SQL

Sorting with ORDER BY

• Multi level sortingSELECT Name, District

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

Page 37: SQL

Updating Data

• See thisSELECT * FROM track WHERE id = 16;• Removing the extra character by updating

dataUPDATE track SET title = ‘Blue Suede Shoes’ WHERE id = 16;

Page 38: SQL

Deleting Data

• See thisSELECT * FROM track WHERE id = 70;• Delete the rowDELETE FROM track WHERE id = 70;

Page 39: SQL

Creating relationships between tables

Page 40: SQL

Creating relationships between tables

Page 41: SQL

Joins

• See thatSELECT 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 JoinSELECT 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;

Page 42: SQL

Joins

• Grouping itSELECT 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;

Page 43: SQL

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;

Page 44: SQL

Index

Page 45: SQL

Index

• Customer Table primery keyCREATE 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));

Page 46: SQL

Index• Customer Table with additional indexCREATE 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));

Page 47: SQL

About the string functions

• Simple StringSELECT 'Hellow, World' AS String;• Another exampleSELECT 'helo''s' AS String;• Concatenating Strings By Function (platform

dependent)SELECT CONCAT('Hello,','World;') AS String;

Page 48: SQL

Finding the length of a string

• See itSELECT LENGTH('What is your name?') AS Length;• Another ExampleSELECT title, LENGTH(title) AS 'Length of title' FROM album;

Page 49: SQL

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;

Page 50: SQL

Some Keyword

Page 51: SQL

Trim Function

• See thatSELECT ' four spaces from both side ' AS String;• Delete all the spacesSELECT TRIM(' four spaces from both side ') AS String;

Page 52: SQL

Making strings UPPERCASE and lowercase

• See thatSELECT title FROM album;• Now make all of them uppercaseSELECT UPPER(title) AS Title FROM album;• Now make all of them lowercaseSELECT LOWER(title) AS Title FROM album;

Page 53: SQL

Some Keys

Page 54: SQL

When to use numeric functions

• See thatSELECT ABS(-12) AS Absolute;• Also works with stringSELECT ABS('-12') AS Absolute;• Undefined ResultSELECT ABS('-x12') AS Absolute;

Page 55: SQL

Rounding numbers

• RoundSELECT ROUND(5.48,1) AS Rounded_Nimber;• A Practical ExampleSELECT Region, AVG(LifeExpectancy) AS AvgLE, ROUND(AVG(LifeExpectancy),0) AS RndLE

FROM Country WHERE LifeExpectancy GROUP BY Region ORDER BY AvgLE;

Page 56: SQL

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 timeSELECT 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;

Page 57: SQL

Integer Divisions and reminders• Making a custom functionSELECT 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

Page 58: SQL

Keywords

Page 59: SQL

Dates and times

Page 60: SQL

Dates and times

• See DateSELECT CURDATE() AS Date;• See TimeSELECT CURTIME() AS Date;• See Time and Date by NOW()SELECT NOW() AS Date;• Adding DatesSELECT NOW() AS Now, DATE_ADD( NOW(), INTERVAL 2 WEEK ) AS Later;

Page 61: SQL

Dates and times

• Subtract DatesSELECT NOW() AS Now, DATE_SUB( NOW(), INTERVAL 2 WEEK ) AS Earlier;

Page 62: SQL

How aggregates work

• SeeSELECT COUNT(*) FROM Country;•Gives You the number of all rowsSELECT COUNT(*) AS Count

FROM Country;• Gives You the number of all rows in each group of regionSELECT Region, COUNT(*) AS Count

FROM Country GROUP BY Region ORDER BY Count, Region;

Page 63: SQL

ExerciseRegion CountMicronesia/Caribbean 1British Islands 2Baltic Countries 3Antarctica 5

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

Southern and Central Asia 14Southern Europe 15Western Africa 17Middle East 18Eastern Africa 20Caribbean 24

Page 64: SQL

How aggregates work (Exercise)

Page 65: SQL

How aggregates work (Solution)

• ANSSELECT 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;

Page 66: SQL

HAVING

• Using HavingSELECT 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;

Page 67: SQL

How aggregates work

• Aggregates works in group rows rather than individual rows

Page 68: SQL

Removing duplicates with DISTINCT

• Count the HeadofstateSELECT COUNT(HeadOfState) AS 'Number of HeadOfState' FROM Country;• Ignoring DuplicatesSELECT COUNT( DISTINCT HeadOfState ) AS 'Number of HeadOfState' FROM Country;

Page 69: SQL

Key Words

Page 70: SQL

Useful Aggregate Functions

• Sum all the valuesSELECT SUM(duration) FROM track;• Second to timeSELECT SEC_TO_TIME(SUM(duration)) FROM track;

Page 71: SQL

Exercise

Page 72: SQL

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 secSELECT 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;

Page 73: SQL

AVG

• Making averageSELECT 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;

Page 74: SQL

MIN

• Showing MinimumSELECT 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;

Page 75: SQL

MAX

• Showing MinimumSELECT 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

Page 76: SQL

Exercise

Page 77: SQL

Solution

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

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

Page 78: SQL

Keys

Page 79: SQL

Functions

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

Page 80: SQL

Another Example

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

Page 81: SQL

CRC32

• Finding CRC32SELECT CRC32('Hello, World');• Covert it to HexSELECT HEX(CRC32('Hello, World'));• Making crc32 of all the headerSELECT title, HEX(CRC32(title)) FROM track;

Page 82: SQL

Other Functions

• Trigonometric FunctionsSELECT 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;

Page 83: SQL

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');

Page 84: SQL

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;

Page 85: SQL

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');