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

La actualidad más candente (20)

Joins in SQL
Joins in SQLJoins in SQL
Joins in SQL
 
SQL - DML and DDL Commands
SQL - DML and DDL CommandsSQL - DML and DDL Commands
SQL - DML and DDL Commands
 
introdution to SQL and SQL functions
introdution to SQL and SQL functionsintrodution to SQL and SQL functions
introdution to SQL and SQL functions
 
Sql and Sql commands
Sql and Sql commandsSql and Sql commands
Sql and Sql commands
 
SQL commands
SQL commandsSQL commands
SQL commands
 
Types Of Join In Sql Server - Join With Example In Sql Server
Types Of Join In Sql Server - Join With Example In Sql ServerTypes Of Join In Sql Server - Join With Example In Sql Server
Types Of Join In Sql Server - Join With Example In Sql Server
 
SQL Join Basic
SQL Join BasicSQL Join Basic
SQL Join Basic
 
Mysql
MysqlMysql
Mysql
 
Getting Started with MySQL I
Getting Started with MySQL IGetting Started with MySQL I
Getting Started with MySQL I
 
MySQL Data types
MySQL Data typesMySQL Data types
MySQL Data types
 
MYSQL
MYSQLMYSQL
MYSQL
 
SQL JOINS
SQL JOINSSQL JOINS
SQL JOINS
 
NESTED SUBQUERY.pptx
NESTED SUBQUERY.pptxNESTED SUBQUERY.pptx
NESTED SUBQUERY.pptx
 
Sql(structured query language)
Sql(structured query language)Sql(structured query language)
Sql(structured query language)
 
Advanced Sql Training
Advanced Sql TrainingAdvanced Sql Training
Advanced Sql Training
 
Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
 
Joins And Its Types
Joins And Its TypesJoins And Its Types
Joins And Its Types
 
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
 
SQL
SQLSQL
SQL
 
SQL Functions and Operators
SQL Functions and OperatorsSQL Functions and Operators
SQL Functions and Operators
 

Destacado

My sql Syntax
My sql SyntaxMy sql Syntax
My sql Syntax
Reka
 
Php File Operations
Php File OperationsPhp File Operations
Php File Operations
mussawir20
 
Complete Sql Server querries
Complete Sql Server querriesComplete Sql Server querries
Complete Sql Server querries
Ibrahim Jutt
 
Prabu's sql quries
Prabu's sql quries Prabu's sql quries
Prabu's sql quries
Prabu Cse
 

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 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 2007
paulguerin
 
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
qiw
 
MySQL Query And Index Tuning
MySQL Query And Index TuningMySQL Query And Index Tuning
MySQL Query And Index Tuning
Manikanda kumar
 
Ms sql server ii
Ms sql server  iiMs sql server  ii
Ms sql server ii
Iblesoft
 

Similar a MySql: Queries (20)

sql statement
sql statementsql statement
sql statement
 
MULTIPLE TABLES
MULTIPLE TABLES MULTIPLE TABLES
MULTIPLE TABLES
 
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
 
0808.pdf
0808.pdf0808.pdf
0808.pdf
 

Más de DataminingTools 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

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Último (20)

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 

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