SlideShare una empresa de Scribd logo
1 de 31
MYSQL DATA QUERYING
OVERVIEW Querying data using joins Aggregation functions Creating and using views Using union operator for querying Subqueries.
Querying data using joins 1.INNER JOIN() CROSS JOIN and JOIN types are all similar to INNER JOIN Used to link a table to itself. Ex: consider two tables t1 and t2.
Mysql>select * from t1 inner join t2; (here each row of one table is combined with each row of the other table, this join performs Cartesian product)
(in order to perform inner join based on certain criteria use WHERE clause) Mysql>select t1.*,t2.* from t1 inner join t2 where t1.i1=t2.i2;        (inner join only selects the records which match the condition)
OUTER JOINS (these select even the records which donot satisfy the condition and place a NULL) 1.LEFT JOIN ( this forces the result set to contain a row for every entry selected from the left table, so if there is no match on the right table, we will find NULL in the result set) Mysql>select t1.*,t2.*  from t1 left join t2  on t1.i1=t2.i2;
2.RIGHT JOIN() (this forces the result set to contain a row for every entry selected from the right table, so if there is no match on the left table, we will find NULL) Mysql>select t1.*,t2.* from t1 right join t2 on t1.i1=t2.i2; Mysql>select t1.* from t1 left join t2 on t1.i1=t2.i2 Where t1.i1 ISNULL;  (left join is used to find the records where there is mismatch)
Join can be used for self referencing Ex: consider the emp_mgr table
(employee table can be retrieved separately by performing self join)                         employee_table Mysql>select t1.ssn,t1.name as  e_name from emp_mgr as t1  inner join emp_mgr as t2 on  t2.ssn=t1.mgr_ssn; 
USING UNION FOR QUERYING We can list the combined result set  from  different tables. Ex://suppose we have 2 teams one for quiz and 1 for debate as follows quiz teamdebate team
Mysql>select name,age from quiz               union               select name,age from debate;  (advantage of union: unique values are not repeated, it eleminates duplicate rows by default. To preserve the duplicate rows use UNION ALL)
Aggregate functions  used to perform calculations on a group  of records and return  a single value. Often used with GROUP BY clause of SELECT statement. Some of the aggregate functions are SUM,AVG,MIN,MAX,COUNT etc
Ex:using employee database Mysql>select * from employee;
1.SUM() Returns the sum of the grouped values, Returns 0 if there are no matching values. Mysql>select dept,sum(sal) From employee Group by dept;               2.AVG() Returns the average of the grouped values. Mysql>select avg(sal) average_salary  from employee;           
3.MIN() and MAX() Mysql>select min(sal) MIN,       max(sal) MAX from employee; 4.COUNT() Returns the count of values, here we can use to count the number of employee’s working in the company. Mysq>select count(*) from  Employee;                                 
5.VARIANCE() Mysql>select variance(sal) from employee; 688888888.8889 6.STDDEV() Mysql>select stddev(sal) from employee; 26246.6929
views Views are virtual tables defined in terms of other(base) tables. When the data in the underlying table changes so does the data in the view. But if the definitions in the table changes for ex: if we add new columns to the table then these changes  might not apply for the views created.
Views are updatable which means you can change the underlying table by means of operations on the view only when the view is mapped directly onto a single table view must select only the columns that are simple references to the table columns any operation on the view row must correspond to an operation on a single in the underlying table. no union operators,GROUP BY OR HAVING clauses,aggregate functions  are used in the query.
A simple view is a way to select a subset of a tables columns. Syntax: CREATE VIEW view_name as select_query                check condition; Ex:using employee database if we want to only select the columns name and ssn from the employee table we have to create the view. Mysql> create view vemp as select ssn,name from employee;
Mysql>select * from vemp; We can further get data from the view by querying using WHERE,ORDER BY and other clauses. You can provide column names explicitly by providing the names in closed parenthesis. Mysql> create view vemp (reg,enm) as              select ssn,name from employee;
A view can be used to perform calculations automatically. Mysql>create view exp as select name, timestampdiff(year,date-of-join,’2010-01-01’) as experience from employee; Mysql>select * from exp; View can be defined on multiple tables, which makes it easy to use queries having join conditions.
The select condition used to create the view can be altered using the syntax: ALTER VIEW view_name select_condition Check_condition; The select query used to define the view can be retrieved using the syntax: SHOW CREATE VIEW view_name; To drop the view use the syntax: DROP VIEW view_name;
Setting privileges for the views Privileges can be granted and revoked using any of the following: GRANT CREATE VIEW; GRANT SHOW CREATE VIEW; REVOKE CREATE VIEW; REVOKE SHOW CREATE VIEW;
sub queries Subqueries support one select query to be nested inside the other. Subquery may return a single value,single column,single row or a table depending on the query. Subqueries may be correlated or uncorrelated. Subqueries can be tested using: Comparison operators(=,>,<) EXISTS,NOT EXISTS tests if the result of the subquery is empty. IN,NOT IN tests if the value is present in the set returned by subquery. ALL,ANY compare the value to the values returned.
Subqueries with comparison operators Comparison operators when used with the subqueries,will find all the rows in the outer query which satisfy the particular relationship with the value returned by the subquery. Ex: to select the employee who is least paid we can use the subquery. Mysql>select * from e where  sal=(select min(sal) from e);
Subqueries with IN and NOT IN Used when the subquery returns multiple values. Matches the row whose value is present in the set of values returned by the sub query. Mysql>select * from employee where ssn IN (select mgr_ssn from manager); retrieves the details of all employees who are managers Mysql>select * from employee where ssn NOT IN (select mgr_ssn from manager); retrieves the details of all employees who are not managers
Subqueries with ALL and ANY  Used along with comparison operators. ALL Tests if the comparison value satisfies the particular relationship with all the values returned by the subquery. Mysql>select ssn,name from employee  where  date_of_join <= ALL (select date_of_join from employee); shows that jack is the most experienced working employee.
ANY Tests if the comparison value satisfies the particular relationship with any  value returned by the subquery. Mysql>select ssn,name from  employee where  date_of_join <= ANY(select date_of_join from employee); this returns all the rows because every date_of_join is <= atleast one of the other date including itself
Subqueries with EXISTS and NOT EXISTS Used to test if the subquery returns any row. If it returns any row.EXISTS is true and NOT EXIST is false, it returns 1. Mysql>select EXISTS(select * from employee where ssn=1111111); 0 Mysql>select NOT EXISTS(select * from employee where ssn=1111111); 1
Benefits sub queries ,[object Object],Structured. ,[object Object],Greater ease of manipulation. ,[object Object],indeed  it was the innovation of sub queries  made people call  the early SQL(“structured query language”).
Visit more self help tutorials Pick a tutorial of your choice and browse through it at your own pace. The tutorials section is free, self-guiding and will not involve any additional support. Visit us at www.dataminingtools.net

