SlideShare a Scribd company logo
MYSQL DATA QUERYING
OVERVIEWQuerying data using joinsAggregation functionsCreating and using viewsUsing union operator for queryingSubqueries.
Querying data using joins1.INNER JOIN()CROSS JOIN and JOIN types are all similar to INNER JOINUsed 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.i2Where t1.i1 ISNULL; (left join is used to find the records where there is mismatch)
Join can be used for self referencingEx: consider the emp_mgr table
(employee table can be retrieved separately byperforming self join)                         employee_tableMysql>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 QUERYINGWe can list the combined result set  from  differenttables.Ex://suppose we have 2 teams one for quiz and 1 for debate as followsquiz 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  ofrecords and return  a single value.Often used with GROUP BY clause of SELECTstatement.Some of the aggregate functions areSUM,AVG,MIN,MAX,COUNT etc
Ex:using employee databaseMysql>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 employeeGroup 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.88896.STDDEV()Mysql>select stddev(sal) from employee;26246.6929
viewsViews are virtual tables defined in terms of other(base) tables.When the data in the underlying table changes so doesthe data in the view.But if the definitions in the table changes for ex: if weadd 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 whenthe view is mapped directly onto a single tableview must select only the columns that are simple references to the table columnsany 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 databaseif 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_conditionCheck_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 viewsPrivileges 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 queriesSubqueries 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 operatorsComparison 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 INUsed 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 managersMysql>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.ALLTests if the comparison value satisfies the particularrelationship with all the values returned by thesubquery.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.
ANYTests if the comparison value satisfies theparticular relationship with any  valuereturned 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 EXISTSUsed to test if the subquery returns any row.If it returns any row.EXISTS is true and NOT EXISTis false, it returns 1.Mysql>select EXISTS(select * from employee where ssn=1111111);0Mysql>select NOT EXISTS(select * from employee where ssn=1111111);1
Benefits sub queriesmakes the query more Structured.reduced data redundancy and  Greater ease of manipulation.sub queries  are more readable than joins or unions, indeed  it was the innovation of sub queries  made people call  the early SQL(“structured query language”).
Visit more self help tutorialsPick 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

More Related Content

What's hot (20)

PPTX
Sql subquery
Raveena Thakur
 
PPT
Sql basics and DDL statements
Mohd Tousif
 
PPT
Data Mining with WEKA WEKA
butest
 
PPT
Joins in SQL
Vigneshwaran Sankaran
 
PPTX
MySQL Basics
mysql content
 
PPTX
07.03 cartesian product
Bishal Ghimire
 
PPTX
SQL Queries Information
Nishant Munjal
 
PPTX
Relational Algebra,Types of join
raj upadhyay
 
PPTX
String function in my sql
knowledgemart
 
PDF
Developing and Deploying Apps with the Postgres FDW
Jonathan Katz
 
PPTX
SQL Server Learning Drive
TechandMate
 
PPTX
Oracle: Functions
oracle content
 
PPTX
MS Sql Server: Joining Databases
DataminingTools Inc
 
PPT
SQL Queries
Nilt1234
 
PPT
MySQL Transactions
Reggie Niccolo Santos
 
PPTX
Parameters in Tableau
Kanika Nagpal
 
PPTX
Data Structure and Algorithms
Sumathi MathanMohan
 
PPTX
Introduction-to-Power-Pivot-in-Excel.pptx
Anupama Kate
 
PPTX
Stored procedure in sql server
baabtra.com - No. 1 supplier of quality freshers
 
PDF
Tutorial On Database Management System
psathishcs
 
Sql subquery
Raveena Thakur
 
Sql basics and DDL statements
Mohd Tousif
 
Data Mining with WEKA WEKA
butest
 
Joins in SQL
Vigneshwaran Sankaran
 
MySQL Basics
mysql content
 
07.03 cartesian product
Bishal Ghimire
 
