SlideShare une entreprise Scribd logo
1  sur  31
T-SQL – 3rd session MedhatDawoud http://www.medhatdawoud.com MedhatDawoud@gmail.com Twitter  @Med7atDawoud
Agenda Nulls Order by Distinct Aggregates Grouping Having vs. where Compute by Union Constraints (PK,FK) Join tables Sub queries, nested queries Common restriction on Sub-queries
Nulls A null does notmean zero A null indicates that a value is missing, unavailable, incomplete, and inapplicable. Nulls represent an unknown quantity or value. Any question about a null could provide three answers: yes, no, or maybe Try it Now
Remember that studying null gives you the full ability to select any data from a database. The select clause specifies what columns we want to see The from clause tells what table we want to see data from The where clause restricts the data we will see
Order by The order by clause is used to specify a sorting order of the result set The sorting can be performed by column name or by column number. The default sort order is ascending (a-z), but you can specify a descending order by using the keyword desc. Try it Now
Distinct Try this:  select studentName from libraryVisitors As you have seen from the above query result, you can get what appear to be duplicate rows in the result set From the scope of the result set, they are duplicates From the scope of the database they are not Sometimes we do not want to see these duplicate rows We can eliminate them by use of the distinct keyword Try it Now
Aggregates The three we will explore are count, sum, and average. countreturns a count of the number of rows in a table that match a certain criteria sumis used to add up all of the values in a column Avgwill return the average value in a column Try it Now
Group by Data in a table is essentially stored randomly The group by will order the data into groups You still need to specify an order by clause to perform sorting Nulls are consider a group The true power of a group by comes from using it in conjunction with an aggregate Try it Now
Group by Note that: One thing to remember is that if you use a group by with an aggregate, you must specify all non-aggregate columns in the group by clause. You can not specify an aggregate in the group by clause. Try it Now
Having vs. where There is a fundamental difference The whereclause defines the set of data the grouping is done on The havingdefines which groups are going to be returned to the user Having clause generally contain aggregates as part of the selection criteria The book "The Practical SQL Handbook" has a good explanation on pages 180 - 185 Try it Now
Compute by With a compute/computed by, you can only use columns in the select list A compute by is used to sub-summaries You can use any aggregate exceptcount(*) Compute by must start with the same expressions as listed after order by and not skip any expressions Try it Now
Compute by Legal order by a,b,c compute by a,b,c compute by a,b compute avg(price) by a Illegal order by a,b,c compute by b,a,c compute by c,a compute avg(price) by b Try it Now
Union combining data from two different tables when they have mutually exclusive criteria The only restrictions on unions are that the same number of columns must be in each separate result set and the datatypes must match We use the keyword Union to do that Try it Now
Relationships A database derives its usefulness from containing a group of tables that have some relationship to each other An entity is a person, place, or thing of importance to an organization An entity generally becomes a table Relationships are the connections between tables Relationships are usually implemented as keys in a database design
Relationships cont. ,[object Object]
One to oneOne row in a table is related to exactly one row in another table ,[object Object],One row in a table is related to one or more rows in another table ,[object Object],Many rows in a table are related to one or more rows in another table
Primary Key A primary key is a special type of key that consists of one or more columns that uniquely identify a row Primary keys must be unique and can not contain null values A table will only have one primary key Primary key can not be null. Try it Now
Foreign Key A foreign key is one or more columns that refer to a primary key of another table If we have stu_id as a primary key in students table it’s consider to be a foreign key in the libraryVisitors table. Try it Now
Composite key A primary key and a foreign key can consist of more than one column When a key contains more than one column, it is known as a composite key The primary key of the titleauthor table is a composite (au_id,title_id)
Join tables All of the data in a database is segmented into tables and we generally need data from more than one table to show what we need You will notice that there is no such thing as a join clause in our SQL syntax If we get the data from library table we will get the stu_id which make no sense we need the studentName so, we use joins as shown in the try it out. Try it Now
Join tables (PUBS)
Join tables We are retrieving data from more than one table, so each table must be specified in the from clause So, The from clause can be seen as the main driver of a SQL statement The type of join we have examined so far is also referred to as an equi-join or an inner join And if you will notice that the results that has null values is ignored
Join tables To solve the problem of the null values we use another type of joins called outer join Outer joins come in three different flavors Left Right Full Left: stores.stor_id *= sales.stor_id Right: sales.stor_id =* stores.stor_id A full outer join is included here for completeness If you have one table with 100 rows and another with 1000 rows, a full outer join will produce a result set of 100,000 rows Try it Now
Full outer Join A full outer join will produce a cross product of the two tables This is because with a full outer join, you are telling the database to give every combination of rows possible The first time you inadvertently fire one of these off, you will get a rather angry call  from your DBA
Sub queries Sub-queriesare simply a SQL statement nested inside of another SQL statement. The most common place to do this is in a where or havingclause. Subqueries come in two basic kinds:  correlated and noncorrelated
Two kinds of sub queries A noncorrelatedsub-query is one in which the inner query is independent, gets evaluated first, and passes it’s result set back to the outer query A correlatedsub-query is one in which the inner query is dependent upon the results from the outer query
Two examples to sub queries noncorrelated: select pub_name from publishers where pub_id in (select pub_id from titles where type = 'business') correlated: select pub_name from publishers p where 'business' in (select type from titles where oub_id = p.pub_id) Try it Now
Join and sub-queries select distinct pub_name from publishers, authors where publishers.city = authors.city AND select pub_name from publishers where city in (select city from authors) will return the same results Whether you use joins or subqueries is usually a matter of choice Most joins can be expressed as subqueries and vice versa
Common restriction Subqueries can not manipulate their results internally.  i.e. They can not contain an order by or the keyword INTO You use the ANY and ALL keywords with a comparison operator in a sub-query > ALL means greater than every value in the results of the inner query (> maximum value) > ANY means greater than any value in the results of the inner query (> minimum value) Try it Now
Exist The last type of sub-query is used to test for the existence of something To find all of the publishers who publish business books we would do the following: select distinct pub_name from publishers where exists (select 1 from titles where pub_id = publishers.pub_id and type = 'business')
Nested Queries A sub-query may contain anothersub-query In fact you can nest as many levels as you need.  However, for most applications more than four levels is an indication of poor database design

