{"id":289,"date":"2014-04-22T21:28:41","date_gmt":"2014-04-22T21:28:41","guid":{"rendered":"http:\/\/opentextbc.ca\/dbdesign01\/?post_type=chapter&#038;p=289"},"modified":"2019-06-11T16:50:50","modified_gmt":"2019-06-11T16:50:50","slug":"chapter-sql-dml","status":"publish","type":"chapter","link":"https:\/\/opentextbc.ca\/dbdesign01\/chapter\/chapter-sql-dml\/","title":{"raw":"Chapter 16 SQL Data Manipulation Language","rendered":"Chapter 16 SQL Data Manipulation Language"},"content":{"raw":"<p style=\"text-align: left;\" align=\"center\">The SQL data manipulation language (DML) is used to query and modify database data. In this chapter, we will describe how to use the SELECT, INSERT, UPDATE, and DELETE\u00a0SQL DML command statements, defined below.<\/p>\r\n\r\n<ul>\r\n \t<li><em>SELECT<\/em>\u00a0 - to query data in the database<\/li>\r\n \t<li><em>INSERT<\/em>\u00a0 - to insert data into a table<\/li>\r\n \t<li><em>UPDATE<\/em>\u00a0- to update data in a table<\/li>\r\n \t<li><em>DELETE<\/em>\u00a0- to delete data from a table<\/li>\r\n<\/ul>\r\nIn the SQL DML statement:\r\n<ul>\r\n \t<li>Each clause in a statement should begin on a new line.<\/li>\r\n \t<li>The beginning of each clause should line up with the beginning of other clauses.<\/li>\r\n \t<li>If a clause has several parts, they should appear on separate lines and be indented under the start of the clause to show the relationship.<\/li>\r\n \t<li>Upper case letters are used to represent reserved words.<\/li>\r\n \t<li>Lower case letters are used to represent user-defined words.<\/li>\r\n<\/ul>\r\n<h1>SELECT Statement<\/h1>\r\nThe SELECT statement, or command, allows the user to extract data from tables, based on specific criteria. It\u00a0<span>is processed according to the following sequence:<\/span>\r\n\r\nSELECT DISTINCT item(s)\r\nFROM\u00a0 table(s)\r\nWHERE\u00a0 predicate\r\nGROUP BY\u00a0 field(s)\r\nORDER BY fields\r\n\r\nWe can use the SELECT\u00a0statement to generate an employee phone list from the Employees table as follows:\r\n<div class=\"textbox shaded\">SELECT \u00a0FirstName, LastName, phone\r\nFROM Employees\r\nORDER BY LastName<\/div>\r\n<span style=\"color: #333333;\">This action will<\/span> display employee's last name, first name, and phone number from the Employees table, seen in Table 16.1.\r\n<table>\r\n<tbody>\r\n<tr>\r\n<td><strong>Last Name<\/strong><\/td>\r\n<td><strong>First Name<\/strong><\/td>\r\n<td><strong>Phone Number<\/strong><\/td>\r\n<\/tr>\r\n<tr>\r\n<td>Hagans<\/td>\r\n<td>Jim<\/td>\r\n<td><span>604-232-3232<\/span><\/td>\r\n<\/tr>\r\n<tr>\r\n<td>Wong<\/td>\r\n<td>Bruce<\/td>\r\n<td><span>604-244-2322<\/span><\/td>\r\n<\/tr>\r\n<\/tbody>\r\n<\/table>\r\n<em>Table 16.1. Employees table.<\/em>\r\n\r\nIn this next example, we will use a Publishers table (Table 16.2). (You will notice that Canada is mispelled in the <em>Publisher Country<\/em> field for Example Publishing and ABC Publishing.\u00a0<span>To correct mispelling, use the UPDATE statement to standardize the country field to Canada - see UPDATE statement later in this chapter.)<\/span>\r\n<table>\r\n<tbody>\r\n<tr>\r\n<td><strong>Publisher Name<\/strong><\/td>\r\n<td><strong>Publisher City<\/strong><\/td>\r\n<td><strong>Publisher Province<\/strong><\/td>\r\n<td><strong>Publisher Country<\/strong><\/td>\r\n<\/tr>\r\n<tr>\r\n<td>Acme Publishing<\/td>\r\n<td>Vancouver<\/td>\r\n<td>BC<\/td>\r\n<td>Canada<\/td>\r\n<\/tr>\r\n<tr>\r\n<td>Example Publishing<\/td>\r\n<td>Edmonton<\/td>\r\n<td>AB<\/td>\r\n<td>Cnada<\/td>\r\n<\/tr>\r\n<tr>\r\n<td>ABC Publishing<\/td>\r\n<td>Toronto<\/td>\r\n<td>ON<\/td>\r\n<td>Canda<\/td>\r\n<\/tr>\r\n<\/tbody>\r\n<\/table>\r\n<em>Table 16.2. Publishers table.<\/em>\r\n\r\nIf you add the publisher's name and city, you would use the SELECT statement followed by the fields name separated by a comma:\r\n<div class=\"textbox shaded\">SELECT PubName, city\r\nFROM Publishers<\/div>\r\nThis action will display the publisher's name and city from the Publishers table.\r\n\r\n<span style=\"color: #333333;\">If you just want the publisher's name under the display name city, you would use the SELECT statement with <em>no comma<\/em> separating pub_name and city:<\/span>\r\n<div class=\"textbox shaded\">SELECT\u00a0<span>PubName city<\/span>\r\nFROM Publishers<\/div>\r\n<span>Performing this action will dis<\/span>play only the pub_name from the Publishers table with a \"city\" heading. \u00a0If you do not include the comma, SQL Server assumes you want a new column name for pub_name.<strong>\u00a0<\/strong>\r\n<h2>SELECT statement with WHERE criteria<\/h2>\r\n<span>Sometimes you might want to focus on a portion of the Publishers table, such as only publishers that are in Vancouver. In this situation, you would use the SELECT statement with the WHERE criterion, i.e., WHERE city = 'Vancouver'.<\/span>\r\n\r\nThese first two examples illustrate\u00a0how to limit record<span>\u00a0selection\u00a0with the WHERE criterion\u00a0using BETWEEN. Each of these examples give the same results for store items with between 20 and 50 items in stock.<\/span>\r\n\r\nExample #1 uses the quantity, <em>qty BETWEEN 20 and 50<\/em>.\r\n<div class=\"textbox shaded\">SELECT StorID, qty, TitleID\r\nFROM Sales\r\nWHERE qty BETWEEN 20 and 50\u00a0 <i>(includes the 20 and 50)<\/i><\/div>\r\nExample #2, on the other hand, uses <em>qty &gt;=20 and qty &lt;=50<\/em>\u00a0.\r\n<div class=\"textbox shaded\">SELECT<span> StorID, qty, TitleID<\/span>\r\nFROM Sales\r\nWHERE qty &gt;= 20 and qty\u00a0 &lt;= 50<\/div>\r\n<span style=\"color: #333333;\">Example #3 illustrates how to limit record selection with the WHERE criterion using NOT BETWEEN.<\/span>\r\n<div class=\"textbox shaded\">SELECT<span> StorID, qty, TitleID<\/span>\r\nFROM Sales\r\nWHERE qty NOT BETWEEN 20 and 50<\/div>\r\nThe next two examples show two different ways\u00a0to limit record\u00a0selection\u00a0with the WHERE criterion using IN, with each yielding the same results.\r\n\r\nExample #4 shows how to select records using<em>\u00a0province= <\/em>as part of the WHERE statement.\r\n<div class=\"textbox shaded\">SELECT *\r\nFROM Publishers\r\nWHERE province = 'BC' OR province = 'AB' OR province = 'ON'<\/div>\r\nExample #5 select records using <em>province IN<\/em> as part of the WHERE statement.\r\n<div class=\"textbox shaded\">SELECT *\r\nFROM Publishers\r\nWHERE province IN ('BC', 'AB', 'ON')<\/div>\r\nThe final two examples illustrate how NULL and NOT NULL can be used to select records. For these examples, a Books\u00a0table (not shown) would be used that contains fields called Title, Quantity, and Price (of book). Each publisher has a Book<span>s<\/span><span>\u00a0table that lists all of its books.<\/span>\r\n\r\n<span style=\"color: #333333;\">Example #6 uses NULL.<\/span>\r\n<div class=\"textbox shaded\">SELECT price, title\r\nFROM Books\r\nWHERE price IS NULL<\/div>\r\nExample #7 uses NOT NULL.\r\n<div class=\"textbox shaded\">SELECT price, title\r\nFROM Books\r\nWHERE price IS NOT NULL<\/div>\r\n<h2><span style=\"color: #333333;\">Using wildcards in the LIKE\u00a0clause<\/span><\/h2>\r\nThe LIKE keyword selects rows containing fields that match specified portions of character strings. LIKE is used with char, varchar, text, datetime and smalldatetime data. A <em>wildcard\u00a0<\/em>allows the user to match fields that contain certain letters. For example, the wildcard province = 'N%' would give all provinces that start with the letter 'N'. Table 16.3 shows four ways to specify wildcards in the SELECT statement in regular express format.\r\n<table style=\"width: 622px;\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">\r\n<tbody>\r\n<tr>\r\n<td valign=\"top\" width=\"105\">\r\n<p align=\"center\">%<\/p>\r\n<\/td>\r\n<td style=\"text-align: left;\" valign=\"top\" width=\"517\">Any string of zero or more characters<\/td>\r\n<\/tr>\r\n<tr>\r\n<td valign=\"top\" width=\"105\">\r\n<p align=\"center\">_<\/p>\r\n<\/td>\r\n<td valign=\"top\" width=\"517\">Any single character<\/td>\r\n<\/tr>\r\n<tr>\r\n<td valign=\"top\" width=\"105\">\r\n<p align=\"center\">[ ]<\/p>\r\n<\/td>\r\n<td valign=\"top\" width=\"517\">Any single character within the specified range (e.g., [a-f]) or set (e.g., [abcdef])<\/td>\r\n<\/tr>\r\n<tr>\r\n<td valign=\"top\" width=\"105\">\r\n<p align=\"center\">[^]<\/p>\r\n<\/td>\r\n<td valign=\"top\" width=\"517\">Any single character not within the specified range (e.g., [^a - f]) or set (e.g., [^abcdef])<\/td>\r\n<\/tr>\r\n<\/tbody>\r\n<\/table>\r\n<em>Table 16.3. How to specify wildcards in the SELECT statement.<\/em>\r\n\r\nIn example #1,\u00a0LIKE 'Mc%' searches for all last names that begin with the letters \"Mc\" (e.g., McBadden).\r\n<div class=\"textbox shaded\">SELECT LastName\r\nFROM Employees\r\nWHERE <span>LastName<\/span>\u00a0LIKE 'Mc%'<\/div>\r\nFor example #2: LIKE '%inger' searches for all last names that end with the letters \"inger\" (e.g., Ringer, Stringer).\r\n<div class=\"textbox shaded\">SELECT\u00a0<span>LastName<\/span>\r\nFROM Employees\r\nWHERE <span>LastName<\/span>\u00a0LIKE '%inger'<\/div>\r\nIn, example #3: LIKE '%en%' searches for all last names that have the letters \"en\" (e.g., Bennett, Green, McBadden).\r\n<div class=\"textbox shaded\">SELECT\u00a0<span>LastName<\/span>\r\nFROM Employees\r\nWHERE <span>LastName<\/span> LIKE '%en%'<\/div>\r\n<h2>SELECT statement with ORDER BY\u00a0clause<\/h2>\r\nYou use the ORDER BY\u00a0clause to sort the records in the resulting list. Use\u00a0<em>ASC\u00a0<\/em>to sort the\u00a0results\u00a0in ascending order and <em>DESC\u00a0<\/em>to sort the results\u00a0in descending order.\r\n\r\nFor example, with ASC:\r\n<div class=\"textbox shaded\">SELECT *\r\nFROM Employees\r\nORDER BY HireDate ASC<\/div>\r\nAnd with DESC:\r\n<div class=\"textbox shaded\">SELECT *\r\nFROM Books\r\nORDER B<span style=\"color: #000000;\">Y type, pric<\/span>e DESC<\/div>\r\n<h2>SELECT\u00a0statement with GROUP BY\u00a0clause<\/h2>\r\nThe <em>GROUP BY\u00a0<\/em>clause is used to create one output row per each group and produces summary values for the selected columns, as shown below.\r\n<div class=\"textbox\">SELECT type\r\nFROM\u00a0Books\r\nGROUP BY type<\/div>\r\nHere is an example using the above statement.\r\n<div class=\"textbox shaded\">SELECT type AS 'Type', MIN(price) AS 'Minimum Price'\r\nFROM\u00a0Books\r\nWHERE royalty &gt; 10\r\nGROUP BY type<\/div>\r\nIf the SELECT statement includes a WHERE criterion where <em>price is not null<\/em>,\r\n<div class=\"textbox\">SELECT type, price\r\nFROM\u00a0Books\r\nWHERE price is not null<\/div>\r\nthen a statement with the GROUP BY clause would look like this:\r\n<div class=\"textbox shaded\">SELECT type AS 'Type', MIN(price) AS 'Minimum Price'\r\nFROM\u00a0Books\r\nWHERE price is not null\r\nGROUP BY type<\/div>\r\n<h3>Using COUNT with GROUP BY<\/h3>\r\nWe can use COUNT to tally how many items are in a container. However, if we want to count different items into separate groups, such as marbles of varying colours, then we would use the COUNT function with the GROUP BY command.\r\n\r\nThe below SELECT statement illustrates how to count groups of data using the COUNT function with the GROUP BY clause.\r\n<div class=\"textbox\">SELECT COUNT(*)\r\nFROM\u00a0Books\r\nGROUP BY type<\/div>\r\n<h3>Using AVG and SUM with GROUP BY<\/h3>\r\nWe can use the AVG function to give us the average of any group, and SUM to give the total.\r\n\r\nExample #1 uses the AVG FUNCTION with the GROUP BY type.\r\n<div class=\"textbox shaded\">SELECT AVG(qty)\r\nFROM\u00a0Books\r\nGROUP BY type<\/div>\r\nExample #2 uses the SUM function with the GROUP BY type.\r\n<div class=\"textbox shaded\">SELECT SUM(qty)\r\nFROM Books\r\nGROUP BY type<\/div>\r\nExample #3 uses both the AVG and SUM functions with the GROUP BY type in the SELECT statement.\r\n<div class=\"textbox shaded\">SELECT 'Total Sales' = SUM(qty), 'Average Sales' = AVG(qty), stor_id\r\nFROM Sales\r\nGROUP BY StorID ORDER BY\u00a0 'Total Sales'<\/div>\r\n<h2>Restricting rows with HAVING<\/h2>\r\nThe HAVING clause can be used to restrict rows. It is similar to the WHERE condition except HAVING\u00a0can include the aggregate function; the WHERE cannot do this.\r\n\r\nThe HAVING clause behaves like the WHERE clause, but is applicable to groups. In this example, we use the HAVING clause to exclude the groups with the province 'BC'.\r\n<div class=\"textbox shaded\">SELECT au_fname AS 'Author''s First Name', province as 'Province'\r\nFROM Authors\r\nGROUP BY au_fname, province\r\nHAVING province &lt;&gt; 'BC'<\/div>\r\n<h2>INSERT statement<\/h2>\r\nThe <em>INSERT statement<\/em> adds rows to a table. In addition,\r\n<ul>\r\n \t<li>INSERT specifies the table or view that data will be inserted into.<\/li>\r\n \t<li>Column_list lists columns that will be affected by the INSERT.<\/li>\r\n \t<li>If a column is omitted, each value must be provided.<\/li>\r\n \t<li>If you are including columns, they can be listed in any order.<\/li>\r\n \t<li>VALUES specifies the data that you want to insert into the table.\u00a0VALUES is required.<\/li>\r\n \t<li>Columns with the IDENTITY property should not be explicitly listed in the column_list or values_clause.<\/li>\r\n<\/ul>\r\nThe syntax for the INSERT statement is:\r\n<div class=\"textbox\">INSERT [INTO] Table_name | view name [column_list]\r\nDEFAULT VALUES | values_list | select statement<\/div>\r\nWhen inserting rows with the INSERT statement, these rules apply:\r\n<ul>\r\n \t<li>Inserting an empty string (' ') into a varchar or text column inserts a single space.<\/li>\r\n \t<li>All char columns are\u00a0right-padded to the defined length.<\/li>\r\n \t<li>All trailing spaces are removed\u00a0from data inserted into varchar columns, except in strings that contain\u00a0only spaces. These strings are truncated to a single space.<\/li>\r\n \t<li>If an INSERT statement violates a constraint, default or rule, or if it is the wrong data type, the\u00a0statement fails and SQL Server displays an error message.<\/li>\r\n<\/ul>\r\nWhen you specify values for only some of the columns in the column_list, one of three things can happen to the columns that have no values:\r\n<ol>\r\n \t<li>A default value is entered if\u00a0the column has a DEFAULT constraint, if a default is bound to the column, or if a default is bound to the underlying user-defined data type.<\/li>\r\n \t<li>NULL is entered if the column allows NULLs and no default value exists for the column.<\/li>\r\n \t<li>An error message is displayed\u00a0and the row is rejected if the column is defined as NOT NULL and no\u00a0default exists.<\/li>\r\n<\/ol>\r\nThis example uses INSERT to add a record to the publisher's Authors table.\r\n<div class=\"textbox shaded\">INSERT INTO Authors\r\nVALUES(\u2018555-093-467\u2019, \u2018Martin\u2019, \u2018April\u2019, \u2018281 555-5673\u2019, \u2018816 Market St.,\u2019 , \u2018Vancouver\u2019, \u2018BC\u2019, \u2018V7G3P4\u2019, 0)<\/div>\r\nThis following example illustrates how to insert a partial row into the Publishers table with a column list. The country column had a default value of Canada so it does not require that you include it in your values.\r\n<div class=\"textbox shaded\">INSERT INTO Publishers\u00a0(PubID, PubName, city, province)\r\nVALUES (\u20189900\u2019, \u2018Acme Publishing\u2019, \u2018Vancouver\u2019, \u2018BC\u2019)<\/div>\r\nTo insert rows into a table with an IDENTITY column, follow the below example.\u00a0Do not supply the value for the IDENTITY nor the name of the column in the column list.\r\n<div class=\"textbox shaded\">INSERT INTO jobs\r\nVALUES (\u2018DBA\u2019, 100, 175)<\/div>\r\n<h3>Inserting specific values into an IDENTITY column<\/h3>\r\nBy default, data cannot be inserted directly into an IDENTITY column; however, if a row is accidentally deleted, or there are gaps in the IDENTITY column values, you can insert a row and specify the IDENTITY column value.\r\n<div class=\"textbox\">IDENTITY_INSERT option<\/div>\r\nTo allow an insert with a specific identity value, the IDENTITY_INSERT option can be used as follows.\r\n<div class=\"textbox shaded\">SET IDENTITY_INSERT jobs ON\r\nINSERT INTO jobs \u00a0(job_id, job_desc, min_lvl, max_lvl)\r\nVALUES (19, \u2019DBA2\u2019, 100, 175)\r\nSET IDENTITY_INSERT jobs OFF<\/div>\r\n<h3>\u00a0Inserting rows with a SELECT\u00a0statement<\/h3>\r\nWe can sometimes create a small temporary table from a large table. For this, we can insert rows with a SELECT statement. When using this command, there is no validation for uniqueness. Consequently, there may be many rows with the same pub_id in the example below.\r\n\r\nThis example creates a smaller temporary Publishers table using the CREATE TABLE statement. Then the INSERT with a SELECT statement is used to add records to this temporary Publishers table from the publis table.\r\n<div class=\"textbox shaded\">CREATE TABLE dbo.tmpPublishers (\r\nPubID char (4) NOT NULL ,\r\nPubName varchar (40) NULL ,\r\ncity varchar (20) NULL ,\r\nprovince char (2) NULL ,\r\ncountry varchar (30) NULL\u00a0 DEFAULT (\u2018Canada\u2019)\r\n)\r\nINSERT\u00a0 tmpPublishers\r\nSELECT * FROM Publishers<\/div>\r\nIn this example, we're copying a subset of data.\r\n<div class=\"textbox shaded\">INSERT tmpPublishers (pub_id, pub_name)\r\nSELECT PubID, PubName\r\nFROM Publishers<\/div>\r\nIn this example, the publishers\u2019 data are copied to the tmpPublishers table and the country column is set to Canada.\r\n<div class=\"textbox shaded\">INSERT tmpPublishers (<span>PubID, PubName<\/span>, city, province, country)\r\nSELECT <span>PubID, PubName<\/span>, city, province, \u2018Canada\u2019\r\nFROM Publishers<\/div>\r\n<h2>UPDATE statement<\/h2>\r\nThe <em>UPDATE\u00a0statement<\/em> changes data in existing rows either by adding new data or modifying existing data.\r\n\r\nThis example uses the UPDATE statement to standardize the country field to be Canada for all records in the Publishers table.\r\n<div class=\"textbox\">UPDATE Publishers\r\nSET country = \u2018Canada\u2019<\/div>\r\nThis example increases the royalty amount by 10% for those royalty amounts between 10 and 20.\r\n<div class=\"textbox shaded\">UPDATE roysched\r\nSET royalty = royalty + (royalty * .10)\r\nWHERE royalty BETWEEN 10 and 20<\/div>\r\n<h3>Including subqueries in an UPDATE statement<\/h3>\r\nThe employees from the Employees table who were hired by the publisher in 2010 are given a promotion to the highest job level for their job type. This is what the UPDATE statement would look like.\r\n<div class=\"textbox shaded\">UPDATE Employees\r\nSET job_lvl =\r\n(SELECT max_lvl FROM jobs\r\nWHERE employee.job_id = jobs.job_id)\r\nWHERE DATEPART(year, employee.hire_date) = 2010<\/div>\r\n<h2>DELETE\u00a0statement<\/h2>\r\nThe <em>DELETE\u00a0statement<\/em> removes rows from a record set. DELETE names the table or view that holds the rows that will be deleted and only one table or row may be listed at a time. WHERE is\u00a0 a standard WHERE clause that limits the deletion to select records.\r\n\r\nThe DELETE syntax looks like this.\r\n<div class=\"textbox\">DELETE [FROM] {table_name | view_name }\r\n[WHERE clause]<\/div>\r\nThe rules for the DELETE statement are:\r\n<ol>\r\n \t<li>If you omit a WHERE clause, all rows in the table are removed\u00a0(except for indexes, the table, constraints)<i>.<\/i><\/li>\r\n \t<li>DELETE cannot be used with a view that has a FROM clause naming more than one table. (Delete can affect only one base table at a time.)<\/li>\r\n<\/ol>\r\nWhat follows are three different DELETE statements that can be used.\r\n\r\n1. Deleting all rows from a table.\r\n<div class=\"textbox\">DELETE\r\nFROM Discounts<\/div>\r\n2. Deleting selected rows:\r\n<div class=\"textbox\">DELETE\r\nFROM Sales\r\nWHERE stor_id = \u20186380\u2019<\/div>\r\n3. Deleting rows based on a value in a subquery:\r\n<div class=\"textbox\">DELETE FROM Sales\r\nWHERE title_id IN\r\n(SELECT title_id FROM Books\u00a0WHERE type = \u2018mod_cook\u2019)<\/div>\r\n<h1>Built-in Functions<\/h1>\r\nThere are many built-in functions in SQL Server such as:\r\n<ol>\r\n \t<li><em>Aggregate:<\/em>\u00a0returns summary values<\/li>\r\n \t<li><em>Conversion:<\/em>\u00a0transforms one data type to another<\/li>\r\n \t<li><em>Date:<\/em>\u00a0displays information about dates and times<\/li>\r\n \t<li><em>Mathematical:<\/em>\u00a0performs operations on numeric data<\/li>\r\n \t<li><em>String:<\/em>\u00a0performs operations on character strings, binary data or expressions<\/li>\r\n \t<li><em>System:<\/em>\u00a0returns a special piece of information from the database<\/li>\r\n \t<li><em>Text and image:<\/em>\u00a0performs operations on text and image data<\/li>\r\n<\/ol>\r\nBelow you will find detailed descriptions and examples for the first four functions.\r\n<h2>Aggregate functions<\/h2>\r\nAggregate functions perform a calculation on a set of values and return a single, or summary, value. Table 16.4 lists these functions.\r\n<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">\r\n<tbody>\r\n<tr>\r\n<td valign=\"top\" width=\"16%\"><strong>FUNCTION<\/strong><\/td>\r\n<td valign=\"top\" width=\"83%\"><strong>DESCRIPTION<\/strong><\/td>\r\n<\/tr>\r\n<tr>\r\n<td valign=\"top\" width=\"16%\">AVG<\/td>\r\n<td valign=\"top\" width=\"83%\">Returns the average of all the values, or only the DISTINCT values, in the expression.<\/td>\r\n<\/tr>\r\n<tr>\r\n<td valign=\"top\" width=\"16%\">COUNT<\/td>\r\n<td valign=\"top\" width=\"83%\">Returns the number of non-null values in the expression. When DISTINCT is specified, COUNT finds the number of unique non-null values.<\/td>\r\n<\/tr>\r\n<tr>\r\n<td valign=\"top\" width=\"16%\">COUNT(*)<\/td>\r\n<td valign=\"top\" width=\"83%\">Returns the number of rows. COUNT(*) takes no parameters and cannot be used with DISTINCT.<\/td>\r\n<\/tr>\r\n<tr>\r\n<td valign=\"top\" width=\"16%\">MAX<\/td>\r\n<td valign=\"top\" width=\"83%\">Returns the maximum value in the expression. MAX can be used with numeric, character and datetime columns, but not with bit columns. With character columns, MAX finds the highest value in the collating sequence. MAX ignores any null values.<\/td>\r\n<\/tr>\r\n<tr>\r\n<td valign=\"top\" width=\"16%\">MIN<\/td>\r\n<td valign=\"top\" width=\"83%\">Returns the minimum value in the expression. MIN can be used with numeric, character and datetime columns, but not with bit columns. With character columns, MIN finds the value that is lowest in the sort sequence. MIN ignores any null values.<\/td>\r\n<\/tr>\r\n<tr>\r\n<td valign=\"top\" width=\"16%\">SUM<\/td>\r\n<td valign=\"top\" width=\"83%\">Returns the sum of all the values, or only the DISTINCT values, in the expression. SUM can be used with numeric columns only.<\/td>\r\n<\/tr>\r\n<\/tbody>\r\n<\/table>\r\n<em>Table 16.4\u00a0A list of aggregate functions and descriptions.<\/em>\r\n\r\nBelow are examples of each of the aggregate functions listed in Table 16.4.\r\n\r\n<strong>Example #1: \u00a0AVG<\/strong>\r\n<div class=\"textbox shaded\">SELECT AVG (price) AS 'Average Title Price'\r\nFROM\u00a0Books<\/div>\r\n<strong>Example #2: COUNT<\/strong>\r\n<div class=\"textbox shaded\">SELECT COUNT(PubID) AS 'Number of Publishers'\r\nFROM Publishers<\/div>\r\n<strong>Example #3: COUNT<\/strong>\r\n<div class=\"textbox shaded\">SELECT COUNT(province) AS 'Number of Publishers'\r\nFROM Publishers<\/div>\r\n<strong>Example #3: COUNT (*)<\/strong>\r\n<div class=\"textbox shaded\">SELECT COUNT(*)\r\nFROM Employees\r\nWHERE job_lvl = 35<\/div>\r\n<strong>Example #4: MAX<\/strong>\r\n<div class=\"textbox shaded\">SELECT MAX (HireDate)\r\nFROM Employees<\/div>\r\n<strong>Example #5: MIN<\/strong>\r\n<div class=\"textbox shaded\">SELECT MIN (price)\r\nFROM\u00a0Books<\/div>\r\n<strong>Example #6: SUM<\/strong>\r\n<div class=\"textbox shaded\">SELECT SUM(discount) AS 'Total Discounts'\r\nFROM Discounts<\/div>\r\n<h2>Conversion function<\/h2>\r\nThe conversion function\u00a0transforms one data type to another.\r\n\r\nIn the example below, a price that contains two 9s is converted into five characters. The syntax for this statement is\u00a0SELECT 'The date is ' + CONVERT(varchar(12), getdate()).\r\n<div class=\"textbox shaded\">SELECT CONVERT(int, 10.6496)\r\nSELECT title_id, price\r\nFROM\u00a0Books\r\nWHERE CONVERT(char(5), price) LIKE '%99%'<\/div>\r\nIn this second example, the conversion function changes data to a data type with a different size.\r\n<div class=\"textbox shaded\">SELECT title_id, CONVERT(char(4), ytd_sales) as 'Sales'\r\nFROM\u00a0Books\r\nWHERE type LIKE '%cook'<\/div>\r\n<h2>Date function<\/h2>\r\nThe date function produces a date by adding an interval to a specified date. The result is a datetime value equal to the date plus the number of date parts. If the date parameter is a smalldatetime value, the result is also a smalldatetime value.\r\n\r\nThe DATEADD function is used to add and increment date values. The\u00a0syntax\u00a0for this function is\u00a0DATEADD(datepart, number, date).\r\n<div class=\"textbox shaded\">SELECT DATEADD(day, 3, hire_date)\r\nFROM Employees<\/div>\r\nIn this example, the\u00a0function\u00a0DATEDIFF(datepart, date1, date2) \u00a0is used.\r\n\r\nThis command returns the number of datepart \"boundaries\" crossed between two specified dates. The method of counting crossed boundaries makes the result given by DATEDIFF consistent across all data types such as minutes, seconds, and milliseconds.\r\n<div class=\"textbox shaded\">SELECT DATEDIFF(day, HireDate, 'Nov 30 1995')\r\nFROM Employees<\/div>\r\nFor any particular date, we can examine any part of that date from the year to the millisecond.\r\n\r\nThe date parts (DATEPART) and abbreviations recognized by SQL Server, and the acceptable values are listed in Table 16.5.\r\n<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">\r\n<tbody>\r\n<tr>\r\n<td valign=\"top\" width=\"147\"><strong>DATE PART<\/strong><\/td>\r\n<td valign=\"top\" width=\"183\"><strong>ABBREVIATION<\/strong><\/td>\r\n<td valign=\"top\" width=\"213\"><strong>VALUES<\/strong><\/td>\r\n<\/tr>\r\n<tr>\r\n<td valign=\"top\" width=\"147\">Year<\/td>\r\n<td valign=\"top\" width=\"183\">yy<\/td>\r\n<td valign=\"top\" width=\"213\">1753-9999<\/td>\r\n<\/tr>\r\n<tr>\r\n<td valign=\"top\" width=\"147\">Quarter<\/td>\r\n<td valign=\"top\" width=\"183\">qq<\/td>\r\n<td valign=\"top\" width=\"213\">1-4<\/td>\r\n<\/tr>\r\n<tr>\r\n<td valign=\"top\" width=\"147\">Month<\/td>\r\n<td valign=\"top\" width=\"183\">mm<\/td>\r\n<td valign=\"top\" width=\"213\">1-12<\/td>\r\n<\/tr>\r\n<tr>\r\n<td valign=\"top\" width=\"147\">Day of year<\/td>\r\n<td valign=\"top\" width=\"183\">dy<\/td>\r\n<td valign=\"top\" width=\"213\">1-366<\/td>\r\n<\/tr>\r\n<tr>\r\n<td valign=\"top\" width=\"147\">Day<\/td>\r\n<td valign=\"top\" width=\"183\">dd<\/td>\r\n<td valign=\"top\" width=\"213\">1-31<\/td>\r\n<\/tr>\r\n<tr>\r\n<td valign=\"top\" width=\"147\">Week<\/td>\r\n<td valign=\"top\" width=\"183\">wk<\/td>\r\n<td valign=\"top\" width=\"213\">1-53<\/td>\r\n<\/tr>\r\n<tr>\r\n<td valign=\"top\" width=\"147\">Weekday<\/td>\r\n<td valign=\"top\" width=\"183\">dw<\/td>\r\n<td valign=\"top\" width=\"213\">1-7 (Sun.-Sat.)<\/td>\r\n<\/tr>\r\n<tr>\r\n<td valign=\"top\" width=\"147\">Hour<\/td>\r\n<td valign=\"top\" width=\"183\">hh<\/td>\r\n<td valign=\"top\" width=\"213\">0-23<\/td>\r\n<\/tr>\r\n<tr>\r\n<td valign=\"top\" width=\"147\">Minute<\/td>\r\n<td valign=\"top\" width=\"183\">mi<\/td>\r\n<td valign=\"top\" width=\"213\">0-59<\/td>\r\n<\/tr>\r\n<tr>\r\n<td valign=\"top\" width=\"147\">Second<\/td>\r\n<td valign=\"top\" width=\"183\">ss<\/td>\r\n<td valign=\"top\" width=\"213\">0-59<\/td>\r\n<\/tr>\r\n<tr>\r\n<td valign=\"top\" width=\"147\">Millisecond<\/td>\r\n<td valign=\"top\" width=\"183\">ms<\/td>\r\n<td valign=\"top\" width=\"213\">0-999<\/td>\r\n<\/tr>\r\n<\/tbody>\r\n<\/table>\r\n<em>Table 16.5. Date part abbreviations and values.<\/em>\r\n<h2>Mathematical functions<b>\u00a0<\/b><\/h2>\r\nMathematical functions\u00a0perform operations on numeric data. The following example lists the current price for each book sold by the publisher\u00a0and what they would be if all prices increased by 10%.\r\n<div class=\"textbox shaded\">SELECT Price, (price * 1.1) AS 'New Price', title\r\nFROM\u00a0Books\r\nSELECT 'Square Root' = SQRT(81)\r\nSELECT 'Rounded\u2018 = ROUND(4567.9876,2)\r\nSELECT FLOOR (123.45)<\/div>\r\n<h1>Joining Tables<\/h1>\r\nJoining two or more tables is the process of comparing the data in specified columns and using the comparison results to form a new table from the rows that qualify. A join statement:\r\n<ul>\r\n \t<li>Specifies a column from each table<\/li>\r\n \t<li>Compares the values in those columns row by row<\/li>\r\n \t<li>Combines rows with qualifying values into a new row<\/li>\r\n<\/ul>\r\n<span style=\"color: #333333;\">Although the comparison is usually for equality \u2013 values that match exactly \u2013 other types of joins can also be specified. All the different joins such as inner, left (outer), right (outer), and cross join will be described below.<\/span>\r\n<h2>Inner join<\/h2>\r\nAn <em>inner join<\/em> connects two tables\u00a0on a column with the same data type. Only the rows where the column values match are returned; unmatched rows are discarded.\r\n\r\n<strong>Example #1<\/strong>\r\n<div class=\"textbox shaded\">SELECT jobs.job_id, job_desc\r\nFROM jobs\r\nINNER JOIN Employees ON employee.job_id = jobs.job_id\r\nWHERE jobs.job_id &lt; 7<\/div>\r\n<b>Example #2\r\n<\/b>\r\n<div class=\"textbox shaded\">SELECT authors.au_fname, authors.au_lname, books.royalty, title\r\nFROM authorsINNER JOIN titleauthor ON authors.au_id=titleauthor.au_id\r\nINNER JOIN books\u00a0ON titleauthor.title_id=books.title_id\r\nGROUP BY authors.au_lname, authors.au_fname, title, title.royalty\r\nORDER BY authors.au_lname<\/div>\r\n<h2>Left outer join<\/h2>\r\nA <em>left outer join<\/em> specifies that all left outer rows be returned. All rows from the left table that did not meet the condition specified are included in the results set, and output columns from the other table are set to NULL.\r\n\r\nThis first example uses the new syntax for a left outer join.\r\n<div class=\"textbox shaded\">SELECT publishers.pub_name, books.title\r\nFROM Publishers\r\nLEFT OUTER JOIN Books\u00a0On publishers.pub_id = books.pub_id<\/div>\r\nThis is an example of a left outer join using the old syntax.\r\n<div class=\"textbox shaded\">SELECT publishers.pub_name, books.title\r\nFROM Publishers,\u00a0Books\r\nWHERE publishers.pub_id *= books.pub_id<\/div>\r\n<h2>Right outer join<\/h2>\r\nA <em>right outer join<\/em> includes, in its result set, all rows from the right table that did not meet the condition specified. Output columns that correspond to the other table are set to NULL.\r\n\r\nBelow is an example using the new syntax for a right outer join.\r\n<div class=\"textbox shaded\">SELECT titleauthor.title_id, authors.au_lname, authors.au_fname\r\nFROM titleauthor\r\nRIGHT OUTER JOIN authors\u00a0ON titleauthor.au_id = authors.au_id\r\nORDERY BY au_lname<\/div>\r\nThis second example show the old syntax used for a right outer join.\r\n<div class=\"textbox shaded\">SELECT titleauthor.title_id, authors.au_lname, authors.au_fname\r\nFROM titleauthor, authors\r\nWHERE titleauthor.au_id =* authors.au_id\r\nORDERY BY au_lname<\/div>\r\n<h2>Full outer join<\/h2>\r\nA <em>full outer join<\/em> specifies that if a row from either table does not match the selection criteria, the row is included in the result set, and its output columns that correspond to the other table are set to NULL.\r\n\r\nHere is an example of a full outer join.\r\n<div class=\"textbox shaded\">SELECT books.title, publishers.pub_name, publishers.province\r\nFROM Publishers\r\nFULL OUTER JOIN Books\u00a0ON books.pub_id = publishers.pub_id\r\nWHERE (publishers.province &lt;&gt; \u201cBC\u201d and publishers.province &lt;&gt; \u201cON\u201d)\r\nORDER BY books.title_id<\/div>\r\n<h2><b>\u00a0<\/b>Cross join<\/h2>\r\nA <em>cross join<\/em> is a product combining two tables. This join returns the same rows as if no WHERE clause were specified. For example:\r\n<div class=\"textbox shaded\">SELECT au_lname, pub_name,\r\nFROM Authors CROSS JOIN Publishers<\/div>\r\n&nbsp;\r\n<div class=\"textbox textbox--key-takeaways\"><header class=\"textbox__header\">\r\n<p class=\"textbox__title\">Key Terms<\/p>\r\n\r\n<\/header>\r\n<div class=\"textbox__content\"><strong>aggregate function<\/strong>:\u00a0returns summary values<strong>ASC<\/strong>: ascending order\r\n\r\n<strong>conversion function<\/strong>:\u00a0transforms one data type to another\r\n\r\n<strong>cross join<\/strong>:\u00a0a product combining two tables\r\n\r\n<strong>date function<\/strong>:\u00a0displays information about dates and times\r\n\r\n<strong>DELETE\u00a0statement<\/strong>:\u00a0removes rows from a record set\r\n\r\n<strong>DESC<\/strong>: descending order\r\n\r\n<strong>full outer join<\/strong>: specifies that if a row from either table does not match the selection criteria\r\n\r\n<strong>GROUP BY<\/strong>:\u00a0used to create one output row per each group and produces summary values for the selected columns\r\n\r\n<strong>inner join<\/strong>:\u00a0connects two tables\u00a0on a column with the same data type\r\n\r\n<strong>INSERT statement<\/strong>:\u00a0adds rows to a table\r\n\r\n<strong>left outer join<\/strong>:\u00a0specifies that all left outer rows be returned\r\n\r\n<strong>mathematical function<\/strong>:\u00a0performs operations on numeric data\r\n\r\n<strong>right outer join<\/strong>: includes all rows from the right table that did not meet the condition specified\r\n\r\n<strong>SELECT statemen<\/strong>t: used\u00a0to query data in the database\r\n\r\n<strong>string function<\/strong>:\u00a0performs operations on character strings, binary data or expressions\r\n\r\n<strong>system function<\/strong>:\u00a0returns a special piece of information from the database\r\n\r\n<strong>text and image functions<\/strong>:\u00a0performs operations on text and image data\r\n\r\n<strong>UPDATE\u00a0statement:<\/strong>\u00a0changes data in existing rows either by adding new data or modifying existing data\r\n\r\n<strong>wildcard<\/strong>:\u00a0 allows the user to match fields that contain certain letters.\r\n\r\n<\/div>\r\n<\/div>\r\n<div class=\"textbox textbox--exercises\"><header class=\"textbox__header\">\r\n<p class=\"textbox__title\">Exercises<\/p>\r\n\r\n<\/header>\r\n<div class=\"textbox__content\">\r\n<p style=\"color: #1f1f1d;\">For questions 1 to 18 use\u00a0the PUBS sample database created by Microsoft. To download the script to generate this database please go to the following site:\u00a0<a style=\"color: #870d0d;\" href=\"http:\/\/www.microsoft.com\/en-ca\/download\/details.aspx?id=23654\">http:\/\/www.microsoft.com\/en-ca\/download\/details.aspx?id=23654<\/a>.<\/p>\r\n\r\n<ol>\r\n \t<li>Display a list of publication dates and titles (books) that were published in 2011.<\/li>\r\n \t<li>Display a list of titles that have been categorized as either traditional or modern cooking. Use the Books table.<\/li>\r\n \t<li>Display all authors whose first names are five letters long.<\/li>\r\n \t<li>Display from the Books table: type, price, pub_id, title about the books put out by each publisher. Rename the column type with \u201dBook Category.\u201d Sort by type (descending) and then price (ascending).<\/li>\r\n \t<li>Display title_id, pubdate and pubdate plus three\u00a0days, using the Books table.<\/li>\r\n \t<li>Using the datediff and getdate function determine how much time has elapsed in months since the books in the Books table were published.<\/li>\r\n \t<li>List the title IDs and quantity of all books that sold more than 30 copies.<\/li>\r\n \t<li>Display a list of all last names of the authors who live in Ontario (ON) and the cities where they live.<\/li>\r\n \t<li>Display all rows that contain a 60 in the payterms field. Use the Sales table.<\/li>\r\n \t<li>Display all authors whose first names are five letters long , end in O or A, and start with M or P.<\/li>\r\n \t<li>Display all titles that cost more than $30 and either begin with T or have a publisher ID of \u00a00877.<\/li>\r\n \t<li>Display from the Employees table the first name (fname), last name (lname), employe ID(emp_id) and job level (job_lvl) columns for those employees with a job level greater than 200; and rename the column headings to:\u00a0 \u201cFirst Name,\u201d \u201cLast Name,\u201d \u201cIDENTIFICATION#\u201d and \u201cJob Level.\u201d<\/li>\r\n \t<li>Display the royalty, royalty plus 50% as \u201croyalty plus 50\u201d and title_id. Use the Roysched table.<\/li>\r\n \t<li>Using the STUFF function create a string \u201c12xxxx567\u201d from the string \u201c1234567.\u201d<\/li>\r\n \t<li>Display the first 40 characters of each title, along with the average monthly sales for that title to date (ytd_sales\/12). Use the Title table.<\/li>\r\n \t<li>Show how many books have assigned prices.<\/li>\r\n \t<li>Display a list of cookbooks with the average cost for all of the books of each type. Use the GROUP BY.<\/li>\r\n<\/ol>\r\n<\/div>\r\n<\/div>\r\n<div class=\"textbox textbox--exercises\"><header class=\"textbox__header\">\r\n<p class=\"textbox__title\">Advanced Questions (Union, Intersect, and Minus)<\/p>\r\n\r\n<\/header>\r\n<div class=\"textbox__content\">\r\n<ol>\r\n \t<li>The relational set operators UNION, INTERSECT and MINUS work properly only if the relations are union-compatible. What does\u00a0union-compatible\u00a0mean, and how would you check for this condition?<\/li>\r\n \t<li>What is the difference between UNION and UNION ALL? Write the syntax for each.<\/li>\r\n \t<li>Suppose that you have two tables, Employees and Employees_1. The Employees table contains the records for three employees: Alice Cordoza, John Cretchakov, and Anne McDonald. The Employees_1 table contains the records for employees: John Cretchakov and Mary Chen. Given that information, what is the query output for the UNION query? List the query output.<\/li>\r\n \t<li>Given the employee information in question 3, what is the query output for the UNION ALL query? List the query output.<\/li>\r\n \t<li>Given the employee information in question 3, what is the query output for the INTERSECT query? List the query output.<\/li>\r\n \t<li>Given the employee information in question 3, what is the query output for the EXCEPT query? List the query output.<\/li>\r\n \t<li>What is a cross join? Give an example of its syntax.<\/li>\r\n \t<li>Explain these three join types:\r\n<ol>\r\n \t<li>left outer join<\/li>\r\n \t<li>right outer join<\/li>\r\n \t<li>full outer join<\/li>\r\n<\/ol>\r\n<\/li>\r\n \t<li>What is a subquery, and what are its basic characteristics?<\/li>\r\n \t<li>What is a correlated subquery? Give an example.<\/li>\r\n \t<li>Suppose that a Product table contains two attributes, PROD_CODE and VEND_CODE. The values for the PROD_CODE are:\u00a0ABC, DEF, GHI and JKL. These are matched by the following values for the VEND_CODE: \u00a0125, 124, 124 and 123, respectively (e.g., PROD_CODE value\u00a0ABC corresponds to\u00a0VEND_CODE\u00a0value\u00a0125). The Vendor table contains a single attribute, VEND_CODE, with values 123, 124, 125 and 126. (The VEND_CODE attribute in the Product table is a foreign key to the VEND_CODE in the Vendor table.)<\/li>\r\n \t<li>Given the information in question 11, what would be the query output for the following? Show values.\r\n<ol>\r\n \t<li>A UNION query based on these two tables<\/li>\r\n \t<li>A UNION ALL query based on these two tables<\/li>\r\n \t<li>An INTERSECT query based on these two tables<\/li>\r\n \t<li>A MINUS query based on these two tables<\/li>\r\n<\/ol>\r\n<\/li>\r\n<\/ol>\r\n<\/div>\r\n<\/div>\r\n<div class=\"textbox textbox--exercises\"><header class=\"textbox__header\">\r\n<p class=\"textbox__title\">Advanced Questions (Using Joins)<\/p>\r\n\r\n<\/header>\r\n<div class=\"textbox__content\">\r\n<ol>\r\n \t<li>Display a list of all titles and sales numbers in the Books and Sales tables, including titles that have no sales. Use a join.<\/li>\r\n \t<li>Display a list of authors\u2019 last names and all associated titles that each\u00a0author has published sorted by the author\u2019s last name. Use a join.\u00a0 Save it as a view named: Published Authors.<\/li>\r\n \t<li>Using a subquery, display all the authors (show last and first name, postal code) who receive a royalty of 100% and live in Alberta. Save it as a view titled: AuthorsView. When creating the view, rename the author\u2019s last name and first name as \u2018Last Name\u2019 and \u2018First Name\u2019.<\/li>\r\n \t<li>Display the stores that did not sell the title\u00a0<em>Is Anger the Enemy?<\/em><\/li>\r\n \t<li>Display a list of store names for sales after 2013 (Order Date is greater than 2013). \u00a0Display store name and order date.<\/li>\r\n \t<li>Display a list of titles for books sold in store name \u201cNews &amp; Brews.\u201d \u00a0Display store name, titles and order dates.<\/li>\r\n \t<li>List total sales (qty) by title. Display total quantity and title columns.<\/li>\r\n \t<li>List total sales (qty) by type. Display total quantity and type columns.<\/li>\r\n \t<li>List total sales (qty*price) by type. Display total dollar\u00a0value and type columns.<\/li>\r\n \t<li>Calculate the total number of types of books by publisher. Show publisher name and total count of types of books for each publisher.<\/li>\r\n \t<li>Show publisher names that do not have any type of book.\u00a0 Display publisher name only.<\/li>\r\n<\/ol>\r\n<\/div>\r\n<\/div>","rendered":"<p style=\"text-align: left; text-align: center;\">The SQL data manipulation language (DML) is used to query and modify database data. In this chapter, we will describe how to use the SELECT, INSERT, UPDATE, and DELETE\u00a0SQL DML command statements, defined below.<\/p>\n<ul>\n<li><em>SELECT<\/em>\u00a0 &#8211; to query data in the database<\/li>\n<li><em>INSERT<\/em>\u00a0 &#8211; to insert data into a table<\/li>\n<li><em>UPDATE<\/em>\u00a0&#8211; to update data in a table<\/li>\n<li><em>DELETE<\/em>\u00a0&#8211; to delete data from a table<\/li>\n<\/ul>\n<p>In the SQL DML statement:<\/p>\n<ul>\n<li>Each clause in a statement should begin on a new line.<\/li>\n<li>The beginning of each clause should line up with the beginning of other clauses.<\/li>\n<li>If a clause has several parts, they should appear on separate lines and be indented under the start of the clause to show the relationship.<\/li>\n<li>Upper case letters are used to represent reserved words.<\/li>\n<li>Lower case letters are used to represent user-defined words.<\/li>\n<\/ul>\n<h1>SELECT Statement<\/h1>\n<p>The SELECT statement, or command, allows the user to extract data from tables, based on specific criteria. It\u00a0<span>is processed according to the following sequence:<\/span><\/p>\n<p>SELECT DISTINCT item(s)<br \/>\nFROM\u00a0 table(s)<br \/>\nWHERE\u00a0 predicate<br \/>\nGROUP BY\u00a0 field(s)<br \/>\nORDER BY fields<\/p>\n<p>We can use the SELECT\u00a0statement to generate an employee phone list from the Employees table as follows:<\/p>\n<div class=\"textbox shaded\">SELECT \u00a0FirstName, LastName, phone<br \/>\nFROM Employees<br \/>\nORDER BY LastName<\/div>\n<p><span style=\"color: #333333;\">This action will<\/span> display employee&#8217;s last name, first name, and phone number from the Employees table, seen in Table 16.1.<\/p>\n<table>\n<tbody>\n<tr>\n<td><strong>Last Name<\/strong><\/td>\n<td><strong>First Name<\/strong><\/td>\n<td><strong>Phone Number<\/strong><\/td>\n<\/tr>\n<tr>\n<td>Hagans<\/td>\n<td>Jim<\/td>\n<td><span>604-232-3232<\/span><\/td>\n<\/tr>\n<tr>\n<td>Wong<\/td>\n<td>Bruce<\/td>\n<td><span>604-244-2322<\/span><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p><em>Table 16.1. Employees table.<\/em><\/p>\n<p>In this next example, we will use a Publishers table (Table 16.2). (You will notice that Canada is mispelled in the <em>Publisher Country<\/em> field for Example Publishing and ABC Publishing.\u00a0<span>To correct mispelling, use the UPDATE statement to standardize the country field to Canada &#8211; see UPDATE statement later in this chapter.)<\/span><\/p>\n<table>\n<tbody>\n<tr>\n<td><strong>Publisher Name<\/strong><\/td>\n<td><strong>Publisher City<\/strong><\/td>\n<td><strong>Publisher Province<\/strong><\/td>\n<td><strong>Publisher Country<\/strong><\/td>\n<\/tr>\n<tr>\n<td>Acme Publishing<\/td>\n<td>Vancouver<\/td>\n<td>BC<\/td>\n<td>Canada<\/td>\n<\/tr>\n<tr>\n<td>Example Publishing<\/td>\n<td>Edmonton<\/td>\n<td>AB<\/td>\n<td>Cnada<\/td>\n<\/tr>\n<tr>\n<td>ABC Publishing<\/td>\n<td>Toronto<\/td>\n<td>ON<\/td>\n<td>Canda<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p><em>Table 16.2. Publishers table.<\/em><\/p>\n<p>If you add the publisher&#8217;s name and city, you would use the SELECT statement followed by the fields name separated by a comma:<\/p>\n<div class=\"textbox shaded\">SELECT PubName, city<br \/>\nFROM Publishers<\/div>\n<p>This action will display the publisher&#8217;s name and city from the Publishers table.<\/p>\n<p><span style=\"color: #333333;\">If you just want the publisher&#8217;s name under the display name city, you would use the SELECT statement with <em>no comma<\/em> separating pub_name and city:<\/span><\/p>\n<div class=\"textbox shaded\">SELECT\u00a0<span>PubName city<\/span><br \/>\nFROM Publishers<\/div>\n<p><span>Performing this action will dis<\/span>play only the pub_name from the Publishers table with a &#8220;city&#8221; heading. \u00a0If you do not include the comma, SQL Server assumes you want a new column name for pub_name.<strong>\u00a0<\/strong><\/p>\n<h2>SELECT statement with WHERE criteria<\/h2>\n<p><span>Sometimes you might want to focus on a portion of the Publishers table, such as only publishers that are in Vancouver. In this situation, you would use the SELECT statement with the WHERE criterion, i.e., WHERE city = &#8216;Vancouver&#8217;.<\/span><\/p>\n<p>These first two examples illustrate\u00a0how to limit record<span>\u00a0selection\u00a0with the WHERE criterion\u00a0using BETWEEN. Each of these examples give the same results for store items with between 20 and 50 items in stock.<\/span><\/p>\n<p>Example #1 uses the quantity, <em>qty BETWEEN 20 and 50<\/em>.<\/p>\n<div class=\"textbox shaded\">SELECT StorID, qty, TitleID<br \/>\nFROM Sales<br \/>\nWHERE qty BETWEEN 20 and 50\u00a0 <i>(includes the 20 and 50)<\/i><\/div>\n<p>Example #2, on the other hand, uses <em>qty &gt;=20 and qty &lt;=50<\/em>\u00a0.<\/p>\n<div class=\"textbox shaded\">SELECT<span> StorID, qty, TitleID<\/span><br \/>\nFROM Sales<br \/>\nWHERE qty &gt;= 20 and qty\u00a0 &lt;= 50<\/div>\n<p><span style=\"color: #333333;\">Example #3 illustrates how to limit record selection with the WHERE criterion using NOT BETWEEN.<\/span><\/p>\n<div class=\"textbox shaded\">SELECT<span> StorID, qty, TitleID<\/span><br \/>\nFROM Sales<br \/>\nWHERE qty NOT BETWEEN 20 and 50<\/div>\n<p>The next two examples show two different ways\u00a0to limit record\u00a0selection\u00a0with the WHERE criterion using IN, with each yielding the same results.<\/p>\n<p>Example #4 shows how to select records using<em>\u00a0province= <\/em>as part of the WHERE statement.<\/p>\n<div class=\"textbox shaded\">SELECT *<br \/>\nFROM Publishers<br \/>\nWHERE province = &#8216;BC&#8217; OR province = &#8216;AB&#8217; OR province = &#8216;ON&#8217;<\/div>\n<p>Example #5 select records using <em>province IN<\/em> as part of the WHERE statement.<\/p>\n<div class=\"textbox shaded\">SELECT *<br \/>\nFROM Publishers<br \/>\nWHERE province IN (&#8216;BC&#8217;, &#8216;AB&#8217;, &#8216;ON&#8217;)<\/div>\n<p>The final two examples illustrate how NULL and NOT NULL can be used to select records. For these examples, a Books\u00a0table (not shown) would be used that contains fields called Title, Quantity, and Price (of book). Each publisher has a Book<span>s<\/span><span>\u00a0table that lists all of its books.<\/span><\/p>\n<p><span style=\"color: #333333;\">Example #6 uses NULL.<\/span><\/p>\n<div class=\"textbox shaded\">SELECT price, title<br \/>\nFROM Books<br \/>\nWHERE price IS NULL<\/div>\n<p>Example #7 uses NOT NULL.<\/p>\n<div class=\"textbox shaded\">SELECT price, title<br \/>\nFROM Books<br \/>\nWHERE price IS NOT NULL<\/div>\n<h2><span style=\"color: #333333;\">Using wildcards in the LIKE\u00a0clause<\/span><\/h2>\n<p>The LIKE keyword selects rows containing fields that match specified portions of character strings. LIKE is used with char, varchar, text, datetime and smalldatetime data. A <em>wildcard\u00a0<\/em>allows the user to match fields that contain certain letters. For example, the wildcard province = &#8216;N%&#8217; would give all provinces that start with the letter &#8216;N&#8217;. Table 16.3 shows four ways to specify wildcards in the SELECT statement in regular express format.<\/p>\n<table style=\"width: 622px; border-spacing: 0px;\" cellpadding=\"0\">\n<tbody>\n<tr>\n<td valign=\"top\" style=\"width: 105px;\">\n<p style=\"text-align: center;\">%<\/p>\n<\/td>\n<td style=\"text-align: left; width: 517px;\" valign=\"top\">Any string of zero or more characters<\/td>\n<\/tr>\n<tr>\n<td valign=\"top\" style=\"width: 105px;\">\n<p style=\"text-align: center;\">_<\/p>\n<\/td>\n<td valign=\"top\" style=\"width: 517px;\">Any single character<\/td>\n<\/tr>\n<tr>\n<td valign=\"top\" style=\"width: 105px;\">\n<p style=\"text-align: center;\">[ ]<\/p>\n<\/td>\n<td valign=\"top\" style=\"width: 517px;\">Any single character within the specified range (e.g., [a-f]) or set (e.g., [abcdef])<\/td>\n<\/tr>\n<tr>\n<td valign=\"top\" style=\"width: 105px;\">\n<p style=\"text-align: center;\">[^]<\/p>\n<\/td>\n<td valign=\"top\" style=\"width: 517px;\">Any single character not within the specified range (e.g., [^a &#8211; f]) or set (e.g., [^abcdef])<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p><em>Table 16.3. How to specify wildcards in the SELECT statement.<\/em><\/p>\n<p>In example #1,\u00a0LIKE &#8216;Mc%&#8217; searches for all last names that begin with the letters &#8220;Mc&#8221; (e.g., McBadden).<\/p>\n<div class=\"textbox shaded\">SELECT LastName<br \/>\nFROM Employees<br \/>\nWHERE <span>LastName<\/span>\u00a0LIKE &#8216;Mc%&#8217;<\/div>\n<p>For example #2: LIKE &#8216;%inger&#8217; searches for all last names that end with the letters &#8220;inger&#8221; (e.g., Ringer, Stringer).<\/p>\n<div class=\"textbox shaded\">SELECT\u00a0<span>LastName<\/span><br \/>\nFROM Employees<br \/>\nWHERE <span>LastName<\/span>\u00a0LIKE &#8216;%inger&#8217;<\/div>\n<p>In, example #3: LIKE &#8216;%en%&#8217; searches for all last names that have the letters &#8220;en&#8221; (e.g., Bennett, Green, McBadden).<\/p>\n<div class=\"textbox shaded\">SELECT\u00a0<span>LastName<\/span><br \/>\nFROM Employees<br \/>\nWHERE <span>LastName<\/span> LIKE &#8216;%en%&#8217;<\/div>\n<h2>SELECT statement with ORDER BY\u00a0clause<\/h2>\n<p>You use the ORDER BY\u00a0clause to sort the records in the resulting list. Use\u00a0<em>ASC\u00a0<\/em>to sort the\u00a0results\u00a0in ascending order and <em>DESC\u00a0<\/em>to sort the results\u00a0in descending order.<\/p>\n<p>For example, with ASC:<\/p>\n<div class=\"textbox shaded\">SELECT *<br \/>\nFROM Employees<br \/>\nORDER BY HireDate ASC<\/div>\n<p>And with DESC:<\/p>\n<div class=\"textbox shaded\">SELECT *<br \/>\nFROM Books<br \/>\nORDER B<span style=\"color: #000000;\">Y type, pric<\/span>e DESC<\/div>\n<h2>SELECT\u00a0statement with GROUP BY\u00a0clause<\/h2>\n<p>The <em>GROUP BY\u00a0<\/em>clause is used to create one output row per each group and produces summary values for the selected columns, as shown below.<\/p>\n<div class=\"textbox\">SELECT type<br \/>\nFROM\u00a0Books<br \/>\nGROUP BY type<\/div>\n<p>Here is an example using the above statement.<\/p>\n<div class=\"textbox shaded\">SELECT type AS &#8216;Type&#8217;, MIN(price) AS &#8216;Minimum Price&#8217;<br \/>\nFROM\u00a0Books<br \/>\nWHERE royalty &gt; 10<br \/>\nGROUP BY type<\/div>\n<p>If the SELECT statement includes a WHERE criterion where <em>price is not null<\/em>,<\/p>\n<div class=\"textbox\">SELECT type, price<br \/>\nFROM\u00a0Books<br \/>\nWHERE price is not null<\/div>\n<p>then a statement with the GROUP BY clause would look like this:<\/p>\n<div class=\"textbox shaded\">SELECT type AS &#8216;Type&#8217;, MIN(price) AS &#8216;Minimum Price&#8217;<br \/>\nFROM\u00a0Books<br \/>\nWHERE price is not null<br \/>\nGROUP BY type<\/div>\n<h3>Using COUNT with GROUP BY<\/h3>\n<p>We can use COUNT to tally how many items are in a container. However, if we want to count different items into separate groups, such as marbles of varying colours, then we would use the COUNT function with the GROUP BY command.<\/p>\n<p>The below SELECT statement illustrates how to count groups of data using the COUNT function with the GROUP BY clause.<\/p>\n<div class=\"textbox\">SELECT COUNT(*)<br \/>\nFROM\u00a0Books<br \/>\nGROUP BY type<\/div>\n<h3>Using AVG and SUM with GROUP BY<\/h3>\n<p>We can use the AVG function to give us the average of any group, and SUM to give the total.<\/p>\n<p>Example #1 uses the AVG FUNCTION with the GROUP BY type.<\/p>\n<div class=\"textbox shaded\">SELECT AVG(qty)<br \/>\nFROM\u00a0Books<br \/>\nGROUP BY type<\/div>\n<p>Example #2 uses the SUM function with the GROUP BY type.<\/p>\n<div class=\"textbox shaded\">SELECT SUM(qty)<br \/>\nFROM Books<br \/>\nGROUP BY type<\/div>\n<p>Example #3 uses both the AVG and SUM functions with the GROUP BY type in the SELECT statement.<\/p>\n<div class=\"textbox shaded\">SELECT &#8216;Total Sales&#8217; = SUM(qty), &#8216;Average Sales&#8217; = AVG(qty), stor_id<br \/>\nFROM Sales<br \/>\nGROUP BY StorID ORDER BY\u00a0 &#8216;Total Sales&#8217;<\/div>\n<h2>Restricting rows with HAVING<\/h2>\n<p>The HAVING clause can be used to restrict rows. It is similar to the WHERE condition except HAVING\u00a0can include the aggregate function; the WHERE cannot do this.<\/p>\n<p>The HAVING clause behaves like the WHERE clause, but is applicable to groups. In this example, we use the HAVING clause to exclude the groups with the province &#8216;BC&#8217;.<\/p>\n<div class=\"textbox shaded\">SELECT au_fname AS &#8216;Author&#8221;s First Name&#8217;, province as &#8216;Province&#8217;<br \/>\nFROM Authors<br \/>\nGROUP BY au_fname, province<br \/>\nHAVING province &lt;&gt; &#8216;BC&#8217;<\/div>\n<h2>INSERT statement<\/h2>\n<p>The <em>INSERT statement<\/em> adds rows to a table. In addition,<\/p>\n<ul>\n<li>INSERT specifies the table or view that data will be inserted into.<\/li>\n<li>Column_list lists columns that will be affected by the INSERT.<\/li>\n<li>If a column is omitted, each value must be provided.<\/li>\n<li>If you are including columns, they can be listed in any order.<\/li>\n<li>VALUES specifies the data that you want to insert into the table.\u00a0VALUES is required.<\/li>\n<li>Columns with the IDENTITY property should not be explicitly listed in the column_list or values_clause.<\/li>\n<\/ul>\n<p>The syntax for the INSERT statement is:<\/p>\n<div class=\"textbox\">INSERT [INTO] Table_name | view name [column_list]<br \/>\nDEFAULT VALUES | values_list | select statement<\/div>\n<p>When inserting rows with the INSERT statement, these rules apply:<\/p>\n<ul>\n<li>Inserting an empty string (&#8216; &#8216;) into a varchar or text column inserts a single space.<\/li>\n<li>All char columns are\u00a0right-padded to the defined length.<\/li>\n<li>All trailing spaces are removed\u00a0from data inserted into varchar columns, except in strings that contain\u00a0only spaces. These strings are truncated to a single space.<\/li>\n<li>If an INSERT statement violates a constraint, default or rule, or if it is the wrong data type, the\u00a0statement fails and SQL Server displays an error message.<\/li>\n<\/ul>\n<p>When you specify values for only some of the columns in the column_list, one of three things can happen to the columns that have no values:<\/p>\n<ol>\n<li>A default value is entered if\u00a0the column has a DEFAULT constraint, if a default is bound to the column, or if a default is bound to the underlying user-defined data type.<\/li>\n<li>NULL is entered if the column allows NULLs and no default value exists for the column.<\/li>\n<li>An error message is displayed\u00a0and the row is rejected if the column is defined as NOT NULL and no\u00a0default exists.<\/li>\n<\/ol>\n<p>This example uses INSERT to add a record to the publisher&#8217;s Authors table.<\/p>\n<div class=\"textbox shaded\">INSERT INTO Authors<br \/>\nVALUES(\u2018555-093-467\u2019, \u2018Martin\u2019, \u2018April\u2019, \u2018281 555-5673\u2019, \u2018816 Market St.,\u2019 , \u2018Vancouver\u2019, \u2018BC\u2019, \u2018V7G3P4\u2019, 0)<\/div>\n<p>This following example illustrates how to insert a partial row into the Publishers table with a column list. The country column had a default value of Canada so it does not require that you include it in your values.<\/p>\n<div class=\"textbox shaded\">INSERT INTO Publishers\u00a0(PubID, PubName, city, province)<br \/>\nVALUES (\u20189900\u2019, \u2018Acme Publishing\u2019, \u2018Vancouver\u2019, \u2018BC\u2019)<\/div>\n<p>To insert rows into a table with an IDENTITY column, follow the below example.\u00a0Do not supply the value for the IDENTITY nor the name of the column in the column list.<\/p>\n<div class=\"textbox shaded\">INSERT INTO jobs<br \/>\nVALUES (\u2018DBA\u2019, 100, 175)<\/div>\n<h3>Inserting specific values into an IDENTITY column<\/h3>\n<p>By default, data cannot be inserted directly into an IDENTITY column; however, if a row is accidentally deleted, or there are gaps in the IDENTITY column values, you can insert a row and specify the IDENTITY column value.<\/p>\n<div class=\"textbox\">IDENTITY_INSERT option<\/div>\n<p>To allow an insert with a specific identity value, the IDENTITY_INSERT option can be used as follows.<\/p>\n<div class=\"textbox shaded\">SET IDENTITY_INSERT jobs ON<br \/>\nINSERT INTO jobs \u00a0(job_id, job_desc, min_lvl, max_lvl)<br \/>\nVALUES (19, \u2019DBA2\u2019, 100, 175)<br \/>\nSET IDENTITY_INSERT jobs OFF<\/div>\n<h3>\u00a0Inserting rows with a SELECT\u00a0statement<\/h3>\n<p>We can sometimes create a small temporary table from a large table. For this, we can insert rows with a SELECT statement. When using this command, there is no validation for uniqueness. Consequently, there may be many rows with the same pub_id in the example below.<\/p>\n<p>This example creates a smaller temporary Publishers table using the CREATE TABLE statement. Then the INSERT with a SELECT statement is used to add records to this temporary Publishers table from the publis table.<\/p>\n<div class=\"textbox shaded\">CREATE TABLE dbo.tmpPublishers (<br \/>\nPubID char (4) NOT NULL ,<br \/>\nPubName varchar (40) NULL ,<br \/>\ncity varchar (20) NULL ,<br \/>\nprovince char (2) NULL ,<br \/>\ncountry varchar (30) NULL\u00a0 DEFAULT (\u2018Canada\u2019)<br \/>\n)<br \/>\nINSERT\u00a0 tmpPublishers<br \/>\nSELECT * FROM Publishers<\/div>\n<p>In this example, we&#8217;re copying a subset of data.<\/p>\n<div class=\"textbox shaded\">INSERT tmpPublishers (pub_id, pub_name)<br \/>\nSELECT PubID, PubName<br \/>\nFROM Publishers<\/div>\n<p>In this example, the publishers\u2019 data are copied to the tmpPublishers table and the country column is set to Canada.<\/p>\n<div class=\"textbox shaded\">INSERT tmpPublishers (<span>PubID, PubName<\/span>, city, province, country)<br \/>\nSELECT <span>PubID, PubName<\/span>, city, province, \u2018Canada\u2019<br \/>\nFROM Publishers<\/div>\n<h2>UPDATE statement<\/h2>\n<p>The <em>UPDATE\u00a0statement<\/em> changes data in existing rows either by adding new data or modifying existing data.<\/p>\n<p>This example uses the UPDATE statement to standardize the country field to be Canada for all records in the Publishers table.<\/p>\n<div class=\"textbox\">UPDATE Publishers<br \/>\nSET country = \u2018Canada\u2019<\/div>\n<p>This example increases the royalty amount by 10% for those royalty amounts between 10 and 20.<\/p>\n<div class=\"textbox shaded\">UPDATE roysched<br \/>\nSET royalty = royalty + (royalty * .10)<br \/>\nWHERE royalty BETWEEN 10 and 20<\/div>\n<h3>Including subqueries in an UPDATE statement<\/h3>\n<p>The employees from the Employees table who were hired by the publisher in 2010 are given a promotion to the highest job level for their job type. This is what the UPDATE statement would look like.<\/p>\n<div class=\"textbox shaded\">UPDATE Employees<br \/>\nSET job_lvl =<br \/>\n(SELECT max_lvl FROM jobs<br \/>\nWHERE employee.job_id = jobs.job_id)<br \/>\nWHERE DATEPART(year, employee.hire_date) = 2010<\/div>\n<h2>DELETE\u00a0statement<\/h2>\n<p>The <em>DELETE\u00a0statement<\/em> removes rows from a record set. DELETE names the table or view that holds the rows that will be deleted and only one table or row may be listed at a time. WHERE is\u00a0 a standard WHERE clause that limits the deletion to select records.<\/p>\n<p>The DELETE syntax looks like this.<\/p>\n<div class=\"textbox\">DELETE [FROM] {table_name | view_name }<br \/>\n[WHERE clause]<\/div>\n<p>The rules for the DELETE statement are:<\/p>\n<ol>\n<li>If you omit a WHERE clause, all rows in the table are removed\u00a0(except for indexes, the table, constraints)<i>.<\/i><\/li>\n<li>DELETE cannot be used with a view that has a FROM clause naming more than one table. (Delete can affect only one base table at a time.)<\/li>\n<\/ol>\n<p>What follows are three different DELETE statements that can be used.<\/p>\n<p>1. Deleting all rows from a table.<\/p>\n<div class=\"textbox\">DELETE<br \/>\nFROM Discounts<\/div>\n<p>2. Deleting selected rows:<\/p>\n<div class=\"textbox\">DELETE<br \/>\nFROM Sales<br \/>\nWHERE stor_id = \u20186380\u2019<\/div>\n<p>3. Deleting rows based on a value in a subquery:<\/p>\n<div class=\"textbox\">DELETE FROM Sales<br \/>\nWHERE title_id IN<br \/>\n(SELECT title_id FROM Books\u00a0WHERE type = \u2018mod_cook\u2019)<\/div>\n<h1>Built-in Functions<\/h1>\n<p>There are many built-in functions in SQL Server such as:<\/p>\n<ol>\n<li><em>Aggregate:<\/em>\u00a0returns summary values<\/li>\n<li><em>Conversion:<\/em>\u00a0transforms one data type to another<\/li>\n<li><em>Date:<\/em>\u00a0displays information about dates and times<\/li>\n<li><em>Mathematical:<\/em>\u00a0performs operations on numeric data<\/li>\n<li><em>String:<\/em>\u00a0performs operations on character strings, binary data or expressions<\/li>\n<li><em>System:<\/em>\u00a0returns a special piece of information from the database<\/li>\n<li><em>Text and image:<\/em>\u00a0performs operations on text and image data<\/li>\n<\/ol>\n<p>Below you will find detailed descriptions and examples for the first four functions.<\/p>\n<h2>Aggregate functions<\/h2>\n<p>Aggregate functions perform a calculation on a set of values and return a single, or summary, value. Table 16.4 lists these functions.<\/p>\n<table cellpadding=\"0\" style=\"border-spacing: 0px;\">\n<tbody>\n<tr>\n<td valign=\"top\" style=\"width: 16%;\"><strong>FUNCTION<\/strong><\/td>\n<td valign=\"top\" style=\"width: 83%;\"><strong>DESCRIPTION<\/strong><\/td>\n<\/tr>\n<tr>\n<td valign=\"top\" style=\"width: 16%;\">AVG<\/td>\n<td valign=\"top\" style=\"width: 83%;\">Returns the average of all the values, or only the DISTINCT values, in the expression.<\/td>\n<\/tr>\n<tr>\n<td valign=\"top\" style=\"width: 16%;\">COUNT<\/td>\n<td valign=\"top\" style=\"width: 83%;\">Returns the number of non-null values in the expression. When DISTINCT is specified, COUNT finds the number of unique non-null values.<\/td>\n<\/tr>\n<tr>\n<td valign=\"top\" style=\"width: 16%;\">COUNT(*)<\/td>\n<td valign=\"top\" style=\"width: 83%;\">Returns the number of rows. COUNT(*) takes no parameters and cannot be used with DISTINCT.<\/td>\n<\/tr>\n<tr>\n<td valign=\"top\" style=\"width: 16%;\">MAX<\/td>\n<td valign=\"top\" style=\"width: 83%;\">Returns the maximum value in the expression. MAX can be used with numeric, character and datetime columns, but not with bit columns. With character columns, MAX finds the highest value in the collating sequence. MAX ignores any null values.<\/td>\n<\/tr>\n<tr>\n<td valign=\"top\" style=\"width: 16%;\">MIN<\/td>\n<td valign=\"top\" style=\"width: 83%;\">Returns the minimum value in the expression. MIN can be used with numeric, character and datetime columns, but not with bit columns. With character columns, MIN finds the value that is lowest in the sort sequence. MIN ignores any null values.<\/td>\n<\/tr>\n<tr>\n<td valign=\"top\" style=\"width: 16%;\">SUM<\/td>\n<td valign=\"top\" style=\"width: 83%;\">Returns the sum of all the values, or only the DISTINCT values, in the expression. SUM can be used with numeric columns only.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p><em>Table 16.4\u00a0A list of aggregate functions and descriptions.<\/em><\/p>\n<p>Below are examples of each of the aggregate functions listed in Table 16.4.<\/p>\n<p><strong>Example #1: \u00a0AVG<\/strong><\/p>\n<div class=\"textbox shaded\">SELECT AVG (price) AS &#8216;Average Title Price&#8217;<br \/>\nFROM\u00a0Books<\/div>\n<p><strong>Example #2: COUNT<\/strong><\/p>\n<div class=\"textbox shaded\">SELECT COUNT(PubID) AS &#8216;Number of Publishers&#8217;<br \/>\nFROM Publishers<\/div>\n<p><strong>Example #3: COUNT<\/strong><\/p>\n<div class=\"textbox shaded\">SELECT COUNT(province) AS &#8216;Number of Publishers&#8217;<br \/>\nFROM Publishers<\/div>\n<p><strong>Example #3: COUNT (*)<\/strong><\/p>\n<div class=\"textbox shaded\">SELECT COUNT(*)<br \/>\nFROM Employees<br \/>\nWHERE job_lvl = 35<\/div>\n<p><strong>Example #4: MAX<\/strong><\/p>\n<div class=\"textbox shaded\">SELECT MAX (HireDate)<br \/>\nFROM Employees<\/div>\n<p><strong>Example #5: MIN<\/strong><\/p>\n<div class=\"textbox shaded\">SELECT MIN (price)<br \/>\nFROM\u00a0Books<\/div>\n<p><strong>Example #6: SUM<\/strong><\/p>\n<div class=\"textbox shaded\">SELECT SUM(discount) AS &#8216;Total Discounts&#8217;<br \/>\nFROM Discounts<\/div>\n<h2>Conversion function<\/h2>\n<p>The conversion function\u00a0transforms one data type to another.<\/p>\n<p>In the example below, a price that contains two 9s is converted into five characters. The syntax for this statement is\u00a0SELECT &#8216;The date is &#8216; + CONVERT(varchar(12), getdate()).<\/p>\n<div class=\"textbox shaded\">SELECT CONVERT(int, 10.6496)<br \/>\nSELECT title_id, price<br \/>\nFROM\u00a0Books<br \/>\nWHERE CONVERT(char(5), price) LIKE &#8216;%99%&#8217;<\/div>\n<p>In this second example, the conversion function changes data to a data type with a different size.<\/p>\n<div class=\"textbox shaded\">SELECT title_id, CONVERT(char(4), ytd_sales) as &#8216;Sales&#8217;<br \/>\nFROM\u00a0Books<br \/>\nWHERE type LIKE &#8216;%cook&#8217;<\/div>\n<h2>Date function<\/h2>\n<p>The date function produces a date by adding an interval to a specified date. The result is a datetime value equal to the date plus the number of date parts. If the date parameter is a smalldatetime value, the result is also a smalldatetime value.<\/p>\n<p>The DATEADD function is used to add and increment date values. The\u00a0syntax\u00a0for this function is\u00a0DATEADD(datepart, number, date).<\/p>\n<div class=\"textbox shaded\">SELECT DATEADD(day, 3, hire_date)<br \/>\nFROM Employees<\/div>\n<p>In this example, the\u00a0function\u00a0DATEDIFF(datepart, date1, date2) \u00a0is used.<\/p>\n<p>This command returns the number of datepart &#8220;boundaries&#8221; crossed between two specified dates. The method of counting crossed boundaries makes the result given by DATEDIFF consistent across all data types such as minutes, seconds, and milliseconds.<\/p>\n<div class=\"textbox shaded\">SELECT DATEDIFF(day, HireDate, &#8216;Nov 30 1995&#8217;)<br \/>\nFROM Employees<\/div>\n<p>For any particular date, we can examine any part of that date from the year to the millisecond.<\/p>\n<p>The date parts (DATEPART) and abbreviations recognized by SQL Server, and the acceptable values are listed in Table 16.5.<\/p>\n<table cellpadding=\"0\" style=\"border-spacing: 0px;\">\n<tbody>\n<tr>\n<td valign=\"top\" style=\"width: 147px;\"><strong>DATE PART<\/strong><\/td>\n<td valign=\"top\" style=\"width: 183px;\"><strong>ABBREVIATION<\/strong><\/td>\n<td valign=\"top\" style=\"width: 213px;\"><strong>VALUES<\/strong><\/td>\n<\/tr>\n<tr>\n<td valign=\"top\" style=\"width: 147px;\">Year<\/td>\n<td valign=\"top\" style=\"width: 183px;\">yy<\/td>\n<td valign=\"top\" style=\"width: 213px;\">1753-9999<\/td>\n<\/tr>\n<tr>\n<td valign=\"top\" style=\"width: 147px;\">Quarter<\/td>\n<td valign=\"top\" style=\"width: 183px;\">qq<\/td>\n<td valign=\"top\" style=\"width: 213px;\">1-4<\/td>\n<\/tr>\n<tr>\n<td valign=\"top\" style=\"width: 147px;\">Month<\/td>\n<td valign=\"top\" style=\"width: 183px;\">mm<\/td>\n<td valign=\"top\" style=\"width: 213px;\">1-12<\/td>\n<\/tr>\n<tr>\n<td valign=\"top\" style=\"width: 147px;\">Day of year<\/td>\n<td valign=\"top\" style=\"width: 183px;\">dy<\/td>\n<td valign=\"top\" style=\"width: 213px;\">1-366<\/td>\n<\/tr>\n<tr>\n<td valign=\"top\" style=\"width: 147px;\">Day<\/td>\n<td valign=\"top\" style=\"width: 183px;\">dd<\/td>\n<td valign=\"top\" style=\"width: 213px;\">1-31<\/td>\n<\/tr>\n<tr>\n<td valign=\"top\" style=\"width: 147px;\">Week<\/td>\n<td valign=\"top\" style=\"width: 183px;\">wk<\/td>\n<td valign=\"top\" style=\"width: 213px;\">1-53<\/td>\n<\/tr>\n<tr>\n<td valign=\"top\" style=\"width: 147px;\">Weekday<\/td>\n<td valign=\"top\" style=\"width: 183px;\">dw<\/td>\n<td valign=\"top\" style=\"width: 213px;\">1-7 (Sun.-Sat.)<\/td>\n<\/tr>\n<tr>\n<td valign=\"top\" style=\"width: 147px;\">Hour<\/td>\n<td valign=\"top\" style=\"width: 183px;\">hh<\/td>\n<td valign=\"top\" style=\"width: 213px;\">0-23<\/td>\n<\/tr>\n<tr>\n<td valign=\"top\" style=\"width: 147px;\">Minute<\/td>\n<td valign=\"top\" style=\"width: 183px;\">mi<\/td>\n<td valign=\"top\" style=\"width: 213px;\">0-59<\/td>\n<\/tr>\n<tr>\n<td valign=\"top\" style=\"width: 147px;\">Second<\/td>\n<td valign=\"top\" style=\"width: 183px;\">ss<\/td>\n<td valign=\"top\" style=\"width: 213px;\">0-59<\/td>\n<\/tr>\n<tr>\n<td valign=\"top\" style=\"width: 147px;\">Millisecond<\/td>\n<td valign=\"top\" style=\"width: 183px;\">ms<\/td>\n<td valign=\"top\" style=\"width: 213px;\">0-999<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p><em>Table 16.5. Date part abbreviations and values.<\/em><\/p>\n<h2>Mathematical functions<b>\u00a0<\/b><\/h2>\n<p>Mathematical functions\u00a0perform operations on numeric data. The following example lists the current price for each book sold by the publisher\u00a0and what they would be if all prices increased by 10%.<\/p>\n<div class=\"textbox shaded\">SELECT Price, (price * 1.1) AS &#8216;New Price&#8217;, title<br \/>\nFROM\u00a0Books<br \/>\nSELECT &#8216;Square Root&#8217; = SQRT(81)<br \/>\nSELECT &#8216;Rounded\u2018 = ROUND(4567.9876,2)<br \/>\nSELECT FLOOR (123.45)<\/div>\n<h1>Joining Tables<\/h1>\n<p>Joining two or more tables is the process of comparing the data in specified columns and using the comparison results to form a new table from the rows that qualify. A join statement:<\/p>\n<ul>\n<li>Specifies a column from each table<\/li>\n<li>Compares the values in those columns row by row<\/li>\n<li>Combines rows with qualifying values into a new row<\/li>\n<\/ul>\n<p><span style=\"color: #333333;\">Although the comparison is usually for equality \u2013 values that match exactly \u2013 other types of joins can also be specified. All the different joins such as inner, left (outer), right (outer), and cross join will be described below.<\/span><\/p>\n<h2>Inner join<\/h2>\n<p>An <em>inner join<\/em> connects two tables\u00a0on a column with the same data type. Only the rows where the column values match are returned; unmatched rows are discarded.<\/p>\n<p><strong>Example #1<\/strong><\/p>\n<div class=\"textbox shaded\">SELECT jobs.job_id, job_desc<br \/>\nFROM jobs<br \/>\nINNER JOIN Employees ON employee.job_id = jobs.job_id<br \/>\nWHERE jobs.job_id &lt; 7<\/div>\n<p><b>Example #2<br \/>\n<\/b><\/p>\n<div class=\"textbox shaded\">SELECT authors.au_fname, authors.au_lname, books.royalty, title<br \/>\nFROM authorsINNER JOIN titleauthor ON authors.au_id=titleauthor.au_id<br \/>\nINNER JOIN books\u00a0ON titleauthor.title_id=books.title_id<br \/>\nGROUP BY authors.au_lname, authors.au_fname, title, title.royalty<br \/>\nORDER BY authors.au_lname<\/div>\n<h2>Left outer join<\/h2>\n<p>A <em>left outer join<\/em> specifies that all left outer rows be returned. All rows from the left table that did not meet the condition specified are included in the results set, and output columns from the other table are set to NULL.<\/p>\n<p>This first example uses the new syntax for a left outer join.<\/p>\n<div class=\"textbox shaded\">SELECT publishers.pub_name, books.title<br \/>\nFROM Publishers<br \/>\nLEFT OUTER JOIN Books\u00a0On publishers.pub_id = books.pub_id<\/div>\n<p>This is an example of a left outer join using the old syntax.<\/p>\n<div class=\"textbox shaded\">SELECT publishers.pub_name, books.title<br \/>\nFROM Publishers,\u00a0Books<br \/>\nWHERE publishers.pub_id *= books.pub_id<\/div>\n<h2>Right outer join<\/h2>\n<p>A <em>right outer join<\/em> includes, in its result set, all rows from the right table that did not meet the condition specified. Output columns that correspond to the other table are set to NULL.<\/p>\n<p>Below is an example using the new syntax for a right outer join.<\/p>\n<div class=\"textbox shaded\">SELECT titleauthor.title_id, authors.au_lname, authors.au_fname<br \/>\nFROM titleauthor<br \/>\nRIGHT OUTER JOIN authors\u00a0ON titleauthor.au_id = authors.au_id<br \/>\nORDERY BY au_lname<\/div>\n<p>This second example show the old syntax used for a right outer join.<\/p>\n<div class=\"textbox shaded\">SELECT titleauthor.title_id, authors.au_lname, authors.au_fname<br \/>\nFROM titleauthor, authors<br \/>\nWHERE titleauthor.au_id =* authors.au_id<br \/>\nORDERY BY au_lname<\/div>\n<h2>Full outer join<\/h2>\n<p>A <em>full outer join<\/em> specifies that if a row from either table does not match the selection criteria, the row is included in the result set, and its output columns that correspond to the other table are set to NULL.<\/p>\n<p>Here is an example of a full outer join.<\/p>\n<div class=\"textbox shaded\">SELECT books.title, publishers.pub_name, publishers.province<br \/>\nFROM Publishers<br \/>\nFULL OUTER JOIN Books\u00a0ON books.pub_id = publishers.pub_id<br \/>\nWHERE (publishers.province &lt;&gt; \u201cBC\u201d and publishers.province &lt;&gt; \u201cON\u201d)<br \/>\nORDER BY books.title_id<\/div>\n<h2><b>\u00a0<\/b>Cross join<\/h2>\n<p>A <em>cross join<\/em> is a product combining two tables. This join returns the same rows as if no WHERE clause were specified. For example:<\/p>\n<div class=\"textbox shaded\">SELECT au_lname, pub_name,<br \/>\nFROM Authors CROSS JOIN Publishers<\/div>\n<p>&nbsp;<\/p>\n<div class=\"textbox textbox--key-takeaways\">\n<header class=\"textbox__header\">\n<p class=\"textbox__title\">Key Terms<\/p>\n<\/header>\n<div class=\"textbox__content\"><strong>aggregate function<\/strong>:\u00a0returns summary values<strong>ASC<\/strong>: ascending order<\/p>\n<p><strong>conversion function<\/strong>:\u00a0transforms one data type to another<\/p>\n<p><strong>cross join<\/strong>:\u00a0a product combining two tables<\/p>\n<p><strong>date function<\/strong>:\u00a0displays information about dates and times<\/p>\n<p><strong>DELETE\u00a0statement<\/strong>:\u00a0removes rows from a record set<\/p>\n<p><strong>DESC<\/strong>: descending order<\/p>\n<p><strong>full outer join<\/strong>: specifies that if a row from either table does not match the selection criteria<\/p>\n<p><strong>GROUP BY<\/strong>:\u00a0used to create one output row per each group and produces summary values for the selected columns<\/p>\n<p><strong>inner join<\/strong>:\u00a0connects two tables\u00a0on a column with the same data type<\/p>\n<p><strong>INSERT statement<\/strong>:\u00a0adds rows to a table<\/p>\n<p><strong>left outer join<\/strong>:\u00a0specifies that all left outer rows be returned<\/p>\n<p><strong>mathematical function<\/strong>:\u00a0performs operations on numeric data<\/p>\n<p><strong>right outer join<\/strong>: includes all rows from the right table that did not meet the condition specified<\/p>\n<p><strong>SELECT statemen<\/strong>t: used\u00a0to query data in the database<\/p>\n<p><strong>string function<\/strong>:\u00a0performs operations on character strings, binary data or expressions<\/p>\n<p><strong>system function<\/strong>:\u00a0returns a special piece of information from the database<\/p>\n<p><strong>text and image functions<\/strong>:\u00a0performs operations on text and image data<\/p>\n<p><strong>UPDATE\u00a0statement:<\/strong>\u00a0changes data in existing rows either by adding new data or modifying existing data<\/p>\n<p><strong>wildcard<\/strong>:\u00a0 allows the user to match fields that contain certain letters.<\/p>\n<\/div>\n<\/div>\n<div class=\"textbox textbox--exercises\">\n<header class=\"textbox__header\">\n<p class=\"textbox__title\">Exercises<\/p>\n<\/header>\n<div class=\"textbox__content\">\n<p style=\"color: #1f1f1d;\">For questions 1 to 18 use\u00a0the PUBS sample database created by Microsoft. To download the script to generate this database please go to the following site:\u00a0<a style=\"color: #870d0d;\" href=\"http:\/\/www.microsoft.com\/en-ca\/download\/details.aspx?id=23654\">http:\/\/www.microsoft.com\/en-ca\/download\/details.aspx?id=23654<\/a>.<\/p>\n<ol>\n<li>Display a list of publication dates and titles (books) that were published in 2011.<\/li>\n<li>Display a list of titles that have been categorized as either traditional or modern cooking. Use the Books table.<\/li>\n<li>Display all authors whose first names are five letters long.<\/li>\n<li>Display from the Books table: type, price, pub_id, title about the books put out by each publisher. Rename the column type with \u201dBook Category.\u201d Sort by type (descending) and then price (ascending).<\/li>\n<li>Display title_id, pubdate and pubdate plus three\u00a0days, using the Books table.<\/li>\n<li>Using the datediff and getdate function determine how much time has elapsed in months since the books in the Books table were published.<\/li>\n<li>List the title IDs and quantity of all books that sold more than 30 copies.<\/li>\n<li>Display a list of all last names of the authors who live in Ontario (ON) and the cities where they live.<\/li>\n<li>Display all rows that contain a 60 in the payterms field. Use the Sales table.<\/li>\n<li>Display all authors whose first names are five letters long , end in O or A, and start with M or P.<\/li>\n<li>Display all titles that cost more than $30 and either begin with T or have a publisher ID of \u00a00877.<\/li>\n<li>Display from the Employees table the first name (fname), last name (lname), employe ID(emp_id) and job level (job_lvl) columns for those employees with a job level greater than 200; and rename the column headings to:\u00a0 \u201cFirst Name,\u201d \u201cLast Name,\u201d \u201cIDENTIFICATION#\u201d and \u201cJob Level.\u201d<\/li>\n<li>Display the royalty, royalty plus 50% as \u201croyalty plus 50\u201d and title_id. Use the Roysched table.<\/li>\n<li>Using the STUFF function create a string \u201c12xxxx567\u201d from the string \u201c1234567.\u201d<\/li>\n<li>Display the first 40 characters of each title, along with the average monthly sales for that title to date (ytd_sales\/12). Use the Title table.<\/li>\n<li>Show how many books have assigned prices.<\/li>\n<li>Display a list of cookbooks with the average cost for all of the books of each type. Use the GROUP BY.<\/li>\n<\/ol>\n<\/div>\n<\/div>\n<div class=\"textbox textbox--exercises\">\n<header class=\"textbox__header\">\n<p class=\"textbox__title\">Advanced Questions (Union, Intersect, and Minus)<\/p>\n<\/header>\n<div class=\"textbox__content\">\n<ol>\n<li>The relational set operators UNION, INTERSECT and MINUS work properly only if the relations are union-compatible. What does\u00a0union-compatible\u00a0mean, and how would you check for this condition?<\/li>\n<li>What is the difference between UNION and UNION ALL? Write the syntax for each.<\/li>\n<li>Suppose that you have two tables, Employees and Employees_1. The Employees table contains the records for three employees: Alice Cordoza, John Cretchakov, and Anne McDonald. The Employees_1 table contains the records for employees: John Cretchakov and Mary Chen. Given that information, what is the query output for the UNION query? List the query output.<\/li>\n<li>Given the employee information in question 3, what is the query output for the UNION ALL query? List the query output.<\/li>\n<li>Given the employee information in question 3, what is the query output for the INTERSECT query? List the query output.<\/li>\n<li>Given the employee information in question 3, what is the query output for the EXCEPT query? List the query output.<\/li>\n<li>What is a cross join? Give an example of its syntax.<\/li>\n<li>Explain these three join types:\n<ol>\n<li>left outer join<\/li>\n<li>right outer join<\/li>\n<li>full outer join<\/li>\n<\/ol>\n<\/li>\n<li>What is a subquery, and what are its basic characteristics?<\/li>\n<li>What is a correlated subquery? Give an example.<\/li>\n<li>Suppose that a Product table contains two attributes, PROD_CODE and VEND_CODE. The values for the PROD_CODE are:\u00a0ABC, DEF, GHI and JKL. These are matched by the following values for the VEND_CODE: \u00a0125, 124, 124 and 123, respectively (e.g., PROD_CODE value\u00a0ABC corresponds to\u00a0VEND_CODE\u00a0value\u00a0125). The Vendor table contains a single attribute, VEND_CODE, with values 123, 124, 125 and 126. (The VEND_CODE attribute in the Product table is a foreign key to the VEND_CODE in the Vendor table.)<\/li>\n<li>Given the information in question 11, what would be the query output for the following? Show values.\n<ol>\n<li>A UNION query based on these two tables<\/li>\n<li>A UNION ALL query based on these two tables<\/li>\n<li>An INTERSECT query based on these two tables<\/li>\n<li>A MINUS query based on these two tables<\/li>\n<\/ol>\n<\/li>\n<\/ol>\n<\/div>\n<\/div>\n<div class=\"textbox textbox--exercises\">\n<header class=\"textbox__header\">\n<p class=\"textbox__title\">Advanced Questions (Using Joins)<\/p>\n<\/header>\n<div class=\"textbox__content\">\n<ol>\n<li>Display a list of all titles and sales numbers in the Books and Sales tables, including titles that have no sales. Use a join.<\/li>\n<li>Display a list of authors\u2019 last names and all associated titles that each\u00a0author has published sorted by the author\u2019s last name. Use a join.\u00a0 Save it as a view named: Published Authors.<\/li>\n<li>Using a subquery, display all the authors (show last and first name, postal code) who receive a royalty of 100% and live in Alberta. Save it as a view titled: AuthorsView. When creating the view, rename the author\u2019s last name and first name as \u2018Last Name\u2019 and \u2018First Name\u2019.<\/li>\n<li>Display the stores that did not sell the title\u00a0<em>Is Anger the Enemy?<\/em><\/li>\n<li>Display a list of store names for sales after 2013 (Order Date is greater than 2013). \u00a0Display store name and order date.<\/li>\n<li>Display a list of titles for books sold in store name \u201cNews &amp; Brews.\u201d \u00a0Display store name, titles and order dates.<\/li>\n<li>List total sales (qty) by title. Display total quantity and title columns.<\/li>\n<li>List total sales (qty) by type. Display total quantity and type columns.<\/li>\n<li>List total sales (qty*price) by type. Display total dollar\u00a0value and type columns.<\/li>\n<li>Calculate the total number of types of books by publisher. Show publisher name and total count of types of books for each publisher.<\/li>\n<li>Show publisher names that do not have any type of book.\u00a0 Display publisher name only.<\/li>\n<\/ol>\n<\/div>\n<\/div>\n","protected":false},"author":5,"menu_order":16,"template":"","meta":{"pb_show_title":"on","pb_short_title":"","pb_subtitle":"","pb_authors":["adrienne-watt-nelson-eng"],"pb_section_license":""},"chapter-type":[],"contributor":[48],"license":[],"class_list":["post-289","chapter","type-chapter","status-publish","hentry","contributor-adrienne-watt-nelson-eng"],"part":3,"_links":{"self":[{"href":"https:\/\/opentextbc.ca\/dbdesign01\/wp-json\/pressbooks\/v2\/chapters\/289","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/opentextbc.ca\/dbdesign01\/wp-json\/pressbooks\/v2\/chapters"}],"about":[{"href":"https:\/\/opentextbc.ca\/dbdesign01\/wp-json\/wp\/v2\/types\/chapter"}],"author":[{"embeddable":true,"href":"https:\/\/opentextbc.ca\/dbdesign01\/wp-json\/wp\/v2\/users\/5"}],"version-history":[{"count":28,"href":"https:\/\/opentextbc.ca\/dbdesign01\/wp-json\/pressbooks\/v2\/chapters\/289\/revisions"}],"predecessor-version":[{"id":1155,"href":"https:\/\/opentextbc.ca\/dbdesign01\/wp-json\/pressbooks\/v2\/chapters\/289\/revisions\/1155"}],"part":[{"href":"https:\/\/opentextbc.ca\/dbdesign01\/wp-json\/pressbooks\/v2\/parts\/3"}],"metadata":[{"href":"https:\/\/opentextbc.ca\/dbdesign01\/wp-json\/pressbooks\/v2\/chapters\/289\/metadata\/"}],"wp:attachment":[{"href":"https:\/\/opentextbc.ca\/dbdesign01\/wp-json\/wp\/v2\/media?parent=289"}],"wp:term":[{"taxonomy":"chapter-type","embeddable":true,"href":"https:\/\/opentextbc.ca\/dbdesign01\/wp-json\/pressbooks\/v2\/chapter-type?post=289"},{"taxonomy":"contributor","embeddable":true,"href":"https:\/\/opentextbc.ca\/dbdesign01\/wp-json\/wp\/v2\/contributor?post=289"},{"taxonomy":"license","embeddable":true,"href":"https:\/\/opentextbc.ca\/dbdesign01\/wp-json\/wp\/v2\/license?post=289"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}