SlideShare uma empresa Scribd logo
1 de 85
SQL 
USING MYSQL 
By Shahriar Robbani
MySQL 
• RDBMS 
• Faster Than File System 
• Easy to Query 
• Download Exercise Files 
– http://www.mediafire.com/download/aufy14p0g 
mi3zvg/SQL.zip
Creating and Deleting Database 
• Creating a DB 
– CREATE DATABASE myDB 
• Deleting a DB 
– DROP DATABASE myDB
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) 
);
Deleting Table 
drop table student;
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
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
Configure Execute Query 
• Start the MySQL server 
• Open Execute Query 
• Follow the next steps
Configure Execute 
Query(Cont.) 
Click on New Connection
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_num 
ber]/[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
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
Configure Execute Query(Cont.) 
Just Click Select You will Just Click save
Configure Execute Query(Cont.) 
Click Find and select the 
following the click ok Its Done!
Configure Execute Query(Cont.) 
Click Connect
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
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;
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;
Select Statement (Cont.) 
KEYWORD DESCRIPTION 
SELECT Fundamental Statement For Queries 
FROM Provides Table for Select Statement 
COUNT() Function - COUNT()s values
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)
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
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;
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
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
SQL SYNTEX 
• Vendor specific 
• SQL Quires consists of clauses an expressions
SQL SYNTEX(Cont.)
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;
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;
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;
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;
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';
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' 
);
Filtering data with IN 
• Adding more specification 
SELECT CountryCode, Name, Population 
FROM City 
WHERE CountryCode IN ( 'USA', 'CAN', 
'MAX' ) 
AND Population >= 5000000;
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%'
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.
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;
Sorting with ORDER BY 
• Multi level sorting 
SELECT Name, District 
FROM City 
WHERE CountryCode = 'USA' 
ORDER BY District, Name;
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;
Deleting Data 
• See this 
SELECT * FROM track WHERE id = 70; 
• Delete the row 
DELETE FROM track WHERE id = 70;
Creating relationships between tables
Creating relationships between tables
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;
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;
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;
Index
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) 
);
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) 
);
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;
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;
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;
Some Keyword
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;
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;
Some Keys
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;
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;
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;
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
Keywords
Dates and times
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;
Dates and times 
• Subtract Dates 
SELECT NOW() AS Now, DATE_SUB( NOW(), 
INTERVAL 2 WEEK ) AS Earlier;
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;
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
How aggregates work (Exercise)
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;
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;
How aggregates work 
• Aggregates works in group rows rather than 
individual rows
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;
Key Words
Useful Aggregate Functions 
• Sum all the values 
SELECT SUM(duration) FROM track; 
• Second to time 
SELECT SEC_TO_TIME(SUM(duration)) FROM 
track;
Exercise
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;
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;
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;
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
Exercise
Solution 
SELECT c.Name AS Country, cl.Language FROM 
Country AS c 
JOIN CountryLanguage AS cl ON 
cl.CountryCode = c.Code 
ORDER BY Country;
Keys
Functions 
• Calculating 
SELECT 320 / 60; 
• Calculating (Only Integer part) 
SELECT 320 DIV 60; 
• Calculating (Only Decimal Part) 
SELECT 320 MOD 60;
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);
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;
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;
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');
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;
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');

Mais conteĂşdo relacionado

Mais procurados

Mindmap: Oracle to Couchbase for developers
Mindmap: Oracle to Couchbase for developersMindmap: Oracle to Couchbase for developers
Mindmap: Oracle to Couchbase for developersKeshav Murthy
 
PostgreSQL talk, Database 2011 conference
PostgreSQL talk, Database 2011 conferencePostgreSQL talk, Database 2011 conference
PostgreSQL talk, Database 2011 conferenceReuven Lerner
 
Miracle Open World 2011 - XML Index Strategies
Miracle Open World 2011  -  XML Index StrategiesMiracle Open World 2011  -  XML Index Strategies
Miracle Open World 2011 - XML Index StrategiesMarco Gralike
 
MS SQL Database basic
MS SQL Database basicMS SQL Database basic
MS SQL Database basicwali1195189
 
Xml part1
Xml part1  Xml part1
Xml part1 NOHA AW
 
Tips for using Firebird system tables
Tips for using Firebird system tablesTips for using Firebird system tables
Tips for using Firebird system tablesMind The Firebird
 