Contenu connexe

Tendances

Tendances (20)

SQL Basics
SQL BasicsSQL Basics
SQL Basics
 
STRUCTURE OF SQL QUERIES
STRUCTURE OF SQL QUERIESSTRUCTURE OF SQL QUERIES
STRUCTURE OF SQL QUERIES
 
Introduction to SQL
Introduction to SQLIntroduction to SQL
Introduction to SQL
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
 
Advanced Sql Training
Advanced Sql TrainingAdvanced Sql Training
Advanced Sql Training
 
SQL Overview
SQL OverviewSQL Overview
SQL Overview
 
Introduction to SQL
Introduction to SQLIntroduction to SQL
Introduction to SQL
 
Sql Basics And Advanced
Sql Basics And AdvancedSql Basics And Advanced
Sql Basics And Advanced
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
 
Sql intro & ddl 1
Sql intro & ddl 1Sql intro & ddl 1
Sql intro & ddl 1
 
Introduction to database
Introduction to databaseIntroduction to database
Introduction to database
 
SQL : introduction
SQL : introductionSQL : introduction
SQL : introduction
 
SQL Commands
SQL Commands SQL Commands
SQL Commands
 
SQL Server Learning Drive
SQL Server Learning Drive SQL Server Learning Drive
SQL Server Learning Drive
 
Sql.pptx
Sql.pptxSql.pptx
Sql.pptx
 
Ankit
AnkitAnkit
Ankit
 
SQL - Structured query language introduction
SQL - Structured query language introductionSQL - Structured query language introduction
SQL - Structured query language introduction
 
Database Design and Normalization Techniques
Database Design and Normalization TechniquesDatabase Design and Normalization Techniques
Database Design and Normalization Techniques
 
Chapter8 my sql revision tour
Chapter8 my sql revision tourChapter8 my sql revision tour
Chapter8 my sql revision tour
 
SQL Queries Information
SQL Queries InformationSQL Queries Information
SQL Queries Information
 

En vedette (10)

Visual Logic User Guide
Visual Logic User GuideVisual Logic User Guide
Visual Logic User Guide
 
Subqueries
SubqueriesSubqueries
Subqueries
 