Más contenido relacionado

La actualidad más candente (20)

The Relational Database Model
The Relational Database ModelThe Relational Database Model
The Relational Database Model
 
Joins in dbms and types
Joins in dbms and typesJoins in dbms and types
Joins in dbms and types
 
RELATIONSHIP IN DBMS.pptx
RELATIONSHIP IN DBMS.pptxRELATIONSHIP IN DBMS.pptx
RELATIONSHIP IN DBMS.pptx
 
Relational model
Relational modelRelational model
Relational model
 
Dbms normalization
Dbms normalizationDbms normalization
Dbms normalization
 
MySql Triggers Tutorial - The Webs Academy
MySql Triggers Tutorial - The Webs AcademyMySql Triggers Tutorial - The Webs Academy
MySql Triggers Tutorial - The Webs Academy
 
Triggers
TriggersTriggers
Triggers
 
Mysql joins
Mysql joinsMysql joins
Mysql joins
 
Normal forms
Normal formsNormal forms
Normal forms
 
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with ExamplesDML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
 
Join
JoinJoin
Join
 
EER modeling
EER modelingEER modeling
EER modeling
 
Relational Algebra,Types of join
Relational Algebra,Types of joinRelational Algebra,Types of join
Relational Algebra,Types of join
 
SQL Views
SQL ViewsSQL Views
SQL Views
 