Episode 6 - DML, Transaction and Error handling in Salesforce
Episode 6 - DML, Transaction and Error handling in SalesforceEpisode 6 - DML, Transaction and Error handling in Salesforce
Episode 6 - DML, Transaction and Error handling in SalesforceJitendra Zaa
 
Xml part2
Xml part2Xml part2
Xml part2NOHA AW
 
Scrap your query boilerplate with specql
Scrap your query boilerplate with specqlScrap your query boilerplate with specql
Scrap your query boilerplate with specqlTatu Tarvainen
 
Xml part3
Xml part3Xml part3
Xml part3NOHA AW
 
Introduction to DBIx::Lite - Kyoto.pm tech talk #2
Introduction to DBIx::Lite - Kyoto.pm tech talk #2Introduction to DBIx::Lite - Kyoto.pm tech talk #2
Introduction to DBIx::Lite - Kyoto.pm tech talk #2Hiroshi Shibamura
 
[Www.pkbulk.blogspot.com]dbms05
[Www.pkbulk.blogspot.com]dbms05[Www.pkbulk.blogspot.com]dbms05
[Www.pkbulk.blogspot.com]dbms05AnusAhmad
 
SQL Server 2008 Portfolio
SQL Server 2008 PortfolioSQL Server 2008 Portfolio
SQL Server 2008 Portfoliolilredlokita
 
Xml part4
Xml part4Xml part4
Xml part4NOHA AW
 
[Www.pkbulk.blogspot.com]dbms02
[Www.pkbulk.blogspot.com]dbms02[Www.pkbulk.blogspot.com]dbms02
[Www.pkbulk.blogspot.com]dbms02AnusAhmad
 
Hadoop Summit EU 2014
Hadoop Summit EU   2014Hadoop Summit EU   2014
Hadoop Summit EU 2014cwensel
 
Introduction to sq lite
Introduction to sq liteIntroduction to sq lite
Introduction to sq litepunu_82
 

Mais procurados (20)

Mindmap: Oracle to Couchbase for developers
Mindmap: Oracle to Couchbase for developersMindmap: Oracle to Couchbase for developers
Mindmap: Oracle to Couchbase for developers
 
PostgreSQL talk, Database 2011 conference
PostgreSQL talk, Database 2011 conferencePostgreSQL talk, Database 2011 conference
PostgreSQL talk, Database 2011 conference
 
Xhtml tags reference
Xhtml tags referenceXhtml tags reference
Xhtml tags reference
 
Miracle Open World 2011 - XML Index Strategies
Miracle Open World 2011  -  XML Index StrategiesMiracle Open World 2011  -  XML Index Strategies
Miracle Open World 2011 - XML Index Strategies
 
MS SQL Database basic
MS SQL Database basicMS SQL Database basic
MS SQL Database basic
 
Xml part1
Xml part1  Xml part1
Xml part1
 
Tips for using Firebird system tables
Tips for using Firebird system tablesTips for using Firebird system tables
Tips for using Firebird system tables
 
Episode 6 - DML, Transaction and Error handling in Salesforce
Episode 6 - DML, Transaction and Error handling in SalesforceEpisode 6 - DML, Transaction and Error handling in Salesforce
Episode 6 - DML, Transaction and Error handling in Salesforce
 
Xml part2
Xml part2Xml part2
Xml part2
 
Scrap your query boilerplate with specql
Scrap your query boilerplate with specqlScrap your query boilerplate with specql
Scrap your query boilerplate with specql
 
Xml part3
Xml part3Xml part3
Xml part3
 
Introduction to DBIx::Lite - Kyoto.pm tech talk #2
Introduction to DBIx::Lite - Kyoto.pm tech talk #2Introduction to DBIx::Lite - Kyoto.pm tech talk #2
Introduction to DBIx::Lite - Kyoto.pm tech talk #2
 
[Www.pkbulk.blogspot.com]dbms05
[Www.pkbulk.blogspot.com]dbms05[Www.pkbulk.blogspot.com]dbms05
[Www.pkbulk.blogspot.com]dbms05
 
SQL Server 2008 Portfolio
SQL Server 2008 PortfolioSQL Server 2008 Portfolio
SQL Server 2008 Portfolio
 
MySQL basics
MySQL basicsMySQL basics
MySQL basics
 
Sql
SqlSql
Sql
 
Xml part4
Xml part4Xml part4
Xml part4
 
[Www.pkbulk.blogspot.com]dbms02
[Www.pkbulk.blogspot.com]dbms02[Www.pkbulk.blogspot.com]dbms02
[Www.pkbulk.blogspot.com]dbms02
 