Sql join
Sql  joinSql  join
Sql join
 
SQL subquery
SQL subquerySQL subquery
SQL subquery
 
New T-SQL Features in SQL Server 2012
New T-SQL Features in SQL Server 2012 New T-SQL Features in SQL Server 2012
New T-SQL Features in SQL Server 2012
 
Sql9e ppt ch05
Sql9e ppt ch05 Sql9e ppt ch05
Sql9e ppt ch05
 
Sql joins
Sql joinsSql joins
Sql joins
 
Part 12 t-sql
Part 12  t-sqlPart 12  t-sql
Part 12 t-sql
 
Sub query_SQL
Sub query_SQLSub query_SQL
Sub query_SQL
 
New Features of SQL Server 2016
New Features of SQL Server 2016New Features of SQL Server 2016
New Features of SQL Server 2016
 

Similaire à Intro to t sql – 3rd session

Ms sql server ii
Ms sql server  iiMs sql server  ii
Ms sql server ii
Iblesoft
 
Ben Finkel- Using the order by clause.pptx
Ben Finkel- Using the order by clause.pptxBen Finkel- Using the order by clause.pptx
Ben Finkel- Using the order by clause.pptx
StephenEfange3
 
Intro to tsql unit 3
Intro to tsql   unit 3Intro to tsql   unit 3
Intro to tsql unit 3
Syed Asrarali
 
SQL dabatase interveiw pdf for interveiw preparation
SQL dabatase  interveiw pdf for interveiw preparationSQL dabatase  interveiw pdf for interveiw preparation
SQL dabatase interveiw pdf for interveiw preparation
kumarvikesh2841998
 
4b6c1c5c-e913-4bbf-b3a4-41e23cb961ba-161004200047.pdf
4b6c1c5c-e913-4bbf-b3a4-41e23cb961ba-161004200047.pdf4b6c1c5c-e913-4bbf-b3a4-41e23cb961ba-161004200047.pdf
4b6c1c5c-e913-4bbf-b3a4-41e23cb961ba-161004200047.pdf
Nitish Nagar
 
Intro to tsql unit 4
Intro to tsql   unit 4Intro to tsql   unit 4
Intro to tsql unit 4
Syed Asrarali
 

Similaire à Intro to t sql – 3rd session (20)

Oracle SQL Part 3
Oracle SQL Part 3Oracle SQL Part 3
Oracle SQL Part 3
 
04 quiz 1 answer key
04 quiz 1 answer key04 quiz 1 answer key
04 quiz 1 answer key
 
Join sql
Join sqlJoin sql
Join sql
 
SQLSERVERQUERIES.pptx
SQLSERVERQUERIES.pptxSQLSERVERQUERIES.pptx
SQLSERVERQUERIES.pptx
 
DBMS and SQL(structured query language) .pptx
DBMS and SQL(structured query language) .pptxDBMS and SQL(structured query language) .pptx
DBMS and SQL(structured query language) .pptx
 
Ms sql server ii
Ms sql server  iiMs sql server  ii
Ms sql server ii
 
Ben Finkel- Using the order by clause.pptx
Ben Finkel- Using the order by clause.pptxBen Finkel- Using the order by clause.pptx
Ben Finkel- Using the order by clause.pptx
 
SQL200.2 Module 2
SQL200.2 Module 2SQL200.2 Module 2
SQL200.2 Module 2
 
Intro to tsql unit 3
Intro to tsql   unit 3Intro to tsql   unit 3
Intro to tsql unit 3
 
Intro To TSQL - Unit 3
Intro To TSQL - Unit 3Intro To TSQL - Unit 3
Intro To TSQL - Unit 3
 
SQL dabatase interveiw pdf for interveiw preparation
SQL dabatase  interveiw pdf for interveiw preparationSQL dabatase  interveiw pdf for interveiw preparation
SQL dabatase interveiw pdf for interveiw preparation
 
Advanced Excel ppt
Advanced Excel pptAdvanced Excel ppt
Advanced Excel ppt
 
Bt0075 rdbms with mysql 2
Bt0075 rdbms with mysql 2Bt0075 rdbms with mysql 2
Bt0075 rdbms with mysql 2
 
Module03
Module03Module03
Module03
 