Data models
Data modelsData models
Data models
 
Inner join and outer join
Inner join and outer joinInner join and outer join
Inner join and outer join
 
Introduction to triggers
Introduction to triggersIntroduction to triggers
Introduction to triggers
 
DBMS - Relational Model
DBMS - Relational ModelDBMS - Relational Model
DBMS - Relational Model
 
MySQL JOIN & UNION
MySQL JOIN & UNIONMySQL JOIN & UNION
MySQL JOIN & UNION
 
Database Normalization
Database NormalizationDatabase Normalization
Database Normalization
 

Destacado

Introducing new SQL syntax and improving performance with preparse Query Rewr...
Introducing new SQL syntax and improving performance with preparse Query Rewr...Introducing new SQL syntax and improving performance with preparse Query Rewr...
Introducing new SQL syntax and improving performance with preparse Query Rewr...Sveta Smirnova
 
My sql Syntax
My sql SyntaxMy sql Syntax
My sql SyntaxReka
 
Even internet computers want to be free: Using Linux and open source software...
Even internet computers want to be free: Using Linux and open source software...Even internet computers want to be free: Using Linux and open source software...
Even internet computers want to be free: Using Linux and open source software...North Bend Public Library
 
Php File Operations
Php File OperationsPhp File Operations
Php File Operationsmussawir20
 
Complete Sql Server querries
Complete Sql Server querriesComplete Sql Server querries
Complete Sql Server querriesIbrahim Jutt
 
Prabu's sql quries
Prabu's sql quries Prabu's sql quries
Prabu's sql quries Prabu Cse
 
PHP Comprehensive Overview
PHP Comprehensive OverviewPHP Comprehensive Overview
PHP Comprehensive OverviewMohamed Loey
 
Different types of Editors in Linux
Different types of Editors in LinuxDifferent types of Editors in Linux
Different types of Editors in LinuxBhavik Trivedi
 
MS SQL SERVER: Microsoft naive bayes algorithm
MS SQL SERVER: Microsoft naive bayes algorithmMS SQL SERVER: Microsoft naive bayes algorithm
MS SQL SERVER: Microsoft naive bayes algorithmDataminingTools Inc
 
MS SQL SERVER: Microsoft sequence clustering and association rules
MS SQL SERVER: Microsoft sequence clustering and association rulesMS SQL SERVER: Microsoft sequence clustering and association rules
MS SQL SERVER: Microsoft sequence clustering and association rulesDataminingTools Inc
 

Destacado (20)

Introducing new SQL syntax and improving performance with preparse Query Rewr...
Introducing new SQL syntax and improving performance with preparse Query Rewr...Introducing new SQL syntax and improving performance with preparse Query Rewr...
Introducing new SQL syntax and improving performance with preparse Query Rewr...
 
My sql Syntax
My sql SyntaxMy sql Syntax
My sql Syntax
 
Even internet computers want to be free: Using Linux and open source software...
Even internet computers want to be free: Using Linux and open source software...Even internet computers want to be free: Using Linux and open source software...
Even internet computers want to be free: Using Linux and open source software...
 
MySQL and its basic commands
MySQL and its basic commandsMySQL and its basic commands
MySQL and its basic commands
 
Php File Operations
Php File OperationsPhp File Operations
Php File Operations
 
Complete Sql Server querries
Complete Sql Server querriesComplete Sql Server querries
Complete Sql Server querries
 
Prabu's sql quries
Prabu's sql quries Prabu's sql quries
Prabu's sql quries
 
PHP Comprehensive Overview
PHP Comprehensive OverviewPHP Comprehensive Overview
PHP Comprehensive Overview
 
Php ppt
Php pptPhp ppt
Php ppt
 
Vi Editor
Vi EditorVi Editor
Vi Editor
 
php
phpphp
php
 
