T-SQL – 3rd sessionMedhatDawoudhttp://www.medhatdawoud.comMedhatDawoud@gmail.comTwitter  @Med7atDawoud
AgendaNullsOrder byDistinctAggregatesGroupingHaving vs. whereCompute byUnionConstraints (PK,FK)Join tablesSub queries, nested queriesCommon restriction on Sub-queries
NullsA null does notmean zeroA 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 maybeTry it Now
Remember thatstudying null gives you the full ability to select any data from a database.The select clause specifies what columns we want to seeThe from clause tells what table we want to see data fromThe where clause restricts the data we will see
Order byThe order by clause is used to specify a sorting order of the result setThe 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
DistinctTry this:  select studentName from libraryVisitorsAs you have seen from the above query result, you can get what appear to be duplicate rows in the result setFrom the scope of the result set, they are duplicatesFrom the scope of the database they are notSometimes we do not want to see these duplicate rowsWe can eliminate them by use of the distinct keywordTry it Now
AggregatesThe three we will explore are count, sum, and average.countreturns a count of the number of rows in a table that match a certain criteriasumis used to add up all of the values in a columnAvgwill return the average value in a columnTry it Now
Group byData in a table is essentially stored randomlyThe group by will order the data into groupsYou still need to specify an order by clause to perform sortingNulls are consider a groupThe true power of a group by comes from using it in conjunction with an aggregateTry it Now
Group byNote 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. whereThere is a fundamental differenceThe whereclause defines the set of data the grouping is done onThe havingdefines which groups are going to be returned to the userHaving clause generally contain aggregates as part of the selection criteriaThe book "The Practical SQL Handbook" has a good explanation on pages 180 - 185Try it Now
Compute byWith a compute/computed by, you can only use columns in the select listA compute by is used to sub-summariesYou can use any aggregate exceptcount(*)Compute by must start with the same expressions as listed after order by and not skip any expressionsTry it Now
Compute byLegalorder by a,b,ccompute by a,b,ccompute by a,bcompute avg(price) by aIllegalorder by a,b,ccompute by b,a,ccompute by c,acompute avg(price) by bTry it Now
Unioncombining data from two different tables when they have mutually exclusive criteriaThe only restrictions on unions are that the same number of columns must be in each separate result set and the datatypes must matchWe use the keyword Union to do thatTry it Now
RelationshipsA database derives its usefulness from containing a group of tables that have some relationship to each otherAn entity is a person, place, or thing of importance to an organizationAn entity generally becomes a tableRelationships are the connections between tablesRelationships are usually implemented as keys in a database design
Relationships cont.Relationships come in three different varieties
One to oneOne row in a table is related to exactly one row in another tableOne to manyOne row in a table is related to one or more rows in another tableMany to manyMany rows in a table are related to one or more rows in another table
Primary KeyA primary key is a special type of key that consists of one or more columns that uniquely identify a rowPrimary keys must be unique and can not contain null valuesA table will only have one primary keyPrimary key can not be null.Try it Now
Foreign KeyA foreign key is one or more columns that refer to a primary key of another tableIf 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 keyA primary key and a foreign key can consist of more than one columnWhen a key contains more than one column, it is known as a composite keyThe primary key of the titleauthor table is a composite (au_id,title_id)
Join tablesAll of the data in a database is segmented into tables and we generally need data from more than one table to show what we needYou will notice that there is no such thing as a join clause in our SQL syntaxIf 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 tablesWe are retrieving data from more than one table, so each table must be specified in the from clauseSo, The from clause can be seen as the main driver of a SQL statementThe type of join we have examined so far is also referred to as an equi-join or an inner joinAnd if you will notice that the results that has null values is ignored
Join tablesTo solve the problem of the null values we use another type of joins called outer joinOuter joins come in three different flavorsLeftRightFullLeft: stores.stor_id *= sales.stor_idRight: sales.stor_id =* stores.stor_idA full outer join is included here for completenessIf you have one table with 100 rows and another with 1000 rows, a full outer join will produce a result set of 100,000 rowsTry it Now
Full outer JoinA full outer join will produce a cross product of the two tablesThis is because with a full outer join, you are telling the database to give every combination of rows possibleThe first time you inadvertently fire one of these off, you will get a rather angry call  from your DBA
Sub queriesSub-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 queriesA noncorrelatedsub-query is one in which the inner query is independent, gets evaluated first, and passes it’s result set back to the outer queryA correlatedsub-query is one in which the inner query is dependent upon the results from the outer query
Two examples to sub queriesnoncorrelated:select pub_name from publisherswhere pub_id in (select pub_id from titleswhere type = 'business')correlated:select pub_name from publishers pwhere 'business' in (select type from titles where oub_id = p.pub_id)Try it Now
Join and sub-queriesselect distinct pub_name from publishers, authors where publishers.city = authors.cityANDselect pub_name from publishers where city in (select city from authors)will return the same resultsWhether you use joins or subqueries is usually a matter of choiceMost joins can be expressed as subqueries and vice versa
Common restrictionSubqueries can not manipulate their results internally.  i.e. They can not contain an order by or the keyword INTOYou 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
ExistThe last type of sub-query is used to test for the existence of somethingTo 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 QueriesA sub-query may contain anothersub-queryIn 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