SQL Queries Information
Nishant Munjal
 
Relational Algebra,Types of join
raj upadhyay
 
String function in my sql
knowledgemart
 
Developing and Deploying Apps with the Postgres FDW
Jonathan Katz
 
SQL Server Learning Drive
TechandMate
 
Oracle: Functions
oracle content
 
MS Sql Server: Joining Databases
DataminingTools Inc
 
SQL Queries
Nilt1234
 
MySQL Transactions
Reggie Niccolo Santos
 
Parameters in Tableau
Kanika Nagpal
 
Data Structure and Algorithms
Sumathi MathanMohan
 
Introduction-to-Power-Pivot-in-Excel.pptx
Anupama Kate
 
Stored procedure in sql server
baabtra.com - No. 1 supplier of quality freshers
 
Tutorial On Database Management System
psathishcs
 

Viewers also liked (20)

PDF
Introducing new SQL syntax and improving performance with preparse Query Rewr...
Sveta Smirnova
 
ODP
My sql Syntax
Reka
 
ODP
Even internet computers want to be free: Using Linux and open source software...
North Bend Public Library
 
PPT
MySQL and its basic commands
Bwsrang Basumatary
 
PPT
Php File Operations
mussawir20
 
DOC
Complete Sql Server querries
Ibrahim Jutt
 
ODP
Prabu's sql quries
Prabu Cse
 
PPSX
PHP Comprehensive Overview
Mohamed Loey
 
PPT
Php ppt
Sanmuga Nathan
 
PDF
Vi Editor
Shiwang Kalkhanda
 
PPTX
Vi editor
Er Mittinpreet Singh
 
PPT
Mysql ppt
Sanmuga Nathan
 
PPT
Vi editor in linux
Bhumivaghasiya
 
PPTX
Different types of Editors in Linux
Bhavik Trivedi
 
PPTX
Txomin Hartz Txikia
irantzugoitia86
 
PPTX
MS SQL SERVER: Microsoft naive bayes algorithm
DataminingTools Inc
 
PPT
How To Make Pb J
spencer shanks
 
PPTX
MS SQL SERVER: Microsoft sequence clustering and association rules
DataminingTools Inc
 
PPTX
Data Mining The Sky
DataminingTools Inc
 
Introducing new SQL syntax and improving performance with preparse Query Rewr...
Sveta Smirnova
 
My sql Syntax
Reka
 
Even internet computers want to be free: Using Linux and open source software...
North Bend Public Library
 
MySQL and its basic commands
Bwsrang Basumatary
 
Php File Operations
mussawir20
 
Complete Sql Server querries
Ibrahim Jutt
 
Prabu's sql quries
Prabu Cse
 
PHP Comprehensive Overview
Mohamed Loey
 
Mysql ppt
Sanmuga Nathan
 
Vi editor in linux
Bhumivaghasiya
 
Different types of Editors in Linux
Bhavik Trivedi
 
Txomin Hartz Txikia
irantzugoitia86
 
MS SQL SERVER: Microsoft naive bayes algorithm
DataminingTools Inc
 
How To Make Pb J
spencer shanks
 
MS SQL SERVER: Microsoft sequence clustering and association rules
DataminingTools Inc
 
Data Mining The Sky
DataminingTools Inc
 
Ad

Similar to MySql: Queries (20)

PPTX
MySqL_n.pptx edshdshfbhjbdhcbjdchdchjcdbbjd
aidenreji
 
PPTX
View od dffmfmfmm,dm,f,dm,dfm,dddfdfsd,sd,sddf,df,ldf
talhahakeem295
 
ODP
BIS05 Introduction to SQL
Prithwis Mukerjee
 
PPTX
SQL Joins and View.pptx
pallavipatil634279
 
PDF
Sql cheat-sheet
Steve Tran
 
PDF
Chapter9 more on database and sql
KV(AFS) Utarlai, Barmer (Rajasthan)
 