Vi editor
Vi editorVi editor
Vi editor
 
Mysql ppt
Mysql pptMysql ppt
Mysql ppt
 
Vi editor in linux
Vi editor in linuxVi editor in linux
Vi editor in linux
 
Different types of Editors in Linux
Different types of Editors in LinuxDifferent types of Editors in Linux
Different types of Editors in Linux
 
Txomin Hartz Txikia
Txomin Hartz TxikiaTxomin Hartz Txikia
Txomin Hartz Txikia
 
MS SQL SERVER: Microsoft naive bayes algorithm
MS SQL SERVER: Microsoft naive bayes algorithmMS SQL SERVER: Microsoft naive bayes algorithm
MS SQL SERVER: Microsoft naive bayes algorithm
 
How To Make Pb J
How To Make Pb JHow To Make Pb J
How To Make Pb J
 
MS SQL SERVER: Microsoft sequence clustering and association rules
MS SQL SERVER: Microsoft sequence clustering and association rulesMS SQL SERVER: Microsoft sequence clustering and association rules
MS SQL SERVER: Microsoft sequence clustering and association rules
 
Data Mining The Sky
Data Mining The SkyData Mining The Sky
Data Mining The Sky
 

Similar a MySql: Queries

sql statement
sql statementsql statement
sql statementzx25 zx25
 
Advanced Sql Training
Advanced Sql TrainingAdvanced Sql Training
Advanced Sql Trainingbixxman
 
Sql server ___________session_16(views)
Sql server  ___________session_16(views)Sql server  ___________session_16(views)
Sql server ___________session_16(views)Ehtisham Ali
 
Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007paulguerin
 
Aggregate Functions,Final
Aggregate Functions,FinalAggregate Functions,Final
Aggregate Functions,Finalmukesh24pandey
 
PHP mysql Aggregate functions
PHP mysql Aggregate functionsPHP mysql Aggregate functions
PHP mysql Aggregate functionsMudasir Syed
 
Bt0075 rdbms with mysql 2
Bt0075 rdbms with mysql 2Bt0075 rdbms with mysql 2
Bt0075 rdbms with mysql 2Techglyphs
 
Its about a sql topic for basic structured query language
Its about a sql topic for basic structured query languageIts about a sql topic for basic structured query language
Its about a sql topic for basic structured query languageIMsKanchanaI
 
Twp Upgrading 10g To 11g What To Expect From Optimizer
Twp Upgrading 10g To 11g What To Expect From OptimizerTwp Upgrading 10g To 11g What To Expect From Optimizer
Twp Upgrading 10g To 11g What To Expect From Optimizerqiw
 
Data Manipulation Language.pptx
Data Manipulation Language.pptxData Manipulation Language.pptx
Data Manipulation Language.pptxEllenGracePorras
 
MySQL Query And Index Tuning
MySQL Query And Index TuningMySQL Query And Index Tuning
MySQL Query And Index TuningManikanda kumar
 
Ms sql server ii
Ms sql server  iiMs sql server  ii
Ms sql server iiIblesoft
 

Similar a MySql: Queries (20)

sql statement
sql statementsql statement
sql statement
 
MULTIPLE TABLES
MULTIPLE TABLES MULTIPLE TABLES
MULTIPLE TABLES
 
Advanced Sql Training
Advanced Sql TrainingAdvanced Sql Training
Advanced Sql Training
 
Sql server ___________session_16(views)
Sql server  ___________session_16(views)Sql server  ___________session_16(views)
Sql server ___________session_16(views)
 
Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007
 
ADVANCED MODELLING.pptx
ADVANCED MODELLING.pptxADVANCED MODELLING.pptx
ADVANCED MODELLING.pptx
 
Aggregate Functions,Final
Aggregate Functions,FinalAggregate Functions,Final
Aggregate Functions,Final
 
Module03
Module03Module03
Module03
 
PHP mysql Aggregate functions
PHP mysql Aggregate functionsPHP mysql Aggregate functions
PHP mysql Aggregate functions
 