Question 2B
Question 2BQuestion 2B
Question 2B
 
4b6c1c5c-e913-4bbf-b3a4-41e23cb961ba-161004200047.pdf
4b6c1c5c-e913-4bbf-b3a4-41e23cb961ba-161004200047.pdf4b6c1c5c-e913-4bbf-b3a4-41e23cb961ba-161004200047.pdf
4b6c1c5c-e913-4bbf-b3a4-41e23cb961ba-161004200047.pdf
 
Intro To TSQL - Unit 4
Intro To TSQL - Unit 4Intro To TSQL - Unit 4
Intro To TSQL - Unit 4
 
Intro to tsql unit 4
Intro to tsql   unit 4Intro to tsql   unit 4
Intro to tsql unit 4
 
5. Group Functions
5. Group Functions5. Group Functions
5. Group Functions
 
Day-2 SQL Theory_V1.pptx
Day-2 SQL Theory_V1.pptxDay-2 SQL Theory_V1.pptx
Day-2 SQL Theory_V1.pptx
 

Plus de Medhat Dawoud (11)

Real time web
Real time webReal time web
Real time web
 
Using Git and BitBucket
Using Git and BitBucketUsing Git and BitBucket
Using Git and BitBucket
 
Introduction to linux
Introduction to linuxIntroduction to linux
Introduction to linux
 
Select your career
Select your careerSelect your career
Select your career
 
Mesh cloud (road to mongoDB)
Mesh cloud (road to mongoDB)Mesh cloud (road to mongoDB)
Mesh cloud (road to mongoDB)
 
Before start
Before startBefore start
Before start
 
DevMix Startup
DevMix StartupDevMix Startup
DevMix Startup
 
Threading in C#
Threading in C#Threading in C#
Threading in C#
 
How to python
How to pythonHow to python
How to python
 
Program threats
Program threatsProgram threats
Program threats
 
Unusual C# - OOP
Unusual C# - OOPUnusual C# - OOP
Unusual C# - OOP
 

Dernier

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Dernier (20)

Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 