PPTX
MULTIPLE TABLES
ASHABOOPATHY
 
PPTX
Data Manipulation Language.pptx
EllenGracePorras
 
PPTX
1. dml select statement reterive data
Amrit Kaur
 
PPT
Oracle tips and tricks
Yanli Liu
 
PPTX
Subqueries, Backups, Users and Privileges
Ashwin Dinoriya
 
PPTX
OracleSQLraining.pptx
Rajendra Jain
 
PPTX
SQL
Siti Ismail
 
PPT
Module03
Sridhar P
 
DOCX
Database object, sub query, Join Commands & Lab Assignment
Arun Sial
 
DOC
ORACLE NOTES
Sachin Shukla
 
PPTX
Interactive SQL and Advance SQL SQL Performance Tuning.pptx
ssuserb8d5cb
 
PPTX
askndmf,dskmlf,bvdmk,v nmdsvjkmc,dvjkcmsdcvjnkmd
talhahakeem295
 
PPT
Mssql
Janas Khan
 
MySqL_n.pptx edshdshfbhjbdhcbjdchdchjcdbbjd
aidenreji
 
View od dffmfmfmm,dm,f,dm,dfm,dddfdfsd,sd,sddf,df,ldf
talhahakeem295
 
BIS05 Introduction to SQL
Prithwis Mukerjee
 
SQL Joins and View.pptx
pallavipatil634279
 
Sql cheat-sheet
Steve Tran
 
Chapter9 more on database and sql
KV(AFS) Utarlai, Barmer (Rajasthan)
 
MULTIPLE TABLES
ASHABOOPATHY
 
Data Manipulation Language.pptx
EllenGracePorras
 
1. dml select statement reterive data
Amrit Kaur
 
Oracle tips and tricks
Yanli Liu
 
Subqueries, Backups, Users and Privileges
Ashwin Dinoriya
 
OracleSQLraining.pptx
Rajendra Jain
 
Module03
Sridhar P
 
Database object, sub query, Join Commands & Lab Assignment
Arun Sial
 
ORACLE NOTES
Sachin Shukla
 
Interactive SQL and Advance SQL SQL Performance Tuning.pptx
ssuserb8d5cb
 
askndmf,dskmlf,bvdmk,v nmdsvjkmc,dvjkcmsdcvjnkmd
talhahakeem295
 
Mssql
Janas Khan
 
Ad

More from DataminingTools Inc (20)

PPTX
Terminology Machine Learning
DataminingTools Inc
 
PPTX
Techniques Machine Learning
DataminingTools Inc
 
PPTX
Machine learning Introduction
DataminingTools Inc
 
PPTX
Areas of machine leanring
DataminingTools Inc
 
PPTX
AI: Planning and AI
DataminingTools Inc
 
PPTX
AI: Logic in AI 2
DataminingTools Inc
 
PPTX
AI: Logic in AI
DataminingTools Inc
 
PPTX
AI: Learning in AI 2
DataminingTools Inc
 
PPTX
AI: Learning in AI
DataminingTools Inc
 
PPTX
AI: Introduction to artificial intelligence
DataminingTools Inc
 
PPTX
AI: Belief Networks
DataminingTools Inc
 
PPTX
AI: AI & Searching
DataminingTools Inc
 
PPTX
AI: AI & Problem Solving
DataminingTools Inc
 
PPTX
Data Mining: Text and web mining
DataminingTools Inc
 
PPTX
Data Mining: Outlier analysis
DataminingTools Inc
 
PPTX
Data Mining: Mining stream time series and sequence data
DataminingTools Inc
 
PPTX
Data Mining: Mining ,associations, and correlations
DataminingTools Inc
 
PPTX
Data Mining: Graph mining and social network analysis
DataminingTools Inc
 
PPTX
Data warehouse and olap technology
DataminingTools Inc
 
PPTX
Data Mining: Data processing
DataminingTools Inc
 