Bt0075 rdbms with mysql 2
Bt0075 rdbms with mysql 2Bt0075 rdbms with mysql 2
Bt0075 rdbms with mysql 2
 
Its about a sql topic for basic structured query language
Its about a sql topic for basic structured query languageIts about a sql topic for basic structured query language
Its about a sql topic for basic structured query language
 
Twp Upgrading 10g To 11g What To Expect From Optimizer
Twp Upgrading 10g To 11g What To Expect From OptimizerTwp Upgrading 10g To 11g What To Expect From Optimizer
Twp Upgrading 10g To 11g What To Expect From Optimizer
 
Data Manipulation Language.pptx
Data Manipulation Language.pptxData Manipulation Language.pptx
Data Manipulation Language.pptx
 
Les18
Les18Les18
Les18
 
SQL
SQLSQL
SQL
 
SAS Proc SQL
SAS Proc SQLSAS Proc SQL
SAS Proc SQL
 
MySQL Query And Index Tuning
MySQL Query And Index TuningMySQL Query And Index Tuning
MySQL Query And Index Tuning
 
Ms sql server ii
Ms sql server  iiMs sql server  ii
Ms sql server ii
 
5. Group Functions
5. Group Functions5. Group Functions
5. Group Functions
 
Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
 

Más de DataminingTools Inc

AI: Introduction to artificial intelligence
AI: Introduction to artificial intelligenceAI: Introduction to artificial intelligence
AI: Introduction to artificial intelligenceDataminingTools Inc
 
Data Mining: Text and web mining
Data Mining: Text and web miningData Mining: Text and web mining
Data Mining: Text and web miningDataminingTools Inc
 
Data Mining: Mining stream time series and sequence data
Data Mining: Mining stream time series and sequence dataData Mining: Mining stream time series and sequence data
Data Mining: Mining stream time series and sequence dataDataminingTools Inc
 
Data Mining: Mining ,associations, and correlations
Data Mining: Mining ,associations, and correlationsData Mining: Mining ,associations, and correlations
Data Mining: Mining ,associations, and correlationsDataminingTools Inc
 
Data Mining: Graph mining and social network analysis
Data Mining: Graph mining and social network analysisData Mining: Graph mining and social network analysis
Data Mining: Graph mining and social network analysisDataminingTools Inc
 
Data warehouse and olap technology
Data warehouse and olap technologyData warehouse and olap technology
Data warehouse and olap technologyDataminingTools Inc
 

Más de DataminingTools Inc (20)

Terminology Machine Learning
Terminology Machine LearningTerminology Machine Learning
Terminology Machine Learning
 
Techniques Machine Learning
Techniques Machine LearningTechniques Machine Learning
Techniques Machine Learning
 
Machine learning Introduction
Machine learning IntroductionMachine learning Introduction
Machine learning Introduction
 
Areas of machine leanring
Areas of machine leanringAreas of machine leanring
Areas of machine leanring
 
AI: Planning and AI
AI: Planning and AIAI: Planning and AI
AI: Planning and AI
 
AI: Logic in AI 2
AI: Logic in AI 2AI: Logic in AI 2
AI: Logic in AI 2
 
AI: Logic in AI
AI: Logic in AIAI: Logic in AI
AI: Logic in AI
 
AI: Learning in AI 2
AI: Learning in AI 2AI: Learning in AI 2
AI: Learning in AI 2
 
AI: Learning in AI
AI: Learning in AI AI: Learning in AI
AI: Learning in AI
 
AI: Introduction to artificial intelligence
AI: Introduction to artificial intelligenceAI: Introduction to artificial intelligence
AI: Introduction to artificial intelligence
 
AI: Belief Networks
AI: Belief NetworksAI: Belief Networks
AI: Belief Networks
 
AI: AI & Searching
AI: AI & SearchingAI: AI & Searching
AI: AI & Searching
 
AI: AI & Problem Solving
AI: AI & Problem SolvingAI: AI & Problem Solving
AI: AI & Problem Solving
 