Hadoop Summit EU 2014
Hadoop Summit EU   2014Hadoop Summit EU   2014
Hadoop Summit EU 2014
 
Introduction to sq lite
Introduction to sq liteIntroduction to sq lite
Introduction to sq lite
 

Destaque

Destaque (16)

Oop lecture9 12
Oop lecture9 12Oop lecture9 12
Oop lecture9 12
 
Oop lecture9 11
Oop lecture9 11Oop lecture9 11
Oop lecture9 11
 
Oop lecture9 13
Oop lecture9 13Oop lecture9 13
Oop lecture9 13
 
Meerkat
MeerkatMeerkat
Meerkat
 
PH301 Socha L
PH301 Socha LPH301 Socha L
PH301 Socha L
 
Cwgd
CwgdCwgd
Cwgd
 
Oop lecture2
Oop lecture2Oop lecture2
Oop lecture2
 
Presentacion viernes 20 [compatibility mode]
Presentacion viernes 20 [compatibility mode]Presentacion viernes 20 [compatibility mode]
Presentacion viernes 20 [compatibility mode]
 
Oop lecture1
Oop lecture1Oop lecture1
Oop lecture1
 
Cwgd
CwgdCwgd
Cwgd
 
Calendario portada
Calendario portadaCalendario portada
Calendario portada
 
ryanair maria louisa
ryanair maria louisaryanair maria louisa
ryanair maria louisa
 
Oop lecture8
Oop lecture8Oop lecture8
Oop lecture8
 
Oop lecture6
Oop lecture6Oop lecture6
Oop lecture6
 
Oop lecture7
Oop lecture7Oop lecture7
Oop lecture7
 
Oop lecture9 10
Oop lecture9 10Oop lecture9 10
Oop lecture9 10
 

Semelhante a SQL

Introduction to SQL (for Chicago Booth MBA technology club)
Introduction to SQL (for Chicago Booth MBA technology club)Introduction to SQL (for Chicago Booth MBA technology club)
Introduction to SQL (for Chicago Booth MBA technology club)Jennifer Berk
 
Tk2323 lecture 7 sql
Tk2323 lecture 7   sql Tk2323 lecture 7   sql
Tk2323 lecture 7 sql MengChun Lam
 
Crash course in sql
Crash course in sqlCrash course in sql
Crash course in sqlMithun Shanbhag
 
Introduction to PostgreSQL
Introduction to PostgreSQLIntroduction to PostgreSQL
Introduction to PostgreSQLJoel Brewer
 
Introduction to SQL
Introduction to SQLIntroduction to SQL
Introduction to SQLMahir Haque
 
SQL Assessment Command Statements
SQL Assessment Command StatementsSQL Assessment Command Statements
SQL Assessment Command StatementsShaun Wilson
 
php basic sql
php basic sqlphp basic sql
php basic sqltumetr1
 
Alasql JavaScript SQL Database Library: User Manual
Alasql JavaScript SQL Database Library: User ManualAlasql JavaScript SQL Database Library: User Manual
Alasql JavaScript SQL Database Library: User ManualAndrey Gershun
 
ms-sql-server-150223140402-conversion-gate02.pptx
ms-sql-server-150223140402-conversion-gate02.pptxms-sql-server-150223140402-conversion-gate02.pptx
ms-sql-server-150223140402-conversion-gate02.pptxYashaswiniSrinivasan1
 
MySQL for beginners
MySQL for beginnersMySQL for beginners
MySQL for beginnersSaeid Zebardast
 
DNN Database Tips & Tricks
DNN Database Tips & TricksDNN Database Tips & Tricks
DNN Database Tips & TricksWill Strohl
 

Semelhante a SQL (20)

Introduction to SQL (for Chicago Booth MBA technology club)
Introduction to SQL (for Chicago Booth MBA technology club)Introduction to SQL (for Chicago Booth MBA technology club)
Introduction to SQL (for Chicago Booth MBA technology club)
 
MS SQL Server
MS SQL ServerMS SQL Server
MS SQL Server
 
Mentor Your Indexes
Mentor Your IndexesMentor Your Indexes
Mentor Your Indexes
 
DB2 Sql Query
DB2 Sql QueryDB2 Sql Query
DB2 Sql Query
 
Tk2323 lecture 7 sql
Tk2323 lecture 7   sql Tk2323 lecture 7   sql
Tk2323 lecture 7 sql
 