Terminology Machine Learning
DataminingTools Inc
 
Techniques Machine Learning
DataminingTools Inc
 
Machine learning Introduction
DataminingTools Inc
 
Areas of machine leanring
DataminingTools Inc
 
AI: Planning and AI
DataminingTools Inc
 
AI: Logic in AI 2
DataminingTools Inc
 
AI: Logic in AI
DataminingTools Inc
 
AI: Learning in AI 2
DataminingTools Inc
 
AI: Learning in AI
DataminingTools Inc
 
AI: Introduction to artificial intelligence
DataminingTools Inc
 
AI: Belief Networks
DataminingTools Inc
 
AI: AI & Searching
DataminingTools Inc
 
AI: AI & Problem Solving
DataminingTools Inc
 
Data Mining: Text and web mining
DataminingTools Inc
 
Data Mining: Outlier analysis
DataminingTools Inc
 
Data Mining: Mining stream time series and sequence data
DataminingTools Inc
 
Data Mining: Mining ,associations, and correlations
DataminingTools Inc
 
Data Mining: Graph mining and social network analysis
DataminingTools Inc
 
Data warehouse and olap technology
DataminingTools Inc
 
Data Mining: Data processing
DataminingTools Inc
 

Recently uploaded (20)

PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PDF
Advancing WebDriver BiDi support in WebKit
Igalia
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PDF
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
What Makes Contify’s News API Stand Out: Key Features at a Glance
Contify
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
Advancing WebDriver BiDi support in WebKit
Igalia
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
What Makes Contify’s News API Stand Out: Key Features at a Glance
Contify
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 

MySql: Queries

  • 2. OVERVIEWQuerying data using joinsAggregation functionsCreating and using viewsUsing union operator for queryingSubqueries.
  • 3. Querying data using joins1.INNER JOIN()CROSS JOIN and JOIN types are all similar to INNER JOINUsed 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.i2Where t1.i1 ISNULL; (left join is used to find the records where there is mismatch)
  • 8. Join can be used for self referencingEx: consider the emp_mgr table
  • 9. (employee table can be retrieved separately byperforming self join) employee_tableMysql>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 QUERYINGWe can list the combined result set from differenttables.Ex://suppose we have 2 teams one for quiz and 1 for debate as followsquiz 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 ofrecords and return a single value.Often used with GROUP BY clause of SELECTstatement.Some of the aggregate functions areSUM,AVG,MIN,MAX,COUNT etc
  • 14. 1.SUM()Returns the sum of the grouped values, Returns 0 if there are no matching values.Mysql>select dept,sum(sal)From employeeGroup 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.88896.STDDEV()Mysql>select stddev(sal) from employee;26246.6929
  • 17. viewsViews are virtual tables defined in terms of other(base) tables.When the data in the underlying table changes so doesthe data in the view.But if the definitions in the table changes for ex: if weadd 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 whenthe view is mapped directly onto a single tableview must select only the columns that are simple references to the table columnsany 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 databaseif 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_conditionCheck_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 viewsPrivileges 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 queriesSubqueries 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 operatorsComparison 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 INUsed 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 managersMysql>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.ALLTests if the comparison value satisfies the particularrelationship with all the values returned by thesubquery.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. ANYTests if the comparison value satisfies theparticular relationship with any valuereturned 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 EXISTSUsed to test if the subquery returns any row.If it returns any row.EXISTS is true and NOT EXISTis false, it returns 1.Mysql>select EXISTS(select * from employee where ssn=1111111);0Mysql>select NOT EXISTS(select * from employee where ssn=1111111);1
  • 30. Benefits sub queriesmakes the query more Structured.reduced data redundancy and Greater ease of manipulation.sub queries are more readable than joins or unions, indeed it was the innovation of sub queries made people call the early SQL(“structured query language”).
  • 31. Visit more self help tutorialsPick 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