Data Mining: Text and web mining
Data Mining: Text and web miningData Mining: Text and web mining
Data Mining: Text and web mining
 
Data Mining: Outlier analysis
Data Mining: Outlier analysisData Mining: Outlier analysis
Data Mining: Outlier analysis
 
Data Mining: Mining stream time series and sequence data
Data Mining: Mining stream time series and sequence dataData Mining: Mining stream time series and sequence data
Data Mining: Mining stream time series and sequence data
 
Data Mining: Mining ,associations, and correlations
Data Mining: Mining ,associations, and correlationsData Mining: Mining ,associations, and correlations
Data Mining: Mining ,associations, and correlations
 
Data Mining: Graph mining and social network analysis
Data Mining: Graph mining and social network analysisData Mining: Graph mining and social network analysis
Data Mining: Graph mining and social network analysis
 
Data warehouse and olap technology
Data warehouse and olap technologyData warehouse and olap technology
Data warehouse and olap technology
 
Data Mining: Data processing
Data Mining: Data processingData Mining: Data processing
Data Mining: Data processing
 

Último

EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 

Último (20)

EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 

MySql: Queries

  • 2. OVERVIEW Querying data using joins Aggregation functions Creating and using views Using union operator for querying Subqueries.
  • 3. Querying data using joins 1.INNER JOIN() CROSS JOIN and JOIN types are all similar to INNER JOIN Used to link a table to itself. Ex: consider two tables t1 and t2.
  • 4. Mysql>select * from t1 inner join t2; (here each row of one table is combined with each row of the other table, this join performs Cartesian product)
  • 5. (in order to perform inner join based on certain criteria use WHERE clause) Mysql>select t1.*,t2.* from t1 inner join t2 where t1.i1=t2.i2;  (inner join only selects the records which match the condition)
  • 6. OUTER JOINS (these select even the records which donot satisfy the condition and place a NULL) 1.LEFT JOIN ( this forces the result set to contain a row for every entry selected from the left table, so if there is no match on the right table, we will find NULL in the result set) Mysql>select t1.*,t2.* from t1 left join t2 on t1.i1=t2.i2;
  • 7. 2.RIGHT JOIN() (this forces the result set to contain a row for every entry selected from the right table, so if there is no match on the left table, we will find NULL) Mysql>select t1.*,t2.* from t1 right join t2 on t1.i1=t2.i2; Mysql>select t1.* from t1 left join t2 on t1.i1=t2.i2 Where t1.i1 ISNULL; (left join is used to find the records where there is mismatch)
  • 8. Join can be used for self referencing Ex: consider the emp_mgr table
  • 9. (employee table can be retrieved separately by performing self join) employee_table Mysql>select t1.ssn,t1.name as e_name from emp_mgr as t1 inner join emp_mgr as t2 on t2.ssn=t1.mgr_ssn; 
  • 10. USING UNION FOR QUERYING We can list the combined result set from different tables. Ex://suppose we have 2 teams one for quiz and 1 for debate as follows quiz teamdebate team
  • 11. Mysql>select name,age from quiz union select name,age from debate;  (advantage of union: unique values are not repeated, it eleminates duplicate rows by default. To preserve the duplicate rows use UNION ALL)
  • 12. Aggregate functions used to perform calculations on a group of records and return a single value. Often used with GROUP BY clause of SELECT statement. Some of the aggregate functions are SUM,AVG,MIN,MAX,COUNT etc
  • 13. Ex:using employee database Mysql>select * from employee;
  • 14. 1.SUM() Returns the sum of the grouped values, Returns 0 if there are no matching values. Mysql>select dept,sum(sal) From employee Group by dept;  2.AVG() Returns the average of the grouped values. Mysql>select avg(sal) average_salary from employee; 
  • 15. 3.MIN() and MAX() Mysql>select min(sal) MIN,  max(sal) MAX from employee; 4.COUNT() Returns the count of values, here we can use to count the number of employee’s working in the company. Mysq>select count(*) from Employee; 
  • 16. 5.VARIANCE() Mysql>select variance(sal) from employee; 688888888.8889 6.STDDEV() Mysql>select stddev(sal) from employee; 26246.6929
  • 17. views Views are virtual tables defined in terms of other(base) tables. When the data in the underlying table changes so does the data in the view. But if the definitions in the table changes for ex: if we add new columns to the table then these changes might not apply for the views created.
  • 18. Views are updatable which means you can change the underlying table by means of operations on the view only when the view is mapped directly onto a single table view must select only the columns that are simple references to the table columns any operation on the view row must correspond to an operation on a single in the underlying table. no union operators,GROUP BY OR HAVING clauses,aggregate functions are used in the query.
  • 19. A simple view is a way to select a subset of a tables columns. Syntax: CREATE VIEW view_name as select_query check condition; Ex:using employee database if we want to only select the columns name and ssn from the employee table we have to create the view. Mysql> create view vemp as select ssn,name from employee;
  • 20. Mysql>select * from vemp; We can further get data from the view by querying using WHERE,ORDER BY and other clauses. You can provide column names explicitly by providing the names in closed parenthesis. Mysql> create view vemp (reg,enm) as select ssn,name from employee;
  • 21. A view can be used to perform calculations automatically. Mysql>create view exp as select name, timestampdiff(year,date-of-join,’2010-01-01’) as experience from employee; Mysql>select * from exp; View can be defined on multiple tables, which makes it easy to use queries having join conditions.
  • 22. The select condition used to create the view can be altered using the syntax: ALTER VIEW view_name select_condition Check_condition; The select query used to define the view can be retrieved using the syntax: SHOW CREATE VIEW view_name; To drop the view use the syntax: DROP VIEW view_name;
  • 23. Setting privileges for the views Privileges can be granted and revoked using any of the following: GRANT CREATE VIEW; GRANT SHOW CREATE VIEW; REVOKE CREATE VIEW; REVOKE SHOW CREATE VIEW;
  • 24. sub queries Subqueries support one select query to be nested inside the other. Subquery may return a single value,single column,single row or a table depending on the query. Subqueries may be correlated or uncorrelated. Subqueries can be tested using: Comparison operators(=,>,<) EXISTS,NOT EXISTS tests if the result of the subquery is empty. IN,NOT IN tests if the value is present in the set returned by subquery. ALL,ANY compare the value to the values returned.
  • 25. Subqueries with comparison operators Comparison operators when used with the subqueries,will find all the rows in the outer query which satisfy the particular relationship with the value returned by the subquery. Ex: to select the employee who is least paid we can use the subquery. Mysql>select * from e where sal=(select min(sal) from e);
  • 26. Subqueries with IN and NOT IN Used when the subquery returns multiple values. Matches the row whose value is present in the set of values returned by the sub query. Mysql>select * from employee where ssn IN (select mgr_ssn from manager); retrieves the details of all employees who are managers Mysql>select * from employee where ssn NOT IN (select mgr_ssn from manager); retrieves the details of all employees who are not managers
  • 27. Subqueries with ALL and ANY Used along with comparison operators. ALL Tests if the comparison value satisfies the particular relationship with all the values returned by the subquery. Mysql>select ssn,name from employee where date_of_join <= ALL (select date_of_join from employee); shows that jack is the most experienced working employee.
  • 28. ANY Tests if the comparison value satisfies the particular relationship with any value returned by the subquery. Mysql>select ssn,name from employee where date_of_join <= ANY(select date_of_join from employee); this returns all the rows because every date_of_join is <= atleast one of the other date including itself
  • 29. Subqueries with EXISTS and NOT EXISTS Used to test if the subquery returns any row. If it returns any row.EXISTS is true and NOT EXIST is false, it returns 1. Mysql>select EXISTS(select * from employee where ssn=1111111); 0 Mysql>select NOT EXISTS(select * from employee where ssn=1111111); 1
  • 30.
  • 31. Visit more self help tutorials Pick a tutorial of your choice and browse through it at your own pace. The tutorials section is free, self-guiding and will not involve any additional support. Visit us at www.dataminingtools.net