Intro to t sql – 3rd session

  • 1.
    T-SQL – 3rdsessionMedhatDawoudhttp://www.medhatdawoud.comMedhatDawoud@gmail.comTwitter  @Med7atDawoud
  • 2.
    AgendaNullsOrder byDistinctAggregatesGroupingHaving vs.whereCompute byUnionConstraints (PK,FK)Join tablesSub queries, nested queriesCommon restriction on Sub-queries
  • 3.
    NullsA null doesnotmean zeroA 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 maybeTry it Now
  • 4.
    Remember thatstudying nullgives you the full ability to select any data from a database.The select clause specifies what columns we want to seeThe from clause tells what table we want to see data fromThe where clause restricts the data we will see
  • 5.
    Order byThe orderby clause is used to specify a sorting order of the result setThe 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.
    DistinctTry this: select studentName from libraryVisitorsAs you have seen from the above query result, you can get what appear to be duplicate rows in the result setFrom the scope of the result set, they are duplicatesFrom the scope of the database they are notSometimes we do not want to see these duplicate rowsWe can eliminate them by use of the distinct keywordTry it Now
  • 7.
    AggregatesThe three wewill explore are count, sum, and average.countreturns a count of the number of rows in a table that match a certain criteriasumis used to add up all of the values in a columnAvgwill return the average value in a columnTry it Now
  • 8.
    Group byData ina table is essentially stored randomlyThe group by will order the data into groupsYou still need to specify an order by clause to perform sortingNulls are consider a groupThe true power of a group by comes from using it in conjunction with an aggregateTry it Now
  • 9.
    Group byNote 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. whereThereis a fundamental differenceThe whereclause defines the set of data the grouping is done onThe havingdefines which groups are going to be returned to the userHaving clause generally contain aggregates as part of the selection criteriaThe book "The Practical SQL Handbook" has a good explanation on pages 180 - 185Try it Now
  • 11.
    Compute byWith acompute/computed by, you can only use columns in the select listA compute by is used to sub-summariesYou can use any aggregate exceptcount(*)Compute by must start with the same expressions as listed after order by and not skip any expressionsTry it Now
  • 12.
    Compute byLegalorder bya,b,ccompute by a,b,ccompute by a,bcompute avg(price) by aIllegalorder by a,b,ccompute by b,a,ccompute by c,acompute avg(price) by bTry it Now
  • 13.
    Unioncombining data fromtwo different tables when they have mutually exclusive criteriaThe only restrictions on unions are that the same number of columns must be in each separate result set and the datatypes must matchWe use the keyword Union to do thatTry it Now
  • 14.
    RelationshipsA database derivesits usefulness from containing a group of tables that have some relationship to each otherAn entity is a person, place, or thing of importance to an organizationAn entity generally becomes a tableRelationships are the connections between tablesRelationships are usually implemented as keys in a database design
  • 15.
    Relationships cont.Relationships comein three different varieties
  • 16.
    One to oneOnerow in a table is related to exactly one row in another tableOne to manyOne row in a table is related to one or more rows in another tableMany to manyMany rows in a table are related to one or more rows in another table
  • 17.
    Primary KeyA primarykey is a special type of key that consists of one or more columns that uniquely identify a rowPrimary keys must be unique and can not contain null valuesA table will only have one primary keyPrimary key can not be null.Try it Now
  • 18.
    Foreign KeyA foreignkey is one or more columns that refer to a primary key of another tableIf 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 keyA primarykey and a foreign key can consist of more than one columnWhen a key contains more than one column, it is known as a composite keyThe primary key of the titleauthor table is a composite (au_id,title_id)
  • 20.
    Join tablesAll ofthe data in a database is segmented into tables and we generally need data from more than one table to show what we needYou will notice that there is no such thing as a join clause in our SQL syntaxIf 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
  • 21.
  • 22.
    Join tablesWe areretrieving data from more than one table, so each table must be specified in the from clauseSo, The from clause can be seen as the main driver of a SQL statementThe type of join we have examined so far is also referred to as an equi-join or an inner joinAnd if you will notice that the results that has null values is ignored
  • 23.
    Join tablesTo solvethe problem of the null values we use another type of joins called outer joinOuter joins come in three different flavorsLeftRightFullLeft: stores.stor_id *= sales.stor_idRight: sales.stor_id =* stores.stor_idA full outer join is included here for completenessIf you have one table with 100 rows and another with 1000 rows, a full outer join will produce a result set of 100,000 rowsTry it Now
  • 24.
    Full outer JoinAfull outer join will produce a cross product of the two tablesThis is because with a full outer join, you are telling the database to give every combination of rows possibleThe first time you inadvertently fire one of these off, you will get a rather angry call  from your DBA
  • 25.
    Sub queriesSub-queriesare simplya 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 ofsub queriesA noncorrelatedsub-query is one in which the inner query is independent, gets evaluated first, and passes it’s result set back to the outer queryA correlatedsub-query is one in which the inner query is dependent upon the results from the outer query
  • 27.
    Two examples tosub queriesnoncorrelated:select pub_name from publisherswhere pub_id in (select pub_id from titleswhere type = 'business')correlated:select pub_name from publishers pwhere 'business' in (select type from titles where oub_id = p.pub_id)Try it Now
  • 28.
    Join and sub-queriesselectdistinct pub_name from publishers, authors where publishers.city = authors.cityANDselect pub_name from publishers where city in (select city from authors)will return the same resultsWhether you use joins or subqueries is usually a matter of choiceMost joins can be expressed as subqueries and vice versa
  • 29.
    Common restrictionSubqueries cannot manipulate their results internally. i.e. They can not contain an order by or the keyword INTOYou 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.
    ExistThe last typeof sub-query is used to test for the existence of somethingTo 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 QueriesA sub-querymay contain anothersub-queryIn 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