Intro to t sql – 3rd session

  • 1. T-SQL – 3rd session MedhatDawoud http://www.medhatdawoud.com MedhatDawoud@gmail.com Twitter  @Med7atDawoud
  • 2. Agenda Nulls Order by Distinct Aggregates Grouping Having vs. where Compute by Union Constraints (PK,FK) Join tables Sub queries, nested queries Common restriction on Sub-queries
  • 3. Nulls A null does notmean zero A null indicates that a value is missing, unavailable, incomplete, and inapplicable. Nulls represent an unknown quantity or value. Any question about a null could provide three answers: yes, no, or maybe Try it Now
  • 4. Remember that studying null gives you the full ability to select any data from a database. The select clause specifies what columns we want to see The from clause tells what table we want to see data from The where clause restricts the data we will see
  • 5. Order by The order by clause is used to specify a sorting order of the result set The sorting can be performed by column name or by column number. The default sort order is ascending (a-z), but you can specify a descending order by using the keyword desc. Try it Now
  • 6. Distinct Try this: select studentName from libraryVisitors As you have seen from the above query result, you can get what appear to be duplicate rows in the result set From the scope of the result set, they are duplicates From the scope of the database they are not Sometimes we do not want to see these duplicate rows We can eliminate them by use of the distinct keyword Try it Now
  • 7. Aggregates The three we will explore are count, sum, and average. countreturns a count of the number of rows in a table that match a certain criteria sumis used to add up all of the values in a column Avgwill return the average value in a column Try it Now
  • 8. Group by Data in a table is essentially stored randomly The group by will order the data into groups You still need to specify an order by clause to perform sorting Nulls are consider a group The true power of a group by comes from using it in conjunction with an aggregate Try it Now
  • 9. Group by Note that: One thing to remember is that if you use a group by with an aggregate, you must specify all non-aggregate columns in the group by clause. You can not specify an aggregate in the group by clause. Try it Now
  • 10. Having vs. where There is a fundamental difference The whereclause defines the set of data the grouping is done on The havingdefines which groups are going to be returned to the user Having clause generally contain aggregates as part of the selection criteria The book "The Practical SQL Handbook" has a good explanation on pages 180 - 185 Try it Now
  • 11. Compute by With a compute/computed by, you can only use columns in the select list A compute by is used to sub-summaries You can use any aggregate exceptcount(*) Compute by must start with the same expressions as listed after order by and not skip any expressions Try it Now
  • 12. Compute by Legal order by a,b,c compute by a,b,c compute by a,b compute avg(price) by a Illegal order by a,b,c compute by b,a,c compute by c,a compute avg(price) by b Try it Now
  • 13. Union combining data from two different tables when they have mutually exclusive criteria The only restrictions on unions are that the same number of columns must be in each separate result set and the datatypes must match We use the keyword Union to do that Try it Now
  • 14. Relationships A database derives its usefulness from containing a group of tables that have some relationship to each other An entity is a person, place, or thing of importance to an organization An entity generally becomes a table Relationships are the connections between tables Relationships are usually implemented as keys in a database design
  • 15.
  • 16.
  • 17. Primary Key A primary key is a special type of key that consists of one or more columns that uniquely identify a row Primary keys must be unique and can not contain null values A table will only have one primary key Primary key can not be null. Try it Now
  • 18. Foreign Key A foreign key is one or more columns that refer to a primary key of another table If we have stu_id as a primary key in students table it’s consider to be a foreign key in the libraryVisitors table. Try it Now
  • 19. Composite key A primary key and a foreign key can consist of more than one column When a key contains more than one column, it is known as a composite key The primary key of the titleauthor table is a composite (au_id,title_id)
  • 20. Join tables All of the data in a database is segmented into tables and we generally need data from more than one table to show what we need You will notice that there is no such thing as a join clause in our SQL syntax If we get the data from library table we will get the stu_id which make no sense we need the studentName so, we use joins as shown in the try it out. Try it Now
  • 22. Join tables We are retrieving data from more than one table, so each table must be specified in the from clause So, The from clause can be seen as the main driver of a SQL statement The type of join we have examined so far is also referred to as an equi-join or an inner join And if you will notice that the results that has null values is ignored
  • 23. Join tables To solve the problem of the null values we use another type of joins called outer join Outer joins come in three different flavors Left Right Full Left: stores.stor_id *= sales.stor_id Right: sales.stor_id =* stores.stor_id A full outer join is included here for completeness If you have one table with 100 rows and another with 1000 rows, a full outer join will produce a result set of 100,000 rows Try it Now
  • 24. Full outer Join A full outer join will produce a cross product of the two tables This is because with a full outer join, you are telling the database to give every combination of rows possible The first time you inadvertently fire one of these off, you will get a rather angry call  from your DBA
  • 25. Sub queries Sub-queriesare simply a SQL statement nested inside of another SQL statement. The most common place to do this is in a where or havingclause. Subqueries come in two basic kinds: correlated and noncorrelated
  • 26. Two kinds of sub queries A noncorrelatedsub-query is one in which the inner query is independent, gets evaluated first, and passes it’s result set back to the outer query A correlatedsub-query is one in which the inner query is dependent upon the results from the outer query
  • 27. Two examples to sub queries noncorrelated: select pub_name from publishers where pub_id in (select pub_id from titles where type = 'business') correlated: select pub_name from publishers p where 'business' in (select type from titles where oub_id = p.pub_id) Try it Now
  • 28. Join and sub-queries select distinct pub_name from publishers, authors where publishers.city = authors.city AND select pub_name from publishers where city in (select city from authors) will return the same results Whether you use joins or subqueries is usually a matter of choice Most joins can be expressed as subqueries and vice versa
  • 29. Common restriction Subqueries can not manipulate their results internally. i.e. They can not contain an order by or the keyword INTO You use the ANY and ALL keywords with a comparison operator in a sub-query > ALL means greater than every value in the results of the inner query (> maximum value) > ANY means greater than any value in the results of the inner query (> minimum value) Try it Now
  • 30. Exist The last type of sub-query is used to test for the existence of something To find all of the publishers who publish business books we would do the following: select distinct pub_name from publishers where exists (select 1 from titles where pub_id = publishers.pub_id and type = 'business')
  • 31. Nested Queries A sub-query may contain anothersub-query In fact you can nest as many levels as you need. However, for most applications more than four levels is an indication of poor database design