IR SQLite Session #1
IR SQLite Session #1IR SQLite Session #1
IR SQLite Session #1
 
Crash course in sql
Crash course in sqlCrash course in sql
Crash course in sql
 
Introduction to PostgreSQL
Introduction to PostgreSQLIntroduction to PostgreSQL
Introduction to PostgreSQL
 
Introduction to SQL
Introduction to SQLIntroduction to SQL
Introduction to SQL
 
Ms sql-server
Ms sql-serverMs sql-server
Ms sql-server
 
SQL(database)
SQL(database)SQL(database)
SQL(database)
 
SQL Assessment Command Statements
SQL Assessment Command StatementsSQL Assessment Command Statements
SQL Assessment Command Statements
 
php basic sql
php basic sqlphp basic sql
php basic sql
 
Alasql JavaScript SQL Database Library: User Manual
Alasql JavaScript SQL Database Library: User ManualAlasql JavaScript SQL Database Library: User Manual
Alasql JavaScript SQL Database Library: User Manual
 
Database
Database Database
Database
 
ms-sql-server-150223140402-conversion-gate02.pptx
ms-sql-server-150223140402-conversion-gate02.pptxms-sql-server-150223140402-conversion-gate02.pptx
ms-sql-server-150223140402-conversion-gate02.pptx
 
MySQL for beginners
MySQL for beginnersMySQL for beginners
MySQL for beginners
 
SQL Inteoduction to SQL manipulating of data
SQL Inteoduction to SQL manipulating of data   SQL Inteoduction to SQL manipulating of data
SQL Inteoduction to SQL manipulating of data
 
Sql server T-sql basics ppt-3
Sql server T-sql basics  ppt-3Sql server T-sql basics  ppt-3
Sql server T-sql basics ppt-3
 
DNN Database Tips & Tricks
DNN Database Tips & TricksDNN Database Tips & Tricks
DNN Database Tips & Tricks
 

Último

"Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ..."Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ...Erbil Polytechnic University
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptSAURABHKUMAR892774
 
System Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingSystem Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingBootNeck1
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
National Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfNational Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfRajuKanojiya4
 
Engineering Drawing section of solid
Engineering Drawing     section of solidEngineering Drawing     section of solid
Engineering Drawing section of solidnamansinghjarodiya
 
Class 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm SystemClass 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm Systemirfanmechengr
 
11. Properties of Liquid Fuels in Energy Engineering.pdf
11. Properties of Liquid Fuels in Energy Engineering.pdf11. Properties of Liquid Fuels in Energy Engineering.pdf
11. Properties of Liquid Fuels in Energy Engineering.pdfHafizMudaserAhmad
 
Internet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptxInternet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptxVelmuruganTECE
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfAsst.prof M.Gokilavani
 
TechTACÂŽ CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTACÂŽ CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTACÂŽ CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTACÂŽ CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catcherssdickerson1
 
Transport layer issues and challenges - Guide
Transport layer issues and challenges - GuideTransport layer issues and challenges - Guide
Transport layer issues and challenges - GuideGOPINATHS437943
 
US Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionUS Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionMebane Rash
 
multiple access in wireless communication
multiple access in wireless communicationmultiple access in wireless communication
multiple access in wireless communicationpanditadesh123
 
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTIONTHE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTIONjhunlian
 
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgUnit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgsaravananr517913
 
Input Output Management in Operating System
Input Output Management in Operating SystemInput Output Management in Operating System
Input Output Management in Operating SystemRashmi Bhat
 
Autonomous emergency braking system (aeb) ppt.ppt
Autonomous emergency braking system (aeb) ppt.pptAutonomous emergency braking system (aeb) ppt.ppt
Autonomous emergency braking system (aeb) ppt.pptbibisarnayak0
 
Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...121011101441
 

Último (20)

"Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ..."Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ...
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.ppt
 
System Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingSystem Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event Scheduling
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
National Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfNational Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdf
 
Engineering Drawing section of solid
Engineering Drawing     section of solidEngineering Drawing     section of solid
Engineering Drawing section of solid
 
Class 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm SystemClass 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm System
 
young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 
11. Properties of Liquid Fuels in Energy Engineering.pdf
11. Properties of Liquid Fuels in Energy Engineering.pdf11. Properties of Liquid Fuels in Energy Engineering.pdf
11. Properties of Liquid Fuels in Energy Engineering.pdf
 
Internet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptxInternet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptx
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
 
TechTACÂŽ CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTACÂŽ CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTACÂŽ CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTACÂŽ CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
 
