Structured Query Language3

Embed Size (px)

Citation preview

  • 7/31/2019 Structured Query Language3

    1/78

    Database DesignDatabase Design Designing a database requires an understanding of both the businessDesigning a database requires an understanding of both the business

    functions you want to model and the database concepts and featuresfunctions you want to model and the database concepts and featuresused to represent those business functions.used to represent those business functions.

    It is important to design a database to accurately model the business,It is important to design a database to accurately model the business,because it can be time consuming to significantly change the design ofbecause it can be time consuming to significantly change the design ofa database once implemented. Additionally, a well-designed databasea database once implemented. Additionally, a well-designed databasewill generally perform better.will generally perform better.

    When creating a database design, you should consider:When creating a database design, you should consider: The purpose of the database and how it affects the designThe purpose of the database and how it affects the design

    considerations.considerations.

    Database normalization rules that prevent mistakes in theDatabase normalization rules that prevent mistakes in thedatabase design.database design.

    Security requirements of the database and user permissions.Security requirements of the database and user permissions.

    Performance needs of the application. You must ensure that thePerformance needs of the application. You must ensure that thedatabase design takes advantage of Microsoft SQL Serverdatabase design takes advantage of Microsoft SQL Server featuresfeaturesthat improve performance. Achieving a balance betweenthat improve performance. Achieving a balance between the size ofthe size ofthe database and the hardware configuration is alsothe database and the hardware configuration is also important forimportant forperformance.performance.

    Ease of maintenance.Ease of maintenance.

  • 7/31/2019 Structured Query Language3

    2/78

    NormalizationNormalization The logical design of the database, including the tablesThe logical design of the database, including the tables

    and the relationships between them, is the core of anand the relationships between them, is the core of anoptimized relational database. A good logical databaseoptimized relational database. A good logical database

    design can lay the foundation for optimal database anddesign can lay the foundation for optimal database and

    application performance. A poor logical database designapplication performance. A poor logical database design

    can hinder the performance of the entire system.can hinder the performance of the entire system.

    Normalizing a logical database design involves usingNormalizing a logical database design involves using

    formal methods to separate the data into multiple, relatedformal methods to separate the data into multiple, related

    tables. A greater number of narrow tables (with fewertables. A greater number of narrow tables (with fewer

    columns) is characteristic of a normalized database. Acolumns) is characteristic of a normalized database. Afew wide tables (with more columns) is characteristic offew wide tables (with more columns) is characteristic of

    an unnormalized database.an unnormalized database.

  • 7/31/2019 Structured Query Language3

    3/78

    Some of the benefits of normalization include:Some of the benefits of normalization include:

    Faster sorting and index creation.Faster sorting and index creation.

    More clustered indexes.More clustered indexes.

    Narrower and more compact indexes.Narrower and more compact indexes.

    Fewer indexes per table, which helps the performance ofFewer indexes per table, which helps the performance of

    INSERT, UPDATE, and DELETE statements.INSERT, UPDATE, and DELETE statements.

    Fewer NULLs and less opportunity for inconsistency,Fewer NULLs and less opportunity for inconsistency,which increases database compactness.which increases database compactness.

  • 7/31/2019 Structured Query Language3

    4/78

    Primary KeyPrimary Key A table usually has a column or combination of columns whose valuesA table usually has a column or combination of columns whose values

    uniquely identify each row in the table. This column (or columns) isuniquely identify each row in the table. This column (or columns) is

    called thecalled theprimaryprimarykey of the table and enforces thekey of the table and enforces the entity integrityentity integrityofofthe table. Primary keys also enforcethe table. Primary keys also enforce referential integrityreferential integrityby establishingby establishing

    a reliable link to data in related tables.a reliable link to data in related tables.

    Primary KeysPrimary Keys

    Au_id Title_id Au_ord royaltyper

    172-32-1176 PS3333 1 100

    213-46-8915 BU1032 2 40

    213-46-8915 BU2075 1 100

    238-95-7766 PC1035 1 100

    267-41-2394 BU1111 2 40

  • 7/31/2019 Structured Query Language3

    5/78

    Foreign KeyForeign Key AA foreign keyforeign keyis a column or combination of columnsis a column or combination of columns

    used to establish and enforce a link between the data inused to establish and enforce a link between the data in

    two tables. A link is created between two tables bytwo tables. A link is created between two tables byadding the column or columns that represent one of theadding the column or columns that represent one of thetables primary key values to the second table. Thetables primary key values to the second table. Theforeign key is then defined on those columns in theforeign key is then defined on those columns in thesecond table.second table.

    You can create a foreign key by defining a FOREIGN KEYYou can create a foreign key by defining a FOREIGN KEYconstraint when you create or alter a table.constraint when you create or alter a table.

    For example, the titles table in the pubs database needsFor example, the titles table in the pubs database needs

    a link to the publishers table because there is a logicala link to the publishers table because there is a logicalrelationship between books and publishers in therelationship between books and publishers in thedatabase. The pub_id column in the titles table containsdatabase. The pub_id column in the titles table containsthe primary key of the publishers table. The pub_idthe primary key of the publishers table. The pub_idcolumn is the foreign key into the publishers table.column is the foreign key into the publishers table.

  • 7/31/2019 Structured Query Language3

    6/78

    Join FundamentalsJoin FundamentalsJoins let you retrieve data from two or more tables based onJoins let you retrieve data from two or more tables based onlogical relationships between the tables. Joins indicate howlogical relationships between the tables. Joins indicate how

    Microsoft SQL Server should use data from one table to selectMicrosoft SQL Server should use data from one table to selectthe rows in another table.the rows in another table.

    A join condition defines how two tables are related in a query:A join condition defines how two tables are related in a query:

    Specifies the column from each table to be used for the join. ASpecifies the column from each table to be used for the join. Atypical join condition specifies a foreign key from one table and itstypical join condition specifies a foreign key from one table and itsassociated key in the other table.associated key in the other table.

    Specifies a logical operator (=, , and so on) to be used inSpecifies a logical operator (=, , and so on) to be used incomparing values from the columns.comparing values from the columns.

    The join conditions combine with the WHERE and HAVING searchThe join conditions combine with the WHERE and HAVING searchconditions to control which rows are selected from the base tablesconditions to control which rows are selected from the base tablesreferenced in the FROM clause.referenced in the FROM clause.

  • 7/31/2019 Structured Query Language3

    7/78

    An example of a FROM clause join specification is:An example of a FROM clause join specification is:

    FROM Suppliers JOIN ProductsON (Suppliers.SupplierID = Products.SupplierID)

    A simple SELECT statement using this join is:

    SELECT ProductID,Suppliers.SupplierID,

    CompanyNameFROM Suppliers JOIN Products

    ON (Suppliers.SupplierID = Products.SupplierID)WHERE UnitPrice > $10AND CompanyName LIKE N'F%'

    GO

  • 7/31/2019 Structured Query Language3

    8/78

    To improve readability use table aliases:To improve readability use table aliases:

    SELECT P.ProductID,S.SupplierID,S.CompanyName

    FROM Suppliers AS S JOIN Products AS PON (S.SupplierID = P.SupplierID)

    WHERE P.UnitPrice > $10AND S.CompanyName LIKE N'F%

    The examples above have specified the join conditions in theFROM clause, which is the preferred method. A query containingthe same join condition can be specified in the WHERE clause as:

    SELECT P.ProductID,S.SupplierID,

    S.CompanyNameFROM Suppliers AS S, Products AS PWHERE S.SupplierID = P.SupplierID

    AND P.UnitPrice > $10AND S.CompanyName LIKE N'F%'

  • 7/31/2019 Structured Query Language3

    9/78

    Subqueries FundamentalsSubqueries Fundamentals

    A subquery is a SELECT query that returns a single value and isA subquery is a SELECT query that returns a single value and isnested inside a SELECT, INSERT, UPDATE, or DELETE statement,nested inside a SELECT, INSERT, UPDATE, or DELETE statement,

    or inside another subquery. A subquery can be used anywhere anor inside another subquery. A subquery can be used anywhere anexpression is allowed. In this example a subquery is used as aexpression is allowed. In this example a subquery is used as acolumn expression named MaxUnitPrice in a SELECT statement.column expression named MaxUnitPrice in a SELECT statement.

    SELECT Ord.OrderID, Ord.OrderDate,SELECT Ord.OrderID, Ord.OrderDate,

    (SELECT MAX(OrdDet.UnitPrice)(SELECT MAX(OrdDet.UnitPrice)FROM Northwind.dbo.[Order Details] AS OrdDetFROM Northwind.dbo.[Order Details] AS OrdDet

    WHERE Ord.OrderID = OrdDet.OrderID) AS MaxUnitPriceWHERE Ord.OrderID = OrdDet.OrderID) AS MaxUnitPrice

    FROM Northwind.dbo.Orders AS OrdFROM Northwind.dbo.Orders AS Ord

    A subquery is also called an inner query or inner select, while theA subquery is also called an inner query or inner select, while thestatement containing a subquery is also called an outer query orstatement containing a subquery is also called an outer query orouter select.outer select.

  • 7/31/2019 Structured Query Language3

    10/78

    /* SELECT statement built using a subquery. *//* SELECT statement built using a subquery. */

    SELECT ProductNameSELECT ProductName

    FROM Northwind.dbo.ProductsFROM Northwind.dbo.Products

    WHERE UnitPrice =WHERE UnitPrice =

    (SELECT UnitPrice(SELECT UnitPrice

    FROM Northwind.dbo.ProductsFROM Northwind.dbo.Products

    WHERE ProductName = 'Sir Rodney''s Scones')WHERE ProductName = 'Sir Rodney''s Scones')

    /* SELECT statement built using a join that returns/* SELECT statement built using a join that returns

    the same result set. */the same result set. */

    SELECT Prd1.ProductNameSELECT Prd1.ProductName

    FROM Northwind.dbo.Products AS Prd1FROM Northwind.dbo.Products AS Prd1

    JOIN Northwind.dbo.Products AS Prd2JOIN Northwind.dbo.Products AS Prd2

    ON (Prd1.UnitPrice = Prd2.UnitPrice)ON (Prd1.UnitPrice = Prd2.UnitPrice)

    WHERE Prd2.ProductName = 'Sir Rodney''s Scones'WHERE Prd2.ProductName = 'Sir Rodney''s Scones'

  • 7/31/2019 Structured Query Language3

    11/78

    A subquery nested in the outer SELECT statement has the followingA subquery nested in the outer SELECT statement has the followingcomponents:components:

    A regular SELECT query including the regular select list components.A regular SELECT query including the regular select list components.

    A regular FROM clause including one or more table or view names .A regular FROM clause including one or more table or view names .

    An optional WHERE clause.An optional WHERE clause.An optional GROUP BY clause.An optional GROUP BY clause.

    An optional HAVING clause.An optional HAVING clause.

    Subquery RulesSubquery Rules

    A subquery is subject to a number of restrictions:A subquery is subject to a number of restrictions: The select list of a subquery introduced with a comparison operatorThe select list of a subquery introduced with a comparison operator

    can include only one expression or column name (except thatcan include only one expression or column name (except that EXISTS andEXISTS andIN operate on SELECT * or a list, respectively).IN operate on SELECT * or a list, respectively).

    If the WHERE clause of an outer query includes a column name, itIf the WHERE clause of an outer query includes a column name, itmust be join-compatible with the column in the subquery select list.must be join-compatible with the column in the subquery select list.

    TheThe ntextntext,, texttext andand imageimage data types are not allowed in the selectdata types are not allowed in the selectlist of subqueries.list of subqueries.

  • 7/31/2019 Structured Query Language3

    12/78

    Because they must return a single value, subqueries introduced byBecause they must return a single value, subqueries introduced byan unmodified comparison operator (one not followed by thean unmodified comparison operator (one not followed by thekeyword ANY or ALL) cannot include GROUP BY and HAVINGkeyword ANY or ALL) cannot include GROUP BY and HAVINGclauses.clauses.

    The DISTINCT keyword cannot be used with subqueries that includeThe DISTINCT keyword cannot be used with subqueries that includeGROUP BY.GROUP BY.

    The COMPUTE and INTO clauses cannot be specified.The COMPUTE and INTO clauses cannot be specified.

    ORDER BY can only be specified if TOP is also specified.ORDER BY can only be specified if TOP is also specified.

    A view created with a subquery cannot be updated.A view created with a subquery cannot be updated.

    The select list of a subquery introduced with EXISTS by conventionThe select list of a subquery introduced with EXISTS by convention

    consists of an asterisk (*) instead of a single column name. Theconsists of an asterisk (*) instead of a single column name. Therules for a subquery introduced with EXISTS are identical to thoserules for a subquery introduced with EXISTS are identical to thosefor a standard select list because a subquery introduced withfor a standard select list because a subquery introduced withEXISTS constitutes an existence test and returns TRUE or FALSEEXISTS constitutes an existence test and returns TRUE or FALSErather than data.rather than data.

  • 7/31/2019 Structured Query Language3

    13/78

    Subqueries With INSubqueries With IN The result of a subquery introduced with IN (or with NOT IN) is a list of zero or moreThe result of a subquery introduced with IN (or with NOT IN) is a list of zero or more

    values. After the subquery returns results, the outer query makes use of them.values. After the subquery returns results, the outer query makes use of them.

    This query finds the names of the publishers who have published business books.This query finds the names of the publishers who have published business books.

    USE pubsUSE pubs

    SELECT pub_nameSELECT pub_name

    FROM publishersFROM publishers

    WHERE pub_id INWHERE pub_id IN

    (SELECT pub_id(SELECT pub_idFROM titlesFROM titles

    WHERE type = 'business')WHERE type = 'business')

    Here is the result set:Here is the result set:

    pub_namepub_name

    --------------------------------------------------------------------------------

    Algodata InfosystemsAlgodata InfosystemsNew Moon BooksNew Moon Books

    (2 row(s) affected)(2 row(s) affected)

  • 7/31/2019 Structured Query Language3

    14/78

    Heres another example of a query that can be formulated withHeres another example of a query that can be formulated witheither a subquery or a join. This query finds the names of alleither a subquery or a join. This query finds the names of allsecond authors who live in California and who receive less than 30second authors who live in California and who receive less than 30percent of the royalties for a book.percent of the royalties for a book.

    USE pubsUSE pubsSELECT au_lname, au_fnameSELECT au_lname, au_fname

    FROM authorsFROM authors

    WHERE state = 'CA'WHERE state = 'CA'

    AND au_id INAND au_id IN

    (SELECT au_id(SELECT au_idFROM titleauthorFROM titleauthor

    WHERE royaltyper < 30WHERE royaltyper < 30

    AND au_ord = 2)AND au_ord = 2)

    Here is the result set:Here is the result set:au_lname au_fnameau_lname au_fname

    ---------------------------------------- ------------------------------------------------------------ --------------------

    MacFeather StearnsMacFeather Stearns

  • 7/31/2019 Structured Query Language3

    15/78

    Heres another example of a query that can be formulated withHeres another example of a query that can be formulated witheither a subquery or a join. This query finds the names of alleither a subquery or a join. This query finds the names of allsecond authors who live in California and who receive less than 30second authors who live in California and who receive less than 30percent of the royalties for a book.percent of the royalties for a book.

    USE pubsUSE pubsSELECT au_lname, au_fnameSELECT au_lname, au_fname

    FROM authorsFROM authors

    WHERE state = 'CA'WHERE state = 'CA'

    AND au_id INAND au_id IN

    (SELECT au_id(SELECT au_idFROM titleauthorFROM titleauthor

    WHERE royaltyper < 30WHERE royaltyper < 30

    AND au_ord = 2)AND au_ord = 2)

    Here is the result set:Here is the result set:au_lname au_fnameau_lname au_fname

    ---------------------------------------- ------------------------------------------------------------ --------------------

    MacFeather StearnsMacFeather Stearns

  • 7/31/2019 Structured Query Language3

    16/78

    The inner query is evaluated, producing the ID numbers of theThe inner query is evaluated, producing the ID numbers of thethree authors who meet the subquery qualifications. The outerthree authors who meet the subquery qualifications. The outerquery is then evaluated. Notice that you can include more than onequery is then evaluated. Notice that you can include more than onecondition in the WHERE clause of both the inner and the outercondition in the WHERE clause of both the inner and the outerquery.query.

    Using a join, the same query is expressed like this:Using a join, the same query is expressed like this:

    USE pubsUSE pubs

    SELECT au_lname, au_fnameSELECT au_lname, au_fname

    FROM authors INNER JOIN titleauthor ON authors.au_id =FROM authors INNER JOIN titleauthor ON authors.au_id =

    titleauthor.au_idtitleauthor.au_idWHERE state = 'CA'WHERE state = 'CA'

    AND royaltyper < 30AND royaltyper < 30

    AND au_ord = 2AND au_ord = 2

    A join can always be expressed as a subquery. A subquery canA join can always be expressed as a subquery. A subquery canoften, but not always, be expressed as a join. This is because joinsoften, but not always, be expressed as a join. This is because joinsare symmetric: you can join table A to B in either order and get theare symmetric: you can join table A to B in either order and get thesame answer. The same is not true if a subquery is involved.same answer. The same is not true if a subquery is involved.

  • 7/31/2019 Structured Query Language3

    17/78

    Subqueries With NOT INSubqueries With NOT INSubqueries introduced with the keyword NOT IN also return a listSubqueries introduced with the keyword NOT IN also return a listof zero or more values.of zero or more values.

    This query finds the names of the publishers who have notThis query finds the names of the publishers who have notpublished business books.published business books.

    USE pubsUSE pubs

    SELECT pub_nameSELECT pub_name

    FROM publishersFROM publishers

    WHERE pub_id NOT INWHERE pub_id NOT IN(SELECT pub_id(SELECT pub_id

    FROM titlesFROM titles

    WHERE type = 'business')WHERE type = 'business')

    The query is exactly the same as the one in Subqueries with IN,The query is exactly the same as the one in Subqueries with IN,except that NOT IN is substituted for IN. However, this statementexcept that NOT IN is substituted for IN. However, this statementcannot be converted to a join. The analogous not-equal join has acannot be converted to a join. The analogous not-equal join has adifferent meaning: It finds the names of publishers who havedifferent meaning: It finds the names of publishers who havepublished some book that is not a business book. For informationpublished some book that is not a business book. For informationabout interpreting the meaning of joins not based on equalityabout interpreting the meaning of joins not based on equality

  • 7/31/2019 Structured Query Language3

    18/78

    Correlated SubqueriesCorrelated Subqueries Many queries can be evaluated by executing the subquery onceMany queries can be evaluated by executing the subquery once

    and substituting the resulting value or values into the WHEREand substituting the resulting value or values into the WHEREclause of the outer query. In queries that include aclause of the outer query. In queries that include a correlatedcorrelatedsubquerysubquery (also known as a repeating subquery), the subquery(also known as a repeating subquery), the subquerydepends on the outer query for its values. This means that thedepends on the outer query for its values. This means that thesubquery is executed repeatedly, once for each row that might besubquery is executed repeatedly, once for each row that might beselected by the outer query.selected by the outer query.

    This query finds the names of all authors who earn 100 percentThis query finds the names of all authors who earn 100 percentof the shared royalty (royaltyper) on a book.of the shared royalty (royaltyper) on a book.

    USE pubsUSE pubs

    SELECT au_lname, au_fnameSELECT au_lname, au_fname

    FROM authorsFROM authors

    WHERE 100 INWHERE 100 IN(SELECT royaltyper(SELECT royaltyper

    FROM titleauthorFROM titleauthor

    WHERE titleauthor.au_ID = authors.au_id)WHERE titleauthor.au_ID = authors.au_id)

  • 7/31/2019 Structured Query Language3

    19/78

    Correlated Subqueries with Comparison OperatorsCorrelated Subqueries with Comparison Operators

    Use a correlated subquery with a comparison operator to findUse a correlated subquery with a comparison operator to findsales where the quantity is less than the average quantity forsales where the quantity is less than the average quantity forsales of that title.sales of that title.

    USE pubsUSE pubsSELECT s1.ord_num, s1.title_id, s1.qtySELECT s1.ord_num, s1.title_id, s1.qty

    FROM sales s1FROM sales s1

    WHERE s1.qty

  • 7/31/2019 Structured Query Language3

    20/78

    Correlated Subqueries with AliasesCorrelated Subqueries with Aliases

    Correlated subqueries can be used in operations such as selecting dataCorrelated subqueries can be used in operations such as selecting datafrom a table referenced in the outer query. In this case a table aliasfrom a table referenced in the outer query. In this case a table alias(also called a correlation name) must be used to unambiguously(also called a correlation name) must be used to unambiguouslyspecify which table reference to use. For example, you can use aspecify which table reference to use. For example, you can use a

    correlated subquery to find the types of books published by more thancorrelated subquery to find the types of books published by more thanone publisher. Aliases are required to distinguish the two differentone publisher. Aliases are required to distinguish the two differentroles in which the titles table appears.roles in which the titles table appears.

    USE pubsUSE pubs

    SELECT DISTINCT t1.typeSELECT DISTINCT t1.type

    FROM titles t1FROM titles t1

    WHERE t1.type INWHERE t1.type IN(SELECT t2.type(SELECT t2.type

    FROM titles t2FROM titles t2

    WHERE t1.pub_id t2.pub_id)WHERE t1.pub_id t2.pub_id)

    Here is the result set:Here is the result set:

    typetype

    --------------------

    businessbusiness

    psychologypsychology

    (2 row(s) affected)(2 row(s) affected)

  • 7/31/2019 Structured Query Language3

    21/78

    Correlated Subqueries in a HAVING ClauseCorrelated Subqueries in a HAVING Clause

    A correlated subquery can also be used in the HAVING clause of an outerA correlated subquery can also be used in the HAVING clause of an outerquery. This construction can be used to find the types of books for whichquery. This construction can be used to find the types of books for whichthe maximum advance is more than twice the average within a giventhe maximum advance is more than twice the average within a givengroup.group.

    In this case, the subquery is evaluated once for each group defined in theIn this case, the subquery is evaluated once for each group defined in theouter query (once for each type of book).outer query (once for each type of book).

    USE pubsUSE pubs

    SELECT t1.typeSELECT t1.type

    FROM titles t1FROM titles t1GROUP BY t1.typeGROUP BY t1.type

    HAVING MAX(t1.advance) >=ALLHAVING MAX(t1.advance) >=ALL

    (SELECT 2 * AVG(t2.advance)(SELECT 2 * AVG(t2.advance)

    FROM titles t2FROM titles t2

    WHERE t1.type = t2.type)WHERE t1.type = t2.type)

    Here is the result set:Here is the result set:

    typetype

    ----------------

    mod_cookmod_cook

    (1 row(s) affected)(1 row(s) affected)

  • 7/31/2019 Structured Query Language3

    22/78

    EXISTS PredicateEXISTS Predicate

    Specifies a subquery to test for the existence of rows.Specifies a subquery to test for the existence of rows.

    SyntaxSyntax

    EXISTSEXISTS subquerysubquery

    ArgumentsArguments

    subquerysubquery

    Is a restricted SELECT statement (the COMPUTEIs a restricted SELECT statement (the COMPUTEclause, and the INTO keyword are not allowed). Forclause, and the INTO keyword are not allowed). Formore information, see the discussion of subqueries inmore information, see the discussion of subqueries inSELECTSELECT..

    Result TypesResult Types

    BooleanBoolean

    Result ValuesResult Values

    Returns TRUE if a subquery contains any rows.Returns TRUE if a subquery contains any rows.

  • 7/31/2019 Structured Query Language3

    23/78

    ExamplesExamples

    A. Use NULL in subquery to still return a result setA. Use NULL in subquery to still return a result set

    This example returns a result set with NULLThis example returns a result set with NULLspecified in the subquery and still evaluates tospecified in the subquery and still evaluates to

    TRUE by using EXISTS.TRUE by using EXISTS.

    USE NorthwindUSE NorthwindGOGO

    SELECT CategoryNameSELECT CategoryName

    FROM CategoriesFROM Categories

    WHERE EXISTS (SELECT NULL)WHERE EXISTS (SELECT NULL)ORDER BY CategoryName ASCORDER BY CategoryName ASC

    GOGO

  • 7/31/2019 Structured Query Language3

    24/78

    B. Compare queries using EXISTS and INB. Compare queries using EXISTS and IN

    This example compares two queries that are semantically equivalent. The firstThis example compares two queries that are semantically equivalent. The firstquery uses EXISTS and the second query uses IN. Note that both queries return thequery uses EXISTS and the second query uses IN. Note that both queries return thesame information.same information.

    USE pubsUSE pubs

    GOGOSELECT DISTINCT pub_nameSELECT DISTINCT pub_name

    FROM publishersFROM publishers

    WHERE EXISTSWHERE EXISTS

    (SELECT *(SELECT *

    FROM titlesFROM titles

    WHERE pub_id = publishers.pub_idWHERE pub_id = publishers.pub_idAND type = 'business')AND type = 'business')

    GOGO

    -- Or, using the IN clause:-- Or, using the IN clause:

    USE pubsUSE pubs

    GOGOSELECT distinct pub_nameSELECT distinct pub_name

    FROM publishersFROM publishers

    WHERE pub_id INWHERE pub_id IN

    (SELECT pub_id(SELECT pub_id

    FROM titlesFROM titles

    WHERE type = 'business')WHERE type = 'business')GOGO

  • 7/31/2019 Structured Query Language3

    25/78

    C. Compare queries using EXISTS and = ANYC. Compare queries using EXISTS and = ANY

    This example shows two queries to find authors who live in the same city as aThis example shows two queries to find authors who live in the same city as apublisher. The first query uses = ANY and the second uses EXISTS. Note that bothpublisher. The first query uses = ANY and the second uses EXISTS. Note that bothqueries return the same information.queries return the same information.

    USE pubsUSE pubsGOGO

    SELECT au_lname, au_fnameSELECT au_lname, au_fname

    FROM authorsFROM authors

    WHERE existsWHERE exists

    (SELECT *(SELECT *

    FROM publishersFROM publishersWHERE authors.city = publishers.city)WHERE authors.city = publishers.city)

    GOGO

    -- Or, using = ANY-- Or, using = ANY

    USE pubsUSE pubs

    GOGOSELECT au_lname, au_fnameSELECT au_lname, au_fname

    FROM authorsFROM authors

    WHERE city = ANYWHERE city = ANY

    (SELECT city(SELECT city

    FROM publishers)FROM publishers)

    GOGO

  • 7/31/2019 Structured Query Language3

    26/78

    D. Compare queries using EXISTS and IND. Compare queries using EXISTS and IN

    This example shows queries to find titles of books published by anyThis example shows queries to find titles of books published by anypublisher located in a city that begins with the letter B.publisher located in a city that begins with the letter B.

    USE pubsUSE pubs

    GOGO

    SELECT titleSELECT title

    FROM titlesFROM titles

    WHERE EXISTSWHERE EXISTS

    (SELECT *(SELECT *

    FROM publishersFROM publishers

    WHERE pub_id = titles.pub_idWHERE pub_id = titles.pub_id

    AND city LIKE 'B%')AND city LIKE 'B%')GOGO

    -- Or, using IN:-- Or, using IN:

    USE pubsUSE pubs

    GOGO

    SELECT titleSELECT title

    FROM titlesFROM titles

    WHERE pub_id INWHERE pub_id IN

    (SELECT pub_id(SELECT pub_id

    FROM publishersFROM publishers

    WHERE city LIKE 'B%')WHERE city LIKE 'B%')

    GOGO

  • 7/31/2019 Structured Query Language3

    27/78

    E. Use NOT EXISTSE. Use NOT EXISTS

    NOT EXISTS works the same as EXISTS, except the WHERENOT EXISTS works the same as EXISTS, except the WHERE

    clause in which NOT EXISTS is used is satisfied if no rows areclause in which NOT EXISTS is used is satisfied if no rows are

    returned by the subquery. This example finds the names ofreturned by the subquery. This example finds the names of

    publishers who do not publish business books.publishers who do not publish business books.

    USE pubsUSE pubs

    GOGO

    SELECT pub_nameSELECT pub_nameFROM publishersFROM publishers

    WHERE NOT EXISTSWHERE NOT EXISTS

    (SELECT *(SELECT *

    FROM titlesFROM titles

    WHERE pub_id = publishers.pub_idWHERE pub_id = publishers.pub_id

    AND type = 'business')AND type = 'business')

    ORDER BY pub_nameORDER BY pub_name

    GOGO

  • 7/31/2019 Structured Query Language3

    28/78

    GROUP BY FundamentalsGROUP BY FundamentalsThe GROUP BY clause contains the following components:The GROUP BY clause contains the following components:

    One or more aggregate-free expressions. These are usuallyOne or more aggregate-free expressions. These are usuallyreferences to the grouping columns.references to the grouping columns. Optionally, the ALL keyword, which specifies that all groupsOptionally, the ALL keyword, which specifies that all groups

    produced by the GROUP BY clause are returned, even if someproduced by the GROUP BY clause are returned, even if some of theof thegroups do not have any rows that meet the searchgroups do not have any rows that meet the search conditions.conditions.

    In addition, the HAVING clause is typically used in conjunction with theIn addition, the HAVING clause is typically used in conjunction with the

    GROUP BY clause, although HAVING can be specified separately.GROUP BY clause, although HAVING can be specified separately.

    You can group by an expression as long as it does not include aggregateYou can group by an expression as long as it does not include aggregatefunctions, for example:functions, for example:

    SELECT DATEPART(yy, HireDate) AS Year,SELECT DATEPART(yy, HireDate) AS Year,

    COUNT(*) AS NumberOfHiresCOUNT(*) AS NumberOfHiresFROM Northwind.dbo.EmployeesFROM Northwind.dbo.Employees

    GROUP BY DATEPART(yy, HireDate)GROUP BY DATEPART(yy, HireDate)

  • 7/31/2019 Structured Query Language3

    29/78

    In a GROUP BY, you must specify the name of a table or view column,In a GROUP BY, you must specify the name of a table or view column,not the name of a result set column assigned with an AS clause. Fornot the name of a result set column assigned with an AS clause. Forexample, replacing the GROUP BY DATEPART(yy, HireDate) clauseexample, replacing the GROUP BY DATEPART(yy, HireDate) clauseearlier with GROUP BY Year is not legal.earlier with GROUP BY Year is not legal.

    You can list more than one column in the GROUP BY clause to nestYou can list more than one column in the GROUP BY clause to nest

    groups; that is, you can group a table by any combination of columns.groups; that is, you can group a table by any combination of columns.For example, this query finds the average price and the sum of year-to-For example, this query finds the average price and the sum of year-to-date sales, grouped by type and publisher ID:date sales, grouped by type and publisher ID:

    USE pubsUSE pubs

    SELECT type, pub_id, 'avg' = AVG(price), 'sum' = sum(ytd_sales)SELECT type, pub_id, 'avg' = AVG(price), 'sum' = sum(ytd_sales)

    FROM titlesFROM titles

    GROUP BY type, pub_idGROUP BY type, pub_id

    Here is the result set:Here is the result set:

    type pub_id avg sumtype pub_id avg sum

    ------------ ------ ---------------------- ----------------------- ------ ---------------------- -----------

    business 0736 11.96 18722business 0736 11.96 18722

    business 1389 17.31 12066business 1389 17.31 12066

    mod_cook 0877 11.49 24278mod_cook 0877 11.49 24278

    popular_comp 1389 21.48 12875popular_comp 1389 21.48 12875

    psychology 0736 45.93 9564psychology 0736 45.93 9564

    psychology 0877 21.59 375psychology 0877 21.59 375

    trad_cook 0877 15.96 19566trad_cook 0877 15.96 19566

    UNDECIDED 0877 (null) (null)UNDECIDED 0877 (null) (null)

    (8 row(s) affected)(8 row(s) affected)

  • 7/31/2019 Structured Query Language3

    30/78

    HAVING ClauseHAVING Clause The HAVING clause sets conditions on the GROUP BY clause similar toThe HAVING clause sets conditions on the GROUP BY clause similar to

    the way WHERE interacts with SELECT. The WHERE search condition isthe way WHERE interacts with SELECT. The WHERE search condition isapplied before the grouping operation occurs; the HAVING searchapplied before the grouping operation occurs; the HAVING search

    condition is applied after the grouping operation occurs. The HAVINGcondition is applied after the grouping operation occurs. The HAVINGsyntax is exactly like the WHERE syntax, except HAVING can containsyntax is exactly like the WHERE syntax, except HAVING can containaggregate functions. HAVING clauses can reference any of the itemsaggregate functions. HAVING clauses can reference any of the itemsthat appear in the select list.that appear in the select list.

    This query finds publishers who have had year-to-date sales greaterThis query finds publishers who have had year-to-date sales greaterthan $40,000:than $40,000:

    USE pubsUSE pubsSELECT pub_id, total = SUM(ytd_sales)SELECT pub_id, total = SUM(ytd_sales)

    FROM titlesFROM titles

    GROUP BY pub_idGROUP BY pub_id

    HAVING SUM(ytd_sales) > 40000HAVING SUM(ytd_sales) > 40000

    Here is the result set:Here is the result set:pub_id totalpub_id total

    ------ ----------------- -----------

    0877 442190877 44219

    (1 row(s) affected)(1 row(s) affected)

  • 7/31/2019 Structured Query Language3

    31/78

    To make sure there are at least six books involved in the calculationsTo make sure there are at least six books involved in the calculationsfor each publisher, this example uses HAVING COUNT(*) > 5 tofor each publisher, this example uses HAVING COUNT(*) > 5 toeliminate the publishers that return totals for fewer than six books:eliminate the publishers that return totals for fewer than six books:

    USE pubsUSE pubs

    SELECT pub_id, total = SUM(ytd_sales)SELECT pub_id, total = SUM(ytd_sales)

    FROM titlesFROM titlesGROUP BY pub_idGROUP BY pub_id

    HAVING COUNT(*) > 5HAVING COUNT(*) > 5

    Here is the result set:Here is the result set:

    pub_id totalpub_id total

    ------ ----------------- -----------0877 442190877 44219

    1389 249411389 24941

    (2 row(s) affected)(2 row(s) affected)

    Understanding the correct sequence in which the WHERE, GROUP BY,Understanding the correct sequence in which the WHERE, GROUP BY,

    and HAVING clauses are applied helps in coding efficient queries:and HAVING clauses are applied helps in coding efficient queries:

    The WHERE clause is used to filter the rows that result from theThe WHERE clause is used to filter the rows that result from theoperations specified in the FROM clause.operations specified in the FROM clause.

    The GROUP BY clause is used to group the output of the WHEREThe GROUP BY clause is used to group the output of the WHEREclause.clause.

    The HAVING clause is used to filter rows from the grouped result.The HAVING clause is used to filter rows from the grouped result.

  • 7/31/2019 Structured Query Language3

    32/78

    The following query shows HAVING with an aggregate function. ItThe following query shows HAVING with an aggregate function. Itgroups the rows in the titles table by type and eliminates thegroups the rows in the titles table by type and eliminates thegroups that include only one book.groups that include only one book.

    USE pubsUSE pubs

    SELECT typeSELECT type

    FROM titlesFROM titles

    GROUP BY typeGROUP BY type

    HAVING COUNT(*) > 1HAVING COUNT(*) > 1

    Here is the result set:Here is the result set:typetype

    ------------------------

    businessbusiness

    mod_cookmod_cook

    popular_comppopular_comppsychologypsychology

    trad_cooktrad_cook

    (5 row(s) affected)(5 row(s) affected)

  • 7/31/2019 Structured Query Language3

    33/78

    This is an example of a HAVING clause without aggregateThis is an example of a HAVING clause without aggregate

    functions. It groups the rows in titles by type and eliminates thosefunctions. It groups the rows in titles by type and eliminates those

    types that do not start with the letter p.types that do not start with the letter p.

    USE pubsUSE pubs

    SELECT typeSELECT type

    FROM titlesFROM titles

    GROUP BY typeGROUP BY type

    HAVING type LIKE 'p%'HAVING type LIKE 'p%'

    Here is the result set:Here is the result set:

    typetype

    ------------------------

    popular_comppopular_comp

    psychologypsychology

    (2 row(s) affected)(2 row(s) affected)

  • 7/31/2019 Structured Query Language3

    34/78

    When multiple conditions are included in HAVING, theyWhen multiple conditions are included in HAVING, they

    are combined with AND, OR, or NOT. The followingare combined with AND, OR, or NOT. The following

    example shows how to group titles by publisher,example shows how to group titles by publisher,

    including only those publishers with identificationincluding only those publishers with identificationnumbers greater than 0800, who have paid more thannumbers greater than 0800, who have paid more than

    $15,000 in total advances, and who sell books for an$15,000 in total advances, and who sell books for an

    average of less than $20.average of less than $20.

    SELECT pub_id, SUM(advance) AS AmountAdvanced,SELECT pub_id, SUM(advance) AS AmountAdvanced,

    AVG(price) AS AveragePriceAVG(price) AS AveragePrice

    FROM pubs.dbo.titlesFROM pubs.dbo.titles

    WHERE pub_id > '0800'WHERE pub_id > '0800'GROUP BY pub_idGROUP BY pub_id

    HAVING SUM(advance) > $15000HAVING SUM(advance) > $15000

    AND AVG(price) < $20AND AVG(price) < $20

  • 7/31/2019 Structured Query Language3

    35/78

    ORDER BY can be used to order the output of a GROUP BY clause.ORDER BY can be used to order the output of a GROUP BY clause.

    This example shows using the ORDER BY clause to define theThis example shows using the ORDER BY clause to define the

    order in which the rows from a GROUP BY clause are returned:order in which the rows from a GROUP BY clause are returned:

    SELECT pub_id, SUM(advance) AS AmountAdvanced,SELECT pub_id, SUM(advance) AS AmountAdvanced,

    AVG(price) AS AveragePriceAVG(price) AS AveragePrice

    FROM pubs.dbo.titlesFROM pubs.dbo.titles

    WHERE pub_id > '0800'WHERE pub_id > '0800'

    AND price >= $5AND price >= $5GROUP BY pub_idGROUP BY pub_id

    HAVING SUM(advance) > $15000HAVING SUM(advance) > $15000

    AND AVG(price) < $20AND AVG(price) < $20

    ORDER BY pub_id DESCORDER BY pub_id DESC

    OUTER JOINS

  • 7/31/2019 Structured Query Language3

    36/78

    OUTER JOINSOUTER JOINS Inner joins only return rows when there is at least one row fromInner joins only return rows when there is at least one row from

    both tables that matches the join condition. In a sense, inner joinsboth tables that matches the join condition. In a sense, inner joins

    eliminate the rows that do not match with a row from the othereliminate the rows that do not match with a row from the othertable. Outer joins, however, return all rows from at least one of thetable. Outer joins, however, return all rows from at least one of the

    tables or views mentioned in the FROM clause, so long as thosetables or views mentioned in the FROM clause, so long as those

    rows meet any WHERE or HAVING search conditions. All rows willrows meet any WHERE or HAVING search conditions. All rows will

    be retrieved from the left table referenced with a left outer join, andbe retrieved from the left table referenced with a left outer join, and

    all rows from the right table referenced in a right outer join. Allall rows from the right table referenced in a right outer join. Allrows from both tables are returned in a full outer join.rows from both tables are returned in a full outer join.

    LEFT OUTER JOIN or LEFT JOINLEFT OUTER JOIN or LEFT JOIN

    RIGHT OUTER JOIN or RIGHT JOINRIGHT OUTER JOIN or RIGHT JOIN

    FULL OUTER JOIN or FULL JOINFULL OUTER JOIN or FULL JOIN

  • 7/31/2019 Structured Query Language3

    37/78

    Using Left Outer JoinsUsing Left Outer Joins

    Consider a join of the authors table and the publishers table onConsider a join of the authors table and the publishers table on

    their city columns. The results show only the authors who live intheir city columns. The results show only the authors who live in

    cities where a publisher is located (in this case, Abraham Bennetcities where a publisher is located (in this case, Abraham Bennet

    and Cheryl Carson).and Cheryl Carson).

    To include all authors in the results, regardless of whether aTo include all authors in the results, regardless of whether a

    publisher is located in the same city, use a SQL-92 left outer join.publisher is located in the same city, use a SQL-92 left outer join.

    Heres what the query and results of the Transact-SQL left outerHeres what the query and results of the Transact-SQL left outer

    join look like:join look like:

    USE pubsUSE pubs

    SELECT a.au_fname, a.au_lname, p.pub_nameSELECT a.au_fname, a.au_lname, p.pub_name

    FROM authors a LEFT OUTER JOIN publishers pFROM authors a LEFT OUTER JOIN publishers p

    ON a.city = p.cityON a.city = p.cityORDER BY p.pub_name ASC, a.au_lname ASC, a.au_fname ASCORDER BY p.pub_name ASC, a.au_lname ASC, a.au_fname ASC

  • 7/31/2019 Structured Query Language3

    38/78

    Here is the result set:Here is the result set:

    au_fname au_lname pub_nameau_fname au_lname pub_name

    -------------------- ------------------------------ ------------------------------------- ------------------------------ -----------------

    Reginald Blotchet-Halls NULLReginald Blotchet-Halls NULL

    Michel DeFrance NULLMichel DeFrance NULL

    Innes del Castillo NULLInnes del Castillo NULL

    Ann Dull NULLAnn Dull NULL

    Marjorie Green NULLMarjorie Green NULL

    Morningstar Greene NULLMorningstar Greene NULL

    Burt Gringlesby NULLBurt Gringlesby NULL

    Sheryl Hunter NULLSheryl Hunter NULL

    Livia Karsen NULLLivia Karsen NULL

    Charlene Locksley NULLCharlene Locksley NULL

    Stearns MacFeather NULLStearns MacFeather NULL

    The LEFT OUTER JOIN includes all rows in the authors table in theThe LEFT OUTER JOIN includes all rows in the authors table in the

    results, whether or not there is a match on the city column in theresults, whether or not there is a match on the city column in the

    publishers table. Notice that in the results there is no matchingpublishers table. Notice that in the results there is no matching

    data for most of the authors listed, so these rows contain nulldata for most of the authors listed, so these rows contain null

    values in the pub_name column.values in the pub_name column.

  • 7/31/2019 Structured Query Language3

    39/78

    Using Right Outer JoinsUsing Right Outer Joins

    Consider a join of the authors table and the publishers table onConsider a join of the authors table and the publishers table on

    their city columns. The results show only the authors who live intheir city columns. The results show only the authors who live in

    cities where a publisher is located (in this case, Abraham Bennetcities where a publisher is located (in this case, Abraham Bennet

    and Cheryl Carson). The SQL-92 right outer join operator, RIGHTand Cheryl Carson). The SQL-92 right outer join operator, RIGHT

    OUTER JOIN, indicates all rows in the second table are to beOUTER JOIN, indicates all rows in the second table are to be

    included in the results, regardless of whether there is matchingincluded in the results, regardless of whether there is matching

    data in the first table.data in the first table.

    USE pubsUSE pubs

    SELECT a.au_fname, a.au_lname, p.pub_nameSELECT a.au_fname, a.au_lname, p.pub_name

    FROM authors AS a RIGHT OUTER JOIN publishers AS pFROM authors AS a RIGHT OUTER JOIN publishers AS p

    ON a.city = p.cityON a.city = p.cityORDER BY p.pub_name ASC, a.au_lname ASC, a.au_fname ASCORDER BY p.pub_name ASC, a.au_lname ASC, a.au_fname ASC

  • 7/31/2019 Structured Query Language3

    40/78

    Here is the result set:Here is the result set:

    au_fname au_lname pub_nameau_fname au_lname pub_name

    -------------------- ------------------------ --------------------------------------------------- ------------------------ -------------------------------

    Abraham Bennet Algodata InfosystemsAbraham Bennet Algodata InfosystemsCheryl Carson Algodata InfosystemsCheryl Carson Algodata Infosystems

    NULL NULL Binnet & HardleyNULL NULL Binnet & Hardley

    NULL NULL Five Lakes PublishingNULL NULL Five Lakes Publishing

    NULL NULL GGG&GNULL NULL GGG&G

    NULL NULL Lucerne PublishingNULL NULL Lucerne Publishing

    NULL NULL New Moon BooksNULL NULL New Moon Books

    NULL NULL Ramona PublishersNULL NULL Ramona Publishers

    NULL NULL Scootney BooksNULL NULL Scootney Books

    (9 row(s) affected)(9 row(s) affected)

  • 7/31/2019 Structured Query Language3

    41/78

  • 7/31/2019 Structured Query Language3

    42/78

    An outer join can be further restricted by using a predicate (likeAn outer join can be further restricted by using a predicate (like

    comparing the join to a constant). This example contains the samecomparing the join to a constant). This example contains the same

    right outer join, but eliminates all titles that have sold less than 50right outer join, but eliminates all titles that have sold less than 50

    copies:copies:

    USE pubsUSE pubs

    SELECT s.stor_id, s.qty, t.titleSELECT s.stor_id, s.qty, t.title

    FROM sales s RIGHT OUTER JOIN titles tFROM sales s RIGHT OUTER JOIN titles t

    ON s.title_id = t.title_idON s.title_id = t.title_idAND s.qty > 50AND s.qty > 50

    ORDER BY s.stor_id ASCORDER BY s.stor_id ASC

    The tables or views in the FROM clause can be specified in anyThe tables or views in the FROM clause can be specified in any

    order with an inner join or full outer join; however, the order oforder with an inner join or full outer join; however, the order oftables or views specified when using either a left or right outer jointables or views specified when using either a left or right outer join

    is important. For more information about table ordering with left oris important. For more information about table ordering with left or

    right outer joins, see Using Outer Joins.right outer joins, see Using Outer Joins.

  • 7/31/2019 Structured Query Language3

    43/78

    SUSE b

  • 7/31/2019 Structured Query Language3

    44/78

    USE pubsUSE pubs

    SELECT a.au_fname, a.au_lname, p.pub_nameSELECT a.au_fname, a.au_lname, p.pub_name

    FROM authors a FULL OUTER JOIN publishers pFROM authors a FULL OUTER JOIN publishers p

    ON a.city = p.cityON a.city = p.city

    ORDER BY p.pub_name ASC, a.au_lname ASC, a.au_fname ASCORDER BY p.pub_name ASC, a.au_lname ASC, a.au_fname ASC

    Here is the result set:Here is the result set:

    au_fname au_lname pub_nameau_fname au_lname pub_name

    -------------------- ---------------------------- ---------------------------------------- ---------------------------- --------------------Reginald Blotchet-Halls NULLReginald Blotchet-Halls NULL

    Michel DeFrance NULLMichel DeFrance NULL

    Innes del Castillo NULLInnes del Castillo NULL

    Ann Dull NULLAnn Dull NULLMarjorie Green NULLMarjorie Green NULL

    Morningstar Greene NULLMorningstar Greene NULL

    Burt Gringlesby NULLBurt Gringlesby NULL

    Alb t Ri NULLAlb t Ri NULL

  • 7/31/2019 Structured Query Language3

    45/78

    Albert Ringer NULLAlbert Ringer NULL

    Anne Ringer NULLAnne Ringer NULL

    Meander Smith NULLMeander Smith NULL

    Dean Straight NULLDean Straight NULL

    Dirk Stringer NULLDirk Stringer NULL

    Johnson White NULLJohnson White NULL

    Akiko Yokomoto NULLAkiko Yokomoto NULL

    Abraham Bennet Algodata InfosystemsAbraham Bennet Algodata Infosystems

    Cheryl Carson Algodata InfosystemsCheryl Carson Algodata Infosystems

    NULL NULL Binnet & HardleyNULL NULL Binnet & Hardley

    NULL NULL Five Lakes PublishingNULL NULL Five Lakes Publishing

    NULL NULL GGG&GNULL NULL GGG&G

    NULL NULL Lucerne PublishingNULL NULL Lucerne PublishingNULL NULL New Moon BooksNULL NULL New Moon Books

    NULL NULL Ramona PublishersNULL NULL Ramona Publishers

    NULL NULL Scootney BooksNULL NULL Scootney Books

    (30 row(s) affected)(30 row(s) affected)

    CROSS TABSCROSS TABS

  • 7/31/2019 Structured Query Language3

    46/78

    CROSS TABSCROSS TABSSometimes it is necessary to rotate results so that columns areSometimes it is necessary to rotate results so that columns are

    presented horizontally and rows are presented vertically. This is knownpresented horizontally and rows are presented vertically. This is knownby various phrases: creating a pivot table, creating a cross-tab report,by various phrases: creating a pivot table, creating a cross-tab report,or rotating data.or rotating data.

    Assume there is a table Pivot that has one row per quarter, so that aAssume there is a table Pivot that has one row per quarter, so that aselect of Pivot would report the quarters vertically:select of Pivot would report the quarters vertically:

    Year Quarter AmountYear Quarter Amount

    ---- ------- ---------- ------- ------

    1990 1 1.11990 1 1.1

    1990 2 1.21990 2 1.2

    1990 3 1.31990 3 1.31990 4 1.41990 4 1.4

    1991 1 2.11991 1 2.1

    1991 2 2.21991 2 2.2

    1991 3 2.31991 3 2.3

    1991 4 2.41991 4 2.4

    A report must be produced with a table that contains one row for eachA report must be produced with a table that contains one row for eachyear, with the values for each quarter appearing in a separate column.year, with the values for each quarter appearing in a separate column.

    Year Q1 Q2 Q3 Q4Year Q1 Q2 Q3 Q4

    ---- --- --- --- ------- --- --- --- ---

    1990 1.1 1.2 1.3 1.41990 1.1 1.2 1.3 1.4

    1991 2.1 2.2 2.3 2.41991 2.1 2.2 2.3 2.4

  • 7/31/2019 Structured Query Language3

    47/78

    INSERT INTO Pivot VALUES (1991 3 2 3)INSERT INTO Pivot VALUES (1991 3 2 3)

  • 7/31/2019 Structured Query Language3

    48/78

    INSERT INTO Pivot VALUES (1991, 3, 2.3)INSERT INTO Pivot VALUES (1991, 3, 2.3)

    INSERT INTO Pivot VALUES (1991, 4, 2.4)INSERT INTO Pivot VALUES (1991, 4, 2.4)

    GOGO

    SET NOCOUNT OFFSET NOCOUNT OFF

    GOGO

    Here is the SELECT statement to create the rotated results:Here is the SELECT statement to create the rotated results:

    SELECT Year,SELECT Year,

    SUM(CASE Quarter WHEN 1 THEN Amount ELSE 0 END) AS Q1,SUM(CASE Quarter WHEN 1 THEN Amount ELSE 0 END) AS Q1,

    SUM(CASE Quarter WHEN 2 THEN Amount ELSE 0 END) AS Q2,SUM(CASE Quarter WHEN 2 THEN Amount ELSE 0 END) AS Q2,

    SUM(CASE Quarter WHEN 3 THEN Amount ELSE 0 END) AS Q3,SUM(CASE Quarter WHEN 3 THEN Amount ELSE 0 END) AS Q3,

    SUM(CASE Quarter WHEN 4 THEN Amount ELSE 0 END) AS Q4SUM(CASE Quarter WHEN 4 THEN Amount ELSE 0 END) AS Q4

    FROM PivotFROM Pivot

    GROUP BY YearGROUP BY YearGOGO

  • 7/31/2019 Structured Query Language3

    49/78

    Cartesian ProductsCartesian Products

    A Cartesian product is formedA Cartesian product is formedwhen:when:

    A join condition is omittedA join condition is omitted

    A join condition is invalidA join condition is invalid All rows in the first table are joinedAll rows in the first table are joined

    to all rows in the second tableto all rows in the second table

    To avoid a Cartesian product,To avoid a Cartesian product,

    always include a valid joinalways include a valid join

    condition in acondition in a WHEREWHERE clause.clause.

    Using Cross JoinsUsing Cross Joins

  • 7/31/2019 Structured Query Language3

    50/78

    Using Cross JoinsUsing Cross Joins

    A cross join that does not have a WHERE clause produces theA cross join that does not have a WHERE clause produces thecartesiancartesian product of the tables involved in the join. The size of aproduct of the tables involved in the join. The size of acartesiancartesian product result set is the number of rows in the first tableproduct result set is the number of rows in the first table

    multiplied by the number of rows in the second table. Here is anmultiplied by the number of rows in the second table. Here is anexample of a Transact-SQL cross join:example of a Transact-SQL cross join:

    USE pubsUSE pubs

    SELECT au_fname, au_lname, pub_nameSELECT au_fname, au_lname, pub_name

    FROM authors CROSS JOIN publishersFROM authors CROSS JOIN publishersORDER BY au_lname DESCORDER BY au_lname DESC

    The result set contains 184 rows (authors has 23 rows and publishersThe result set contains 184 rows (authors has 23 rows and publishers

    has 8; 23 multiplied by 8 equals 184).has 8; 23 multiplied by 8 equals 184).

    However if a WHERE clause is added the cross join behaves as anHowever if a WHERE clause is added the cross join behaves as an

  • 7/31/2019 Structured Query Language3

    51/78

    However, if a WHERE clause is added, the cross join behaves as anHowever, if a WHERE clause is added, the cross join behaves as aninner join. For example, the following Transact-SQL queriesinner join. For example, the following Transact-SQL queriesproduce the same result set:produce the same result set:

    USE pubsUSE pubs

    SELECT au_fname, au_lname, pub_nameSELECT au_fname, au_lname, pub_nameFROM authors CROSS JOIN publishersFROM authors CROSS JOIN publishers

    WHERE authors.city = publishers.cityWHERE authors.city = publishers.city

    ORDER BY au_lname DESCORDER BY au_lname DESC

    -- Or-- OrUSE pubsUSE pubs

    SELECT au_fname, au_lname, pub_nameSELECT au_fname, au_lname, pub_name

    FROM authors INNER JOIN publishersFROM authors INNER JOIN publishers

    ON authors.city = publishers.cityON authors.city = publishers.city

    ORDER BY au_lname DESCORDER BY au_lname DESC

    UsingUsing SelfSelf--JoinsJoins

  • 7/31/2019 Structured Query Language3

    52/78

    UsingUsing SelfSelf--JoinsJoins

    A table can beA table can bejoinedjoined to itself in ato itself in a selfself--joinjoin. For example, you can. For example, you canuse ause a selfself--joinjoin to find out which authors in Oakland, California liveto find out which authors in Oakland, California livein the same zip code area.in the same zip code area.

    Because this query involves aBecause this query involves ajoinjoin of the authors table with itself,of the authors table with itself,the authors table appears in two roles. To distinguish these roles,the authors table appears in two roles. To distinguish these roles,you must give the authors table two different aliases (au1 and au2)you must give the authors table two different aliases (au1 and au2)in the FROM clause. These aliases are used to qualify the columnin the FROM clause. These aliases are used to qualify the columnnames in the rest of the query. Thenames in the rest of the query. The selfself--joinjoin Transact-SQLTransact-SQLstatement looks like this:statement looks like this:

    USE pubsUSE pubs

    SELECT au1.au_fname, au1.au_lname, au2.au_fname,SELECT au1.au_fname, au1.au_lname, au2.au_fname,au2.au_lnameau2.au_lname

    FROM authors au1 INNERFROM authors au1 INNERJOINJOIN authors au2authors au2

    ON au1.zip = au2.zipON au1.zip = au2.zipWHERE au1.city = 'Oakland'WHERE au1.city = 'Oakland'

    ORDER BY au1.au_fname ASC, au1.au_lname ASCORDER BY au1.au_fname ASC, au1.au_lname ASC

    Here is the result set:Here is the result set:

  • 7/31/2019 Structured Query Language3

    53/78

    Here is the result set:Here is the result set:

    au_fname au_lname au_fname au_lnameau_fname au_lname au_fname au_lname

    -------------------- ------------------- -------------------- ----------------------------- ------------------- -------------------- ---------

    Dean Straight Dean StraightDean Straight Dean Straight

    Dean Straight Dirk StringerDean Straight Dirk StringerDean Straight Livia KarsenDean Straight Livia Karsen

    Dirk Stringer Dean StraightDirk Stringer Dean Straight

    Dirk Stringer Dirk StringerDirk Stringer Dirk Stringer

    Dirk Stringer Livia KarsenDirk Stringer Livia Karsen

    Livia Karsen Dean StraightLivia Karsen Dean Straight

    Livia Karsen Dirk StringerLivia Karsen Dirk Stringer

    Livia Karsen Livia KarsenLivia Karsen Livia Karsen

    Marjorie Green Marjorie GreenMarjorie Green Marjorie Green

    Stearns MacFeather Stearns MacFeatherStearns MacFeather Stearns MacFeather

    (11 row(s) affected)(11 row(s) affected)

    To eliminate the rows in the results where the authors match themselves and toTo eliminate the rows in the results where the authors match themselves and to

  • 7/31/2019 Structured Query Language3

    54/78

    To eliminate the rows in the results where the authors match themselves and toTo eliminate the rows in the results where the authors match themselves and toeliminate rows that are identical except the order of the authors is reversed, makeeliminate rows that are identical except the order of the authors is reversed, makethis change to the Transact-SQLthis change to the Transact-SQL selfself--joinjoin query:query:

    USE pubsUSE pubs

    SELECT au1.au_fname, au1.au_lname, au2.au_fname, au2.au_lnameSELECT au1.au_fname, au1.au_lname, au2.au_fname, au2.au_lnameFROM authors au1 INNERFROM authors au1 INNERJOINJOIN authors au2authors au2

    ON au1.zip = au2.zipON au1.zip = au2.zip

    WHERE au1.city = 'Oakland'WHERE au1.city = 'Oakland'

    AND au1.state = 'CA'AND au1.state = 'CA'

    AND au1.au_id < au2.au_idAND au1.au_id < au2.au_id

    ORDER BY au1.au_lname ASC, au1.au_fname ASCORDER BY au1.au_lname ASC, au1.au_fname ASCHere is the result set:Here is the result set:

    au_fname au_lname au_fnameau_fname au_lname au_fnameau_lnameau_lname

    ------------ ----------------- -------------------- -------------------------------- ----------------- -------------------- --------------------

    Dean Straight Dirk StringerDean Straight Dirk StringerDean Straight Livia KarsenDean Straight Livia Karsen

    Dirk Stringer Livia KarsenDirk Stringer Livia Karsen(3 row(s) affected)(3 row(s) affected)It is now clear that Dean Straight, Dirk Stringer, and Livia Karsen all have the same zipIt is now clear that Dean Straight, Dirk Stringer, and Livia Karsen all have the same zipcode and live in Oakland, California.code and live in Oakland, California.

  • 7/31/2019 Structured Query Language3

    55/78

    Batch ExamplesBatch Examples

  • 7/31/2019 Structured Query Language3

    56/78

    atc a p esp

    These examples are scripts that use the SQL Server QueryThese examples are scripts that use the SQL Server QueryAnalyzer and osql GO statement to define batch boundaries.Analyzer and osql GO statement to define batch boundaries.

    Here is an example that creates a view. Because CREATE VIEWHere is an example that creates a view. Because CREATE VIEWmust be the only statement in a batch, the GO statements aremust be the only statement in a batch, the GO statements arerequired to isolate the CREATE VIEW statement from the USErequired to isolate the CREATE VIEW statement from the USEand SELECT statements around it.and SELECT statements around it.

    USE pubsUSE pubs

    GO /* Signals the end of the batch */GO /* Signals the end of the batch */

    CREATE VIEW auth_titlesCREATE VIEW auth_titles

    ASAS

    SELECT *SELECT *

    FROM authorsFROM authors

    GO /* Signals the end of the batch */GO /* Signals the end of the batch */SELECT *SELECT *

    FROM auth_titlesFROM auth_titles

    GO /* Signals the end of the batch */GO /* Signals the end of the batch */

    This example show several batches combined into one transaction. The BEGIN TRANSACTION and COMMITThis example show several batches combined into one transaction. The BEGIN TRANSACTION and COMMITstatements delimit the transaction boundaries The BEGIN TRANSACTION USE CREATE TABLE SELECT andstatements delimit the transaction boundaries The BEGIN TRANSACTION USE CREATE TABLE SELECT and

  • 7/31/2019 Structured Query Language3

    57/78

    statements delimit the transaction boundaries. The BEGIN TRANSACTION, USE, CREATE TABLE, SELECT, andstatements delimit the transaction boundaries. The BEGIN TRANSACTION, USE, CREATE TABLE, SELECT, andCOMMIT statements are all in their own, single-statement batches. All of the INSERT statements are included inCOMMIT statements are all in their own, single-statement batches. All of the INSERT statements are included inone batch.one batch.

    BEGIN TRANSACTIONBEGIN TRANSACTION

    GOGO

    USE pubsUSE pubs

    GOGO

    CREATE TABLE mycompaniesCREATE TABLE mycompanies((

    id_num int IDENTITY(100, 5),id_num int IDENTITY(100, 5),

    company_name nvarchar(100)company_name nvarchar(100)

    ))

    GOGO

    INSERT mycompanies (company_name)INSERT mycompanies (company_name)

    VALUES ('New Moon Books')VALUES ('New Moon Books')

    INSERT mycompanies (company_name)INSERT mycompanies (company_name)

    VALUES ('Binnet & Hardley')VALUES ('Binnet & Hardley')INSERT mycompanies (company_name)INSERT mycompanies (company_name)

    VALUES ('Algodata Infosystems')VALUES ('Algodata Infosystems')

    INSERT mycompanies (company_name)INSERT mycompanies (company_name)

    VALUES ('Five Lakes Publishing')VALUES ('Five Lakes Publishing')

    INSERT mycompanies (company_name)INSERT mycompanies (company_name)

    VALUES ('Ramona Publishers')VALUES ('Ramona Publishers')

    INSERT mycompanies (company_name)INSERT mycompanies (company_name)

    VALUES ('GGG&G')VALUES ('GGG&G')

    INSERT mycompanies (company_name)INSERT mycompanies (company_name)

    VALUES ('Scootney Books')VALUES ('Scootney Books')

    INSERT mycompanies (company_name)INSERT mycompanies (company_name)

    VALUES ('Lucerne Publishing')VALUES ('Lucerne Publishing')

    GOGO

    SELECT *SELECT *

    FROM mycompaniesFROM mycompanies

    ORDER BY company_name ASCORDER BY company_name ASC

    GOGOCOMMITCOMMIT

    STORED PROCEDURESSTORED PROCEDURES

  • 7/31/2019 Structured Query Language3

    58/78

    STORED PROCEDURESSTORED PROCEDURESWhen you create an application with Microsoft SQL Server, theWhen you create an application with Microsoft SQL Server, theTransact-SQL programming language is the primary programmingTransact-SQL programming language is the primary programminginterface between your applications and the SQL Server database.interface between your applications and the SQL Server database.

    When you use Transact-SQL programs, two methods are availableWhen you use Transact-SQL programs, two methods are availablefor storing and executing the programs. You can store the programsfor storing and executing the programs. You can store the programslocally and create applications that send the commands to SQLlocally and create applications that send the commands to SQLServer and process the results, or you can store the programs asServer and process the results, or you can store the programs asstored proceduresstored procedures in SQL Server and create applications thatin SQL Server and create applications thatexecute the stored procedures and process the results.execute the stored procedures and process the results.

    Stored procedures in SQL Server are similar to procedures in otherStored procedures in SQL Server are similar to procedures in otherprogramming languages in that they can:programming languages in that they can:

    Accept input parameters and return multiple values in the form ofAccept input parameters and return multiple values in the form ofoutput parameters to the calling procedure or batch.output parameters to the calling procedure or batch.

    Contain programming statements to perform operations in theContain programming statements to perform operations in thedatabase, including the ability to call other procedures.database, including the ability to call other procedures.

    Return a status value to a calling procedure or batch to indicateReturn a status value to a calling procedure or batch to indicatesuccess or failure (and the reason for failure).success or failure (and the reason for failure).

    The benefits of using stored procedures are:The benefits of using stored procedures are:

  • 7/31/2019 Structured Query Language3

    59/78

    g pg p

    They allow modular programming.They allow modular programming.

    You can create the procedure once, store it in the database, and call it anyYou can create the procedure once, store it in the database, and call it anynumber of times in your program. They can be created by a person whonumber of times in your program. They can be created by a person who

    specializes in database programming, and they can be modifiedspecializes in database programming, and they can be modifiedindependently of the program source code.independently of the program source code. Faster execution.Faster execution.

    In situations where the operation requires a large amount of Transact-SQLIn situations where the operation requires a large amount of Transact-SQLcode, or if the operation is performed repetitively, stored procedures cancode, or if the operation is performed repetitively, stored procedures canbe faster. They are parsed and optimized when they are created, and an in-be faster. They are parsed and optimized when they are created, and an in-memory version of the procedure can be used after the procedure ismemory version of the procedure can be used after the procedure is

    executed the first time. Transact-SQL statements repeatedly sent from theexecuted the first time. Transact-SQL statements repeatedly sent from theclient each time they need to be run are compiled and optimized everyclient each time they need to be run are compiled and optimized everytime they are executed by SQL Server.time they are executed by SQL Server.

    They can reduce network traffic.They can reduce network traffic.

    An operation requiring hundreds of lines of Transact SQL code can beAn operation requiring hundreds of lines of Transact SQL code can beperformed through a single statement that executes the code in aperformed through a single statement that executes the code in aprocedure, rather than by sending hundreds of lines of code over theprocedure, rather than by sending hundreds of lines of code over the

    network.network. They can be used as a security mechanism.They can be used as a security mechanism.

    A user can be granted permission to execute a stored procedure even ifA user can be granted permission to execute a stored procedure even ifthey do not have permission to execute the procedures statementsthey do not have permission to execute the procedures statementsdirectly.directly.

  • 7/31/2019 Structured Query Language3

    60/78

    Stored Procedure RulesStored Procedure Rules

  • 7/31/2019 Structured Query Language3

    61/78

    Stored Procedure RulesStored Procedure Rules

    CREATE PROCEDURE statements cannot be combined with otherCREATE PROCEDURE statements cannot be combined with other

    SQL statements in a single batch.SQL statements in a single batch. The CREATE PROCEDURE definition itself can include any numberThe CREATE PROCEDURE definition itself can include any number

    and type of SQL statements, with the exception of the followingand type of SQL statements, with the exception of the following

    CREATE statements which cannot be used anywhere within aCREATE statements which cannot be used anywhere within a

    stored procedure:stored procedure:

    Other database objects can be created within a stored procedure. YouOther database objects can be created within a stored procedure. Youcan reference an object created in the same procedure as long as it iscan reference an object created in the same procedure as long as it is

    created before it is referenced.created before it is referenced.

    If you execute a procedure that calls another procedure, the calledIf you execute a procedure that calls another procedure, the called

    procedure can access all objects created by the first procedure,procedure can access all objects created by the first procedure,

    including temporary tables.including temporary tables. If you execute a remote stored procedure that makes changes on aIf you execute a remote stored procedure that makes changes on a

    remote Microsoft SQL Server , those changes cannot be rolledremote Microsoft SQL Server , those changes cannot be rolled

    back. Remote stored procedures do not take part in transactions.back. Remote stored procedures do not take part in transactions.

  • 7/31/2019 Structured Query Language3

    62/78

    ExamplesExamples

  • 7/31/2019 Structured Query Language3

    63/78

    Here is an example of a stored procedure that is useful in the pubs database. GivenHere is an example of a stored procedure that is useful in the pubs database. Givenan authors last and first name, it displays the title and publisher of each of thatan authors last and first name, it displays the title and publisher of each of thatauthors books:authors books:

    CREATE PROC au_info @lastname varchar(40), @firstname varchar(20)CREATE PROC au_info @lastname varchar(40), @firstname varchar(20)ASAS

    SELECT au_lname, au_fname, title, pub_nameSELECT au_lname, au_fname, title, pub_name

    FROM authors INNER JOIN titleauthor ON authors.au_id = titleauthor.au_idFROM authors INNER JOIN titleauthor ON authors.au_id = titleauthor.au_id

    JOIN titles ON titleauthor.title_id = titles.title_idJOIN titles ON titleauthor.title_id = titles.title_id

    JOIN publishers ON titles.pub_id = publishers.pub_idJOIN publishers ON titles.pub_id = publishers.pub_id

    WHERE au_fname = @firstnameWHERE au_fname = @firstname

    AND au_lname = @lastnameAND au_lname = @lastname

    You get a message stating that the command did not return any data and it did notYou get a message stating that the command did not return any data and it did notreturn any rows, which means the procedure has been created.return any rows, which means the procedure has been created.

    Now execute au_info:Now execute au_info:

    au_info Ringer, Anneau_info Ringer, Anne

    au_lname au_fname title pub_nameau_lname au_fname title pub_name

    ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    Ringer Anne The Gourmet Microwave Binnet & HardleyRinger Anne The Gourmet Microwave Binnet & Hardley

    Ringer Anne Is Anger the Enemy? New Moon BooksRinger Anne Is Anger the Enemy? New Moon Books

    (2 row(s) affected)(2 row(s) affected)

    You can assign a default value for the parameter in the CREATEYou can assign a default value for the parameter in the CREATEPROCEDURE Thi l hi h b i

  • 7/31/2019 Structured Query Language3

    64/78

    gPROCEDURE statement. This value, which can be any constant, isPROCEDURE statement. This value, which can be any constant, istaken as the parameter to the procedure when the user does nottaken as the parameter to the procedure when the user does notsupply one.supply one.

    If a parameter is expected but none is supplied, and if a defaultIf a parameter is expected but none is supplied, and if a defaultvalue is not supplied in the CREATE PROCEDURE statement, SQLvalue is not supplied in the CREATE PROCEDURE statement, SQLServer displays an error message that lists the expectedServer displays an error message that lists the expectedparameters.parameters.

    Here is a procedure, pub_info2, that displays the names of allHere is a procedure, pub_info2, that displays the names of all

    authors who have written a book published by the publisher givenauthors who have written a book published by the publisher givenas a parameter. If no publisher name is supplied, the procedureas a parameter. If no publisher name is supplied, the procedureshows the authors published by Algodata Infosystems.shows the authors published by Algodata Infosystems.

    CREATE PROC pub_info2 @pubname varchar(40) = 'Algodata Infosystems'CREATE PROC pub_info2 @pubname varchar(40) = 'Algodata Infosystems'

    ASAS

    SELECT au_lname, au_fname, pub_nameSELECT au_lname, au_fname, pub_nameFROM authors a INNER JOIN titleauthor ta ON a.au_id = ta.au_idFROM authors a INNER JOIN titleauthor ta ON a.au_id = ta.au_id

    JOIN titles t ON ta.title_id = t.title_idJOIN titles t ON ta.title_id = t.title_id

    JOIN publishers p ON t.pub_id = p.pub_idJOIN publishers p ON t.pub_id = p.pub_id

    WHERE @pubname = p.pub_nameWHERE @pubname = p.pub_name

    TEMPORARY TABLETEMPORARY TABLE

  • 7/31/2019 Structured Query Language3

    65/78

    TEMPORARY TABLEA table placed in the temporary database, tempdb, and erased atA table placed in the temporary database, tempdb, and erased at

    the end of the session.the end of the session.

    A temporary table is created by prefacing the table name (in theA temporary table is created by prefacing the table name (in the

    CREATE statement) with a number sign, for example:CREATE statement) with a number sign, for example:

    create table #authors (au_id Exchar (11))create table #authors (au_id Exchar (11))

    The first 13 characters of a temporary table name (excluding theThe first 13 characters of a temporary table name (excluding the

    number sign) must be unique in tempdb. Because all temporarynumber sign) must be unique in tempdb. Because all temporary

    objects belong to the tempdb database, you can create a temporaryobjects belong to the tempdb database, you can create a temporary

    table with the same name as a table already in another database.table with the same name as a table already in another database.

    This example creates a temporary table namedThis example creates a temporary table named

  • 7/31/2019 Structured Query Language3

    66/78

    This example creates a temporary table namedThis example creates a temporary table named

    #coffeetabletitles in tempdb. To use this table, always#coffeetabletitles in tempdb. To use this table, always

    refer to it with the exact name shown, including therefer to it with the exact name shown, including the

    number sign (#).number sign (#).

    USE pubsUSE pubs

    CREATE TABLE #coffeetabletitlesCREATE TABLE #coffeetabletitles

    GOGO

    SET NOCOUNT ONSET NOCOUNT ON

    SELECT * INTO #coffeetabletitlesSELECT * INTO #coffeetabletitles

    FROM titlesFROM titles

    WHERE price < $20WHERE price < $20

    SET NOCOUNT OFFSET NOCOUNT OFF

    SELECT nameSELECT name

    FROM tempdb..sysobjectsFROM tempdb..sysobjects

    WHERE name LIKE '#c%'WHERE name LIKE '#c%'

  • 7/31/2019 Structured Query Language3

    67/78

  • 7/31/2019 Structured Query Language3

    68/78

    CONTROL-of- FLOWCONTROL-of- FLOW

  • 7/31/2019 Structured Query Language3

    69/78

    BEGIN...ENDBEGIN...END

    Encloses a series of Transact-SQL statements so that a groupEncloses a series of Transact-SQL statements so that a groupof Transact-SQL statements can be executed. BEGIN...ENDof Transact-SQL statements can be executed. BEGIN...ENDblocks can be nested.blocks can be nested.

    SyntaxSyntax

    BEGINBEGIN{{

    sql_statementsql_statement||statement_blockstatement_block

    }}ENDEND

    ArgumentArgument

    {{sql_statementsql_statement||statement_blockstatement_block}}Is any valid Transact-SQL statement or statement grouping asIs any valid Transact-SQL statement or statement grouping as

    defined with a statement block. To define a statement block,defined with a statement block. To define a statement block,use the control-of-flow language keywords BEGIN and END.use the control-of-flow language keywords BEGIN and END.

    Although all Transact-SQL statements are valid within aAlthough all Transact-SQL statements are valid within aBEGIN...END block, certain Transact-SQL statements shouldBEGIN...END block, certain Transact-SQL statements shouldnot be grouped together within the same batch (statementnot be grouped together within the same batch (statementblock). For more information, see Batches and the individualblock). For more information, see Batches and the individualstatements being used.statements being used.

    Result TypeResult Type

    BooleanBoolean

  • 7/31/2019 Structured Query Language3

    70/78

    ExamplesExamples

    In this example, BEGIN and END define the group ofIn this example, BEGIN and END define the group ofTransact-SQL statements that should always be executedTransact-SQL statements that should always be executedtogether. If the BEGIN...END block were not included, thetogether. If the BEGIN...END block were not included, theIF condition would cause only the ROLLBACKIF condition would cause only the ROLLBACKTRANSACTION to execute, and the print message wouldTRANSACTION to execute, and the print message wouldnot be returned.not be returned.

    USE pubsUSE pubs

    GOGOCREATE TRIGGER deltitleCREATE TRIGGER deltitle

    ON titlesON titles

    FOR deleteFOR delete

    ASAS

    IF (SELECT COUNT(*) FROM deleted, salesIF (SELECT COUNT(*) FROM deleted, sales

    WHERE sales.title_id = deleted.title_id) > 0WHERE sales.title_id = deleted.title_id) > 0BEGINBEGIN

    ROLLBACK TRANSACTIONROLLBACK TRANSACTION

    PRINT 'You can''t delete a title with sales.'PRINT 'You can''t delete a title with sales.'

    ENDEND

    GOTOGOTO

  • 7/31/2019 Structured Query Language3

    71/78

    Alters the flow of execution to a label. The Transact-SQLAlters the flow of execution to a label. The Transact-SQLstatement(s) following GOTO are skipped and processingstatement(s) following GOTO are skipped and processingcontinues at the label. GOTO statements and labels can be usedcontinues at the label. GOTO statements and labels can be used

    anywhere within a procedure, batch, or statement block. GOTOanywhere within a procedure, batch, or statement block. GOTOstatements can be nested.statements can be nested.

    SyntaxSyntax

    Define the label:Define the label:

    labellabel::

    Alter the execution:Alter the execution:

    GOTOGOTO labellabelArgumentsArguments

    labellabelIs the point after which processing begins if a GOTO is targeted to thatIs the point after which processing begins if a GOTO is targeted to that

    label. Labels must follow the rules for identifiers. A label can be usedlabel. Labels must follow the rules for identifiers. A label can be usedas a commenting method whether or not GOTO is used.as a commenting method whether or not GOTO is used.

    RemarksRemarks

    GOTO can exist within conditional control-of-flow statements,GOTO can exist within conditional control-of-flow statements,statement blocks, or procedures, but it cannot go to a labelstatement blocks, or procedures, but it cannot go to a labeloutside of the batch. GOTO branching can go to a label definedoutside of the batch. GOTO branching can go to a label definedbefore or after GOTO.before or after GOTO.

    PermissionsPermissions

    GOTO permissions default to any valid user.GOTO permissions default to any valid user.

    ExamplesExamplesThi l h GOTO l i lt ti t i WHILE

  • 7/31/2019 Structured Query Language3

    72/78

    This example shows GOTO looping as an alternative to using WHILE.This example shows GOTO looping as an alternative to using WHILE.

    Note The tnames_cursor cursor is not defined. This example is forNote The tnames_cursor cursor is not defined. This example is forillustration only.illustration only.

    USE pubsUSE pubs

    GOGO

    DECLARE @tablename sysnameDECLARE @tablename sysname

    SET @tablename = N'authors'SET @tablename = N'authors'

    table_loop:table_loop:

    IF (@@fetch_status -2)IF (@@fetch_status -2)BEGINBEGIN

    SELECT @tablename = RTRIM(UPPER(@tablename))SELECT @tablename = RTRIM(UPPER(@tablename))

    EXEC ("SELECT """ + @tablename + """ = COUNT(*) FROM "EXEC ("SELECT """ + @tablename + """ = COUNT(*) FROM "

    + @tablename )+ @tablename )

    PRINT " "PRINT " "ENDEND

    FETCH NEXT FROM tnames_cursor INTO @tablenameFETCH NEXT FROM tnames_cursor INTO @tablename

    IF (@@fetch_status -1) GOTO table_loopIF (@@fetch_status -1) GOTO table_loop

    GOGO

    IF...ELSEIF...ELSE

    Imposes conditions on the execution of a Transact SQL statement The Transact SQLImposes conditions on the execution of a Transact SQL statement The Transact SQL

  • 7/31/2019 Structured Query Language3

    73/78

    Imposes conditions on the execution of a Transact-SQL statement. The Transact-SQLImposes conditions on the execution of a Transact-SQL statement. The Transact-SQLstatement following an IF keyword and its condition is executed if the condition isstatement following an IF keyword and its condition is executed if the condition issatisfied (when the Boolean expression returns true). The optional ELSE keywordsatisfied (when the Boolean expression returns true). The optional ELSE keywordintroduces an alternate Transact-SQL statement that is executed when the IFintroduces an alternate Transact-SQL statement that is executed when the IFcondition is not satisfied (when the Boolean expression returns false).condition is not satisfied (when the Boolean expression returns false).

    SyntaxSyntax

    IFIF Boolean_expressionBoolean_expression{{sql_statementsql_statement || statement_blockstatement_block}}

    [ELSE[ELSE{{sql_statementsql_statement || statement_blockstatement_block}]}]

    ArgumentsArguments

    Boolean_expressionBoolean_expression Is an expression that returns TRUE or FALSE. If the Boolean expression contains aIs an expression that returns TRUE or FALSE. If the Boolean expression contains a

    SELECT statement, the SELECT statement must be enclosed in parentheses.SELECT statement, the SELECT statement must be enclosed in parentheses.{{sql_statementsql_statement || statement_blockstatement_block}}

    Is any Transact-SQL statement or statement grouping as defined with a statementIs any Transact-SQL statement or statement grouping as defined with a statementblock. The IF or ELSE condition can affect the performance of only one Transact-block. The IF or ELSE condition can affect the performance of only one Transact-SQL statement, unless a statement block is used. To define a statement block,SQL statement, unless a statement block is used. To define a statement block,use the control-of-flow keywords BEGIN and END. CREATE TABLE or SELECTuse the control-of-flow keywords BEGIN and END. CREATE TABLE or SELECTINTO statements must refer to the same table name if the CREATE TABLE orINTO statements must refer to the same table name if the CREATE TABLE or

    SELECT INTO statements are used in both the IF and ELSE areas of the IF...ELSESELECT INTO statements are used in both the IF and ELSE areas of the IF...ELSEblock.block.

    RemarksRemarks

    IF...ELSE constructs can be used in batches, in stored procedures (where theseIF...ELSE constructs can be used in batches, in stored procedures (where theseconstructs are often used to test for the existence of some parameter), and in ad hocconstructs are often used to test for the existence of some parameter), and in ad hocqueries.queries.

    IF tests can be nested, either after another IF or following an ELSE. There is no limit toIF tests can be nested, either after another IF or following an ELSE. There is no limit tothe number of nested levels.the number of nested levels.

    A.Use one IF...ELSE blockA.Use one IF...ELSE block

    This example shows an IF condition with a statement block If theThis example shows an IF condition with a statement block If the

  • 7/31/2019 Structured Query Language3

    74/78

    This example shows an IF condition with a statement block. If theThis example shows an IF condition with a statement block. If theaverage price of the title is not less than $15, the text Average title priceaverage price of the title is not less than $15, the text Average title priceis more than $15 is printed.is more than $15 is printed.

    USE pubsUSE pubs

    IF (SELECT AVG(price) FROM titles WHERE type = 'mod_cook') < $15IF (SELECT AVG(price) FROM titles WHERE type = 'mod_cook') < $15BEGINBEGIN

    PRINT 'The following titles are excellent mod_cook books:'PRINT 'The following titles are excellent mod_cook books:'

    PRINT ' 'PRINT ' '

    S