Transport layer issues and challenges - Guide
Transport layer issues and challenges - GuideTransport layer issues and challenges - Guide
Transport layer issues and challenges - Guide
 
US Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionUS Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of Action
 
multiple access in wireless communication
multiple access in wireless communicationmultiple access in wireless communication
multiple access in wireless communication
 
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTIONTHE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
 
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgUnit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
 
Input Output Management in Operating System
Input Output Management in Operating SystemInput Output Management in Operating System
Input Output Management in Operating System
 
Autonomous emergency braking system (aeb) ppt.ppt
Autonomous emergency braking system (aeb) ppt.pptAutonomous emergency braking system (aeb) ppt.ppt
Autonomous emergency braking system (aeb) ppt.ppt
 
Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...
 

SQL

  • 1. SQL USING MYSQL By Shahriar Robbani
  • 2. MySQL • RDBMS • Faster Than File System • Easy to Query • Download Exercise Files – http://www.mediafire.com/download/aufy14p0g mi3zvg/SQL.zip
  • 3. Creating and Deleting Database • Creating a DB – CREATE DATABASE myDB • Deleting a DB – DROP DATABASE myDB
  • 4. 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) );
  • 5. Deleting Table drop table student;
  • 6. 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
  • 7. 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
  • 8. Configure Execute Query • Start the MySQL server • Open Execute Query • Follow the next steps
  • 9. Configure Execute Query(Cont.) Click on New Connection
  • 10. 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_num ber]/[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
  • 11. 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
  • 12. Configure Execute Query(Cont.) Just Click Select You will Just Click save
  • 13. Configure Execute Query(Cont.) Click Find and select the following the click ok Its Done!
  • 15. 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
  • 16. 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;
  • 17. 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;
  • 18. Select Statement (Cont.) KEYWORD DESCRIPTION SELECT Fundamental Statement For Queries FROM Provides Table for Select Statement COUNT() Function - COUNT()s values
  • 19. 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)
  • 20. 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
  • 21. 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;
  • 22. 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
  • 23. 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
  • 24. SQL SYNTEX • Vendor specific • SQL Quires consists of clauses an expressions
  • 26. 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;
  • 27. 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;
  • 28. 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;
  • 29. 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;
  • 30. 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';
  • 31. 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' );
  • 32. Filtering data with IN • Adding more specification SELECT CountryCode, Name, Population FROM City WHERE CountryCode IN ( 'USA', 'CAN', 'MAX' ) AND Population >= 5000000;
  • 33. 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%'
  • 34. 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.
  • 35. 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;
  • 36. Sorting with ORDER BY • Multi level sorting SELECT Name, District FROM City WHERE CountryCode = 'USA' ORDER BY District, Name;
  • 37. 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;
  • 38. Deleting Data • See this SELECT * FROM track WHERE id = 70; • Delete the row DELETE FROM track WHERE id = 70;
  • 41. 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;
  • 42. 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;
  • 43. 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;
  • 44. Index
  • 45. 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) );
  • 46. 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) );
  • 47. 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;
  • 48. 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;
  • 49. 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;
  • 51. 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;
  • 52. 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;
  • 54. 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;
  • 55. 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;
  • 56. 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;
  • 57. 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
  • 60. 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;
  • 61. Dates and times • Subtract Dates SELECT NOW() AS Now, DATE_SUB( NOW(), INTERVAL 2 WEEK ) AS Earlier;
  • 62. 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;
  • 63. 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
  • 64. How aggregates work (Exercise)
  • 65. 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;
  • 66. 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;
  • 67. How aggregates work • Aggregates works in group rows rather than individual rows
  • 68. 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;
  • 70. Useful Aggregate Functions • Sum all the values SELECT SUM(duration) FROM track; • Second to time SELECT SEC_TO_TIME(SUM(duration)) FROM track;
  • 72. 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;
  • 73. 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;
  • 74. 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;
  • 75. 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
  • 77. Solution SELECT c.Name AS Country, cl.Language FROM Country AS c JOIN CountryLanguage AS cl ON cl.CountryCode = c.Code ORDER BY Country;
  • 78. Keys
  • 79. Functions • Calculating SELECT 320 / 60; • Calculating (Only Integer part) SELECT 320 DIV 60; • Calculating (Only Decimal Part) SELECT 320 MOD 60;
  • 80. 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);
  • 81. 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;
  • 82. 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;
  • 83. 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');
  • 84. 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;
  • 85. 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');