老问题 Column 'xx' does not belong to table Table.

有时有点2 2012-11-06 02:18:50
查询数据方法:
表中的字段是存在的 只是偶尔会出现这种问题
网上找了资料 有的说是conn 关闭问题 但具体 怎么修改 还请高人 帮帮忙
 
public DataSet CommandDataSet(string cmdText, params SqlParameter[] cmdParms)
{
SqlConnection conn = new SqlConnection(DefaultConn);
SqlCommand cmd = new SqlCommand(cmdText, conn);
cmd.CommandType = CommandType.StoredProcedure;
if (cmdParms != null)
{
foreach (SqlParameter parm in cmdParms)
{
cmd.Parameters.Add(parm);
}
}
cmd.Connection.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
conn.Close();
return ds;
}
...全文
2252 16 打赏 收藏 转发到动态 举报
写回复
用AI写文章
16 条回复
切换为时间正序
请发表友善的回复…
发表回复
yjh754429778 2015-05-07
  • 打赏
  • 举报
回复 1
回答找不到字段 检查SQL的之类的都是SB 根本就没有睁大双眼看清楚问题,这个原因是因为SQLconnection大批量请求时 数据库时断时连造成的
shishui508 2014-12-26
  • 打赏
  • 举报
回复
可能是连接未关闭,,使用sqlhelper类试试
黄色不倒翁 2014-12-02
  • 打赏
  • 举报
回复
我也碰到这个问题了。偶尔出现,感觉像是服务器的问题!
看看看灰机 2012-11-06
  • 打赏
  • 举报
回复
把要找的列名都写上。。再测
XBodhi. 2012-11-06
  • 打赏
  • 举报
回复
对于楼主这种问题,我真不愿意回答了, 1.列名不存在,无非是你的 SELECT出的字段没有那个列名。 2.DataReader 的时候列名写错。 3.DataTable 的时候名字写错。 4.DataSet 的TableIndex写错
lhx527099095 2012-11-06
  • 打赏
  • 举报
回复
我觉得是你数据库里面出来的字段和你前台页面上绑定的字段有不一致的情况 请仔细检查下你绑定的问题 数据这边貌似没什么问题哦
有时有点2 2012-11-06
  • 打赏
  • 举报
回复
如果是字段 查找不到 我就不在这发帖了 暂时排除 字段找不到这种情况 谢谢
  • 打赏
  • 举报
回复
你要确保程序中你用到的表字段(比如绑定)都存在于 你判断后查询执行语句 【筛选出来的字段】,无论是进入了哪种判断,你说偶尔的情况,估计应该是偶尔进入了某种判断,而这种判断所选出的字段可能少于你所需的字段.
有时有点2 2012-11-06
  • 打赏
  • 举报
回复
这个查询没有相关的输入内容 参数是在页面里自己传的 判断什么都有 本地都是好好的 发布之后就会出现
手可摘星辰 2012-11-06
  • 打赏
  • 举报
回复
引用 6 楼 fei80317 的回复:
引用 5 楼 touzilk 的回复:tblorders_200809_backup 和tblorders 的字段是一致的吗?不会说偶尔出现这问题 tblorders_200809_backup 是一张表名
这两个不是同一个表吧(字段一致否),如果不是那你看前台绑定的部分,要是了我也不知道了
有时有点2 2012-11-06
  • 打赏
  • 举报
回复
引用 5 楼 touzilk 的回复:
tblorders_200809_backup 和tblorders 的字段是一致的吗?不会说偶尔出现这问题
tblorders_200809_backup 是一张表名
手可摘星辰 2012-11-06
  • 打赏
  • 举报
回复
tblorders_200809_backup 和tblorders 的字段是一致的吗?不会说偶尔出现这问题
misswangjinfeng 2012-11-06
  • 打赏
  • 举报
回复
你debug 捕捉一下,什么情况会出这个问题~ 是不是你页面输入了什么特殊字
有时有点2 2012-11-06
  • 打赏
  • 举报
回复
SQL 是没问题的 这个情况只是偶尔出现 大部分是正常的 下面是执行的存储过程

BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	if(@Flag=1)
		select * from tblorders_200809_backup where orderno=@OrderNo
	else
		select * from tblorders where orderno=@OrderNo
END
白云任去留 2012-11-06
  • 打赏
  • 举报
回复
检查你的SQL语句拼装!
快溜 2012-11-06
  • 打赏
  • 举报
回复
你的cmdText问题
Contents Overview 1 Lesson 1: Index Concepts 3 Lesson 2: Concepts – Statistics 29 Lesson 3: Concepts – Query Optimization 37 Lesson 4: Information Collection and Analysis 61 Lesson 5: Formulating and Implementing Resolution 75 Module 6: Troubleshooting Query Performance Overview At the end of this module, you will be able to:  Describe the different types of indexes and how indexes can be used to improve performance.  Describe what statistics are used for and how they can help in optimizing query performance.  Describe how queries are optimized.  Analyze the information collected from various tools.  Formulate resolution to query performance problems. Lesson 1: Index Concepts Indexes are the most useful tool for improving query performance. Without a useful index, Microsoft® SQL Server™ must search every row on every page in table to find the rows to return. With a multitable query, SQL Server must sometimes search a table multiple times so each page is scanned much more than once. Having useful indexes speeds up finding individual rows in a table, as well as finding the matching rows needed to join two tables. What You Will Learn After completing this lesson, you will be able to:  Understand the structure of SQL Server indexes.  Describe how SQL Server uses indexes to find rows.  Describe how fillfactor can impact the performance of data retrieval and insertion.  Describe the different types of fragmentation that can occur within an index. Recommended Reading  Chapter 8: “Indexes”, Inside SQL Server 2000 by Kalen Delaney  Chapter 11: “Batches, Stored Procedures and Functions”, Inside SQL Server 2000 by Kalen Delaney Finding Rows without Indexes With No Indexes, A Table Must Be Scanned SQL Server keeps track of which pages belong to a table or index by using IAM pages. If there is no clustered index, there is a sysindexes row for the table with an indid value of 0, and that row will keep track of the address of the first IAM for the table. The IAM is a giant bitmap, and every 1 bit indicates that the corresponding extent belongs to the table. The IAM allows SQL Server to do efficient prefetching of the table’s extents, but every row still must be examined. General Index Structure All SQL Server Indexes Are Organized As B-Trees Indexes in SQL Server store their information using standard B-trees. A B-tree provides fast access to data by searching on a key value of the index. B-trees cluster records with similar keys. The B stands for balanced, and balancing the tree is a core feature of a B-tree’s usefulness. The trees are managed, and branches are grafted as necessary, so that navigating down the tree to find a value and locate a specific record takes only a few page accesses. Because the trees are balanced, finding any record requires about the same amount of resources, and retrieval speed is consistent because the index has the same depth throughout. Clustered and Nonclustered Indexes Both Index Types Have Many Common Features An index consists of a tree with a root from which the navigation begins, possible intermediate index levels, and bottom-level leaf pages. You use the index to find the correct leaf page. The number of levels in an index will vary depending on the number of rows in the table and the size of the key column or columns for the index. If you create an index using a large key, fewer entries will fit on a page, so more pages (and possibly more levels) will be needed for the index. On a qualified select, update, or delete, the correct leaf page will be the lowest page of the tree in which one or more rows with the specified key or keys reside. A qualified operation is one that affects only specific rows that satisfy the conditions of a WHERE clause, as opposed to accessing the whole table. An index can have multiple node levels An index page above the leaf is called a node page. Each index row in node pages contains an index key (or set of keys for a composite index) and a pointer to a page at the next level for which the first key value is the same as the key value in the current index row. Leaf Level contains all key values In any index, whether clustered or nonclustered, the leaf level contains every key value, in key sequence. In SQL Server 2000, the sequence can be either ascending or descending. The sysindexes table contains all sizing, location and distribution information Any information about size of indexes or tables is stored in sysindexes. The only source of any storage location information is the sysindexes table, which keeps track of the address of the root page for every index, and the first IAM page for the index or table. There is also a column for the first page of the table, but this is not guaranteed to be reliable. SQL Server can find all pages belonging to an index or table by examining the IAM pages. Sysindexes contains a pointer to the first IAM page, and each IAM page contains a pointer to the next one. The Difference between Clustered and Nonclustered Indexes The main difference between the two types of indexes is how much information is stored at the leaf. The leaf levels of both types of indexes contain all the key values in order, but they also contain other information. Clustered Indexes The Leaf Level of a Clustered Index Is the Data The leaf level of a clustered index contains the data pages, not just the index keys. Another way to say this is that the data itself is part of the clustered index. A clustered index keeps the data in a table ordered around the key. The data pages in the table are kept in a doubly linked list called the page chain. The order of pages in the page chain, and the order of rows on the data pages, is the order of the index key or keys. Deciding which key to cluster on is an important performance consideration. When the index is traversed to the leaf level, the data itself has been retrieved, not simply pointed to. Uniqueness Is Maintained In Key Values In SQL Server 2000, all clustered indexes are unique. If you build a clustered index without specifying the unique keyword, SQL Server forces uniqueness by adding a uniqueifier to the rows when necessary. This uniqueifier is a 4-byte value added as an additional sort key to only the rows that have duplicates of their primary sort key. You can see this extra value if you use DBCC PAGE to look at the actual index rows the section on indexes internal. . Finding Rows in a Clustered Index The Leaf Level of a Clustered Index Contains the Data A clustered index is like a telephone directory in which all of the rows for customers with the same last name are clustered together in the same part of the book. Just as the organization of a telephone directory makes it easy for a person to search, SQL Server quickly searches a table with a clustered index. Because a clustered index determines the sequence in which rows are stored in a table, there can only be one clustered index for a table at a time. Performance Considerations Keeping your clustered key value small increases the number of index rows that can be placed on an index page and decreases the number of levels that must be traversed. This minimizes I/O. As we’ll see, the clustered key is duplicated in every nonclustered index row, so keeping your clustered key small will allow you to have more index fit per page in all your indexes. Note The query corresponding to the slide is: SELECT lastname, firstname FROM member WHERE lastname = ‘Ota’ Nonclustered Indexes The Leaf Level of a Nonclustered Index Contains a Bookmark A nonclustered index is like the index of a textbook. The data is stored in one place and the index is stored in another. Pointers indicate the storage location of the indexed items in the underlying table. In a nonclustered index, the leaf level contains each index key, plus a bookmark that tells SQL Server where to find the data row corresponding to the key in the index. A bookmark can take one of two forms:  If the table has a clustered index, the bookmark is the clustered index key for the corresponding data row. This clustered key can be multiple column if the clustered index is composite, or is defined to be non-unique.  If the table is a heap (in other words, it has no clustered index), the bookmark is a RID, which is an actual row locator in the form File#:Page#:Slot#. Finding Rows with a NC Index on a Heap Nonclustered Indexes Are Very Efficient When Searching For A Single Row After the nonclustered key at the leaf level of the index is found, only one more page access is needed to find the data row. Searching for a single row using a nonclustered index is almost as efficient as searching for a single row in a clustered index. However, if we are searching for multiple rows, such as duplicate values, or keys in a range, anything more than a small number of rows will make the nonclustered index search very inefficient. Note The query corresponding to the slide is: SELECT lastname, firstname FROM member WHERE lastname BETWEEN ‘Master’ AND ‘Rudd’ Finding Rows with a NC Index on a Clustered Table A Clustered Key Is Used as the Bookmark for All Nonclustered Indexes If the table has a clustered index, all columns of the clustered key will be duplicated in the nonclustered index leaf rows, unless there is overlap between the clustered and nonclustered key. For example, if the clustered index is on (lastname, firstname) and a nonclustered index is on firstname, the firstname value will not be duplicated in the nonclustered index leaf rows. Note The query corresponding to the slide is: SELECT lastname, firstname, phone FROM member WHERE firstname = ‘Mike’ Covering Indexes A Covering Index Provides the Fastest Data Access A covering index contains ALL the fields accessed in the query. Normally, only the columns in the WHERE clause are helpful in determining useful indexes, but for a covering index, all columns must be included. If all columns needed for the query are in the index, SQL Server never needs to access the data pages. If even one column in the query is not part of the index, the data rows must be accessed. The leaf level of an index is the only level that contains every key value, or set of key values. For a clustered index, the leaf level is the data itself, so in reality, a clustered index ALWAYS covers any query. Nevertheless, for most of our optimization discussions, we only consider nonclustered indexes. Scanning the leaf level of a nonclustered index is almost always faster than scanning a clustered index, so covering indexes are particular valuable when we need ALL the key values of a particular nonclustered index. Example: Select an aggregate value of a column with a clustered index. Suppose we have a nonclustered index on price, this query is covered: SELECT avg(price) from titles Since the clustered key is included in every nonclustered index row, the clustered key can be included in the covering. Suppose you have a nonclustered index on price and a clustered index on title_id; then this query is covered: SELECT title_id, price FROM titles WHERE price between 10 and 20 Performance Considerations In general, you do want to keep your indexes narrow. However, if you have a critical query that just is not giving you satisfactory performance no matter what you do, you should consider creating an index to cover it, or adding one or two extra columns to an existing index, so that the query will be covered. The leaf level of a nonclustered index is like a ‘mini’ clustered index, so you can have most of the benefits of clustering, even if there already is another clustered index on the table. The tradeoff to adding more, wider indexes for covering queries are the added disk space, and more overhead for updating those columns that are now part of the index. Bug In general, SQL Server will detect when a query is covered, and detect the possible covering indexes. However, in some cases, you must force SQL Server to use a covering index by including a WHERE clause, even if the WHERE clause will return ALL the rows in the table. This is SHILOH bug #352079 Steps to reproduce 1. Make copy of orders table from Northwind: USE Northwind CREATE TABLE [NewOrders] ( [OrderID] [int] NOT NULL , [CustomerID] [nchar] (5) NULL , [EmployeeID] [int] NULL , [OrderDate] [datetime] NULL , [RequiredDate] [datetime] NULL , [ShippedDate] [datetime] NULL , [ShipVia] [int] NULL , [Freight] [money] NULL , [ShipName] [nvarchar] (40) NULL, [ShipAddress] [nvarchar] (60) , [ShipCity] [nvarchar] (15) NULL, [ShipRegion] [nvarchar] (15) NULL, [ShipPostalCode] [nvarchar] (10) NULL, [ShipCountry] [nvarchar] (15) NULL ) INSERT into NewOrders SELECT * FROM Orders 2. Build nc index on OrderDate: create index dateindex on neworders(orderdate) 3. Test Query by looking at query plan: select orderdate from NewOrders The index is being scanned, as expected. 4. Build an index on orderId: create index orderid_index on neworders(orderID) 5. Test Query by looking at query plan: select orderdate from NewOrders Now the TABLE is being scanned, instead of the original index! Index Intersection Multiple Indexes Can Be Used On A Single Table In versions prior to SQL Server 7, only one index could be used for any table to process any single query. The only exception was a query involving an OR. In current SQL Server versions, multiple nonclustered indexes can each be accessed, retrieving a set of keys with bookmarks, and then the result sets can be joined on the common bookmarks. The optimizer weighs the cost of performing the unindexed join on the intermediate result sets, with the cost of only using one index, and then scanning the entire result set from that single index. Fillfactor and Performance Creating an Index with a Low Fillfactor Delays Page Splits when Inserting DBCC SHOWCONTIG will show you a low value for “Avg. Page Density” when a low fillfactor has been specified. This is good for inserts and updates, because it will delay the need to split pages to make room for new rows. It can be bad for scans, because fewer rows will be on each page, and more pages must be read to access the same amount of data. However, this cost will be minimal if the scan density value is good. Index Reorganization DBCC SHOWCONTIG Provides Lots of Information Here’s some sample output from running a basic DBCC SHOWCONTIG on the order details table in the Northwind database: DBCC SHOWCONTIG scanning 'Order Details' table... Table: 'Order Details' (325576198); index ID: 1, database ID:6 TABLE level scan performed. - Pages Scanned................................: 9 - Extents Scanned..............................: 6 - Extent Switches..............................: 5 - Avg. Pages per Extent........................: 1.5 - Scan Density [Best Count:Actual Count].......: 33.33% [2:6] - Logical Scan Fragmentation ..................: 0.00% - Extent Scan Fragmentation ...................: 16.67% - Avg. Bytes Free per Page.....................: 673.2 - Avg. Page Density (full).....................: 91.68% By default, DBCC SHOWCONTIG scans the page chain at the leaf level of the specified index and keeps track of the following values:  Average number of bytes free on each page (Avg. Bytes Free per Page)  Number of pages accessed (Pages scanned)  Number of extents accessed (Extents scanned)  Number of times a page had a lower page number than the previous page in the scan (This value for Out of order pages is not displayed, but is used for additional computations.)  Number of times a page in the scan was on a different extent than the previous page in the scan (Extent switches) SQL Server also keeps track of all the extents that have been accessed, and then it determines how many gaps are in the used extents. An extent is identified by the page number of its first page. So, if extents 8, 16, 24, 32, and 40 make up an index, there are no gaps. If the extents are 8, 16, 24, and 40, there is one gap. The value in DBCC SHOWCONTIG’s output called Extent Scan Fragmentation is computed by dividing the number of gaps by the number of extents, so in this example the Extent Scan Fragmentation is ¼, or 25 percent. A table using extents 8, 24, 40, and 56 has three gaps, and its Extent Scan Fragmentation is ¾, or 75 percent. The maximum number of gaps is the number of extents - 1, so Extent Scan Fragmentation can never be 100 percent. The value in DBCC SHOWCONTIG’s output called Logical Scan Fragmentation is computed by dividing the number of Out of order pages by the number of pages in the table. This value is meaningless in a heap. You can use either the Extent Scan Fragmentation value or the Logical Scan Fragmentation value to determine the general level of fragmentation in a table. The lower the value, the less fragmentation there is. Alternatively, you can use the value called Scan Density, which is computed by dividing the optimum number of extent switches by the actual number of extent switches. A high value means that there is little fragmentation. Scan Density is not valid if the table spans multiple files; therefore, it is less useful than the other values. SQL Server 2000 allows online defragmentation You can choose from several methods for removing fragmentation from an index. You could rebuild the index and have SQL Server allocate all new contiguous pages for you. To rebuild the index, you can use a simple DROP INDEX and CREATE INDEX combination, but in many cases using these commands is less than optimal. In particular, if the index is supporting a constraint, you cannot use the DROP INDEX command. Alternatively, you can use DBCC DBREINDEX, which can rebuild all the indexes on a table in one operation, or you can use the drop_existing clause along with CREATE INDEX. The drawback of these methods is that the table is unavailable while SQL Server is rebuilding the index. When you are rebuilding only nonclustered indexes, SQL Server takes a shared lock on the table, which means that users cannot make modifications, but other processes can SELECT from the table. Of course, those SELECT queries cannot take advantage of the index you are rebuilding, so they might not perform as well as they would otherwise. If you are rebuilding a clustered index, SQL Server takes an exclusive lock and does not allow access to the table, so your data is temporarily unavailable. SQL Server 2000 lets you defragment an index without completely rebuilding it. DBCC INDEXDEFRAG reorders the leaf-level pages into physical order as well as logical order, but using only the pages that are already allocated to the leaf level. This command does an in-place ordering, which is similar to a sorting technique called bubble sort (you might be familiar with this technique if you've studied and compared various sorting algorithms). In-place ordering can reduce logical fragmentation to 2 percent or less, making an ordered scan through the leaf level much faster. DBCC INDEXDEFRAG also compacts the pages of an index, based on the original fillfactor. The pages will not always end up with the original fillfactor, but SQL Server uses that value as a goal. The defragmentation process attempts to leave at least enough space for one average-size row on each page. In addition, if SQL Server cannot obtain a lock on a page during the compaction phase of DBCC INDEXDEFRAG, it skips the page and does not return to it. Any empty pages created as a result of compaction are removed. The algorithm SQL Server 2000 uses for DBCC INDEXDEFRAG finds the next physical page in a file belonging to the index's leaf level and the next logical page in the leaf level to swap it with. To find the next physical page, the algorithm scans the IAM pages belonging to that index. In a database spanning multiple files, in which a table or index has pages on more than one file, SQL Server handles pages on different files separately. SQL Server finds the next logical page by scanning the index's leaf level. After each page move, SQL Server drops all locks and saves the last key on the last page it moved. The next iteration of the algorithm uses the last key to find the next logical page. This process lets other users update the table and index while DBCC INDEXDEFRAG is running. Let us look at an example in which an index's leaf level consists of the following pages in the following logical order: 47 22 83 32 12 90 64 The first key is on page 47, and the last key is on page 64. SQL Server would have to scan the pages in this order to retrieve the data in sorted order. As its first step, DBCC INDEXDEFRAG would find the first physical page, 12, and the first logical page, 47. It would then swap the pages, using a temporary buffer as a holding area. After the first swap, the leaf level would look like this: 12 22 83 32 47 90 64 The next physical page is 22, which is also the next logical page, so no work would be necessary. DBCC INDEXDEFRAG would then swap the next physical page, 32, with the next logical page, 83: 12 22 32 83 47 90 64 After the next swap of 47 with 83, the leaf level would look like this: 12 22 32 47 83 90 64 Then, the defragmentation process would swap 64 with 83: 12 22 32 47 64 90 83 and 83 with 90: 12 22 32 47 64 83 90 At the end of the DBCC INDEXDEFRAG operation, the pages in the table or index are not contiguous, but their logical order matches their physical order. Now, if the pages were accessed from disk in sorted order, the head would need to move in only one direction. Keep in mind that DBCC INDEXDEFRAG uses only pages that are already part of the index's leaf level; it allocates no new pages. In addition, defragmenting a large table can take quite a while, and you will get a report every 5 minutes about the estimated percentage completed. However, except for the locks on the pages being switched, this command needs no additional locks. All the table's other pages and indexes are fully available for your applications to use during the defragmentation process. If you must completely rebuild an index because you want a new fillfactor, or if simple defragmentation is not enough because you want to remove all fragmentation from your indexes, another SQL Server 2000 improvement makes index rebuilding less of an imposition on the rest of the system. SQL Server 2000 lets you create an index in parallel—that is, using multiple processors—which drastically reduces the time necessary to perform the rebuild. The algorithm SQL Server 2000 uses, allows near-linear scaling with the number of processors you use for the rebuild, so four processors will take only one-fourth the time that one processor requires to rebuild an index. System availability increases because the length of time that a table is unavailable decreases. Note that only the SQL Server 2000 Enterprise Edition supports parallel index creation. Indexes on Views and Computed Columns Building an Index Gives the Data Physical Existence Normally, views are only logical and the rows comprising the view’s data are not generated until the view is accessed. The values for computed columns are typically not stored anywhere in the database; only the definition for the computation is stored and the computation is redone every time a computed column is accessed. The first index on a view must be a clustered index, so that the leaf level can hold all the actual rows that make up the view. Once that clustered index has been build, and the view’s data is now physical, additional (nonclustered) indexes can be built. An index on a computed column can be nonclustered, because all we need to store is the index key values. Common Prerequisites for Indexed Views and Indexes on Computed Columns In order for SQL Server to create use these special indexes, you must have the seven SET options correctly specified: ARITHABORT, CONCAT_NULL_YIELDS_NULL, QUOTED_IDENTIFIER, ANSI_NULLS, ANSI_PADDING, ANSI_WARNING must be all ON NUMERIC_ROUNDABORT must be OFF Only deterministic expressions can be used in the definition of Indexed Views or indexes on Computed Columns. See the BOL for the list of deterministic functions and expressions. Property functions are available to check if a column or view meets the requirements and is indexable. SELECT OBJECTPROPERTY (Object_id, ‘IsIndexable’) SELECT COLUMNPROPERTY (Object_id, column_name , ‘IsIndexable’ ) Schema Binding Guarantees That Object Definition Won’t Change A view can only be indexed if it has been built with schema binding. The SQL Server Optimizer Determines If the Indexed View Can Be Used The query must request a subset of the data contained in the view. The ability of the optimizer to use the indexed view even if the view is not directly referenced is available only in SQL Server 2000 Enterprise Edition. In Standard edition, you can create indexed views, and you can select directly from them, but the optimizer will not choose to use them if they are not directly referenced. Examples of Indexed Views: The best candidates for improvement by indexed views are queries performing aggregations and joins. We will explain how the useful indexed views may be created for these two major groups of queries. The considerations are valid also for queries and indexed views using both joins and aggregations. -- Example: USE Northwind -- Identify 5 products with overall biggest discount total. -- This may be expressed for example by two different queries: -- Q1. select TOP 5 ProductID, SUM(UnitPrice*Quantity)- SUM(UnitPrice*Quantity*(1.00-Discount)) Rebate from [order details] group by ProductID order by Rebate desc --Q2. select TOP 5 ProductID, SUM(UnitPrice*Quantity*Discount) Rebate from [order details] group by ProductID order by Rebate desc --The following indexed view will be used to execute Q1. create view Vdiscount1 with schemabinding as select SUM(UnitPrice*Quantity) SumPrice, SUM(UnitPrice*Quantity*(1.00-Discount)) SumDiscountPrice, COUNT_BIG(*) Count, ProductID from dbo.[order details] group By ProductID create unique clustered index VDiscountInd on Vdiscount1 (ProductID) However, it will not be used by the Q2 because the indexed view does not contain the SUM(UnitPrice*Quantity*Discount) aggregate. We can construct another indexed view create view Vdiscount2 with schemabinding as select SUM(UnitPrice*Quantity) SumPrice, SUM(UnitPrice*Quantity*(1.00-Discount)) SumDiscountPrice, SUM(UnitPrice*Quantity*Discount) SumDiscoutPrice2, COUNT_BIG(*) Count, ProductID from dbo.[order details] group By ProductID create unique clustered index VDiscountInd on Vdiscount2 (ProductID) This view may be used by both Q1 and Q2. Observe that the indexed view Vdiscount2 will have the same number of rows and only one more column compared to Vdiscount1, and it may be used by more queries. In general, try to design indexed views that may be used by more queries. The following query asking for the order with the largest total discount -- Q3. select TOP 3 OrderID, SUM(UnitPrice*Quantity*Discount) OrderRebate from dbo.[order details] group By OrderID Q3 can use neither of the Vdiscount views because the column OrderID is not included in the view definition. To address this variation of the discount analysis query we may create a different indexed view, similar to the query itself. An attempt to generalize the previous indexed view Vdiscount2 so that all three queries Q1, Q2, and Q3 can take advantage of a single indexed view would require a view with both OrderID and ProductID as grouping columns. Because the OrderID, ProductID combination is unique in the original order details table the resulting view would have as many rows as the original table and we would see no savings in using such view compared to using the original table. Consider the size of the resulting indexed view. In the case of pure aggregation, the indexed view may provide no significant performance gains if its size is close to the size of the original table. Complex aggregates (STDEV, VARIANCE, AVG) cannot participate in the index view definition. However, SQL Server may use an indexed view to execute a query containing AVG aggregate. Query containing STDEV or VARIANCE cannot use indexed view to pre-compute these values. The next example shows a query producing the average price for a particular product -- Q4. select ProductName, od.ProductID, AVG(od.UnitPrice*(1.00-Discount)) AvgPrice, SUM(od.Quantity) Units from [order details] od, Products p where od.ProductID=p.ProductID group by ProductName, od.ProductID This is an example of indexed view that will be considered by the SQL Server to answer the Q4 create view v3 with schemabinding as select od.ProductID, SUM(od.UnitPrice*(1.00-Discount)) Price, COUNT_BIG(*) Count, SUM(od.Quantity) Units from dbo.[order details] od group by od.ProductID go create UNIQUE CLUSTERED index iv3 on v3 (ProductID) go Observe that the view definition does not contain the table Products. The indexed view does not need to contain all tables used in the query that uses the indexed view. In addition, the following query (same as above Q4 only with one additional search condition) will use the same indexed view. Observe that the added predicate references only columns from tables not present in the v3 view definition. -- Q5. select ProductName, od.ProductID, AVG(od.UnitPrice*(1.00-Discount)) AvgPrice, SUM(od.Quantity) Units from [order details] od, Products p where od.ProductID=p.ProductID and p.ProductName like '%tofu%' group by ProductName, od.ProductID The following query cannot use the indexed view because the added search condition od.UnitPrice>10 contains a column from the table in the view definition and the column is neither grouping column nor the predicate appears in the view definition. -- Q6. select ProductName, od.ProductID, AVG(od.UnitPrice*(1.00-Discount)) AvgPrice, SUM(od.Quantity) Units from [order details] od, Products p where od.ProductID=p.ProductID and od.UnitPrice>10 group by ProductName, od.ProductID To contrast the Q6 case, the following query will use the indexed view v3 since the added predicate is on the grouping column of the view v3. -- Q7. select ProductName, od.ProductID, AVG(od.UnitPrice*(1.00-Discount)) AvgPrice, SUM(od.Quantity) Units from [order details] od, Products p where od.ProductID=p.ProductID and od.ProductID in (1,2,13,41) group by ProductName, od.ProductID -- The previous query Q6 will use the following indexed view V4: create view V4 with schemabinding as select ProductName, od.ProductID, SUM(od.UnitPrice*(1.00-Discount)) AvgPrice, SUM(od.Quantity) Units, COUNT_BIG(*) Count from dbo.[order details] od, dbo.Products p where od.ProductID=p.ProductID and od.UnitPrice>10 group by ProductName, od.ProductID create unique clustered index VDiscountInd on V4 (ProductName, ProductID) The same index on the view V4 will be used also for a query where a join to the table Orders is added, for example -- Q8. select ProductName, od.ProductID, AVG(od.UnitPrice*(1.00-Discount)) AvgPrice, SUM(od.Quantity) Units from dbo.[order details] od, dbo.Products p, dbo.Orders o where od.ProductID=p.ProductID and o.OrderID=od.OrderID and od.UnitPrice>10 group by ProductName, od.ProductID We will show several modifications of the query Q8 and explain why such modifications cannot use the above view V4. -- Q8a. select ProductName, od.ProductID, AVG(od.UnitPrice*(1.00-Discount)) AvgPrice, SUM(od.Quantity) Units from dbo.[order details] od, dbo.Products p, dbo.Orders o where od.ProductID=p.ProductID and o.OrderID=od.OrderID and od.UnitPrice>25 group by ProductName, od.ProductID 8a cannot use the indexed view because of the where clause mismatch. Observe that table Orders does not participate in the indexed view V4 definition. In spite of that, adding a predicate on this table will disallow using the indexed view because the added predicate may eliminate additional rows participating in the aggregates as it is shown in Q8b. -- Q8b. select ProductName, od.ProductID, AVG(od.UnitPrice*(1.00-Discount)) AvgPrice, SUM(od.Quantity) Units from dbo.[order details] od, dbo.Products p, dbo.Orders o where od.ProductID=p.ProductID and o.OrderID=od.OrderID and od.UnitPrice>10 and o.OrderDate>'01/01/1998' group by ProductName, od.ProductID Locking and Indexes In General, You Should Let SQL Server Control the Locking within Indexes The stored procedure sp_indexoption lets you manually control the unit of locking within an index. It also lets you disallow page locks or row locks within an index. Since these options are available only for indexes, there is no way to control the locking within the data pages of a heap. (But remember that if a table has a clustered index, the data pages are part of the index and are affected by the sp_indexoption setting.) The index options are set for each table or index individually. Two options, Allow Rowlocks and AllowPageLocks, are both set to TRUE initially for every table and index. If both of these options are set to FALSE for a table, only full table locks are allowed. As described in Module 4, SQL Server determines at runtime whether to initially lock rows, pages, or the entire table. The locking of rows (or keys) is heavily favored. The type of locking chosen is based on the number of rows and pages to be scanned, the number of rows on a page, the isolation level in effect, the update activity going on, the number of users on the system needing memory for their own purposes, and so on. SAP databases frequently use sp_indexoption to reduce deadlocks Setting vs. Querying In SQL Server 2000, the procedure sp_indexoption should only be used for setting an index option. To query an option, use the INDEXPROPERTY function. Lesson 2: Concepts – Statistics Statistics are the most important tool that the SQL Server query optimizer has to determine the ideal execution plan for a query. Statistics that are out of date or nonexistent seriously jeopardize query performance. SQL Server 2000 computes and stores statistics in a completely different format that all earlier versions of SQL Server. One of the improvements is an increased ability to determine which values are out of the normal range in terms of the number of occurrences. The new statistics maintenance routines are particularly good at determining when a key value has a very unusual skew of data. What You Will Learn After completing this lesson, you will be able to:  Define terms related to statistics collected by SQL Server.  Describe how statistics are maintained by SQL Server.  Discuss the autostats feature of SQL Server.  Describe how statistics are used in query optimization. Recommended Reading  Statistics Used by the Query Optimizer in Microsoft SQL Server 2000 http://msdn.microsoft.com/library/techart/statquery.htm Definitions Cardinality The cardinality means how many unique values exist in the data. Density For each index and set of column statistics, SQL Server keeps track of details about the uniqueness (or density) of the data values encountered, which provides a measure of how selective the index is. A unique index, of course, has the lowest density —by definition, each index entry can point to only one row. A unique index has a density value of 1/number of rows in the table. Density values range from 0 through 1. Highly selective indexes have density values of 0.10 or lower. For example, a unique index on a table with 8345 rows has a density of 0.00012 (1/8345). If a nonunique nonclustered index has a density of 0.2165 on the same table, each index key can be expected to point to about 1807 rows (0.2165 × 8345). This is probably not selective enough to be more efficient than just scanning the table, so this index is probably not useful. Because driving the query from a nonclustered index means that the pages must be retrieved in index order, an estimated 1807 data page accesses (or logical reads) are needed if there is no clustered index on the table and the leaf level of the index contains the actual RID of the desired data row. The only time a data page doesn’t need to be reaccessed is when the occasional coincidence occurs in which two adjacent index entries happen to point to the same data page. In general, you can think of density as the average number of duplicates. We can also talk about the term ‘join density’, which applies to the average number of duplicates in the foreign key column. This would answer the question: in this one-to-many relationship, how many is ‘many’? Selectivity In general selectivity applies to a particular data value referenced in a WHERE clause. High selectivity means that only a small percentage of the rows satisfy the WHERE clause filter, and a low selectivity means that many rows will satisfy the filter. For example, in an employees table, the column employee_id is probably very selective, and the column gender is probably not very selective at all. Statistics Statistics are a histogram consisting of an even sampling of values for a column or for an index key (or the first column of the key for a composite index) based on the current data. The histogram is stored in the statblob field of the sysindexes table, which is of type image. (Remember that image data is actually stored in structures separate from the data row itself. The data row merely contains a pointer to the image data. For simplicity’s sake, we’ll talk about the index statistics as being stored in the image field called statblob.) To fully estimate the usefulness of an index, the optimizer also needs to know the number of pages in the table or index; this information is stored in the dpages column of sysindexes. During the second phase of query optimization, index selection, the query optimizer determines whether an index exists for a columns in your WHERE clause, assesses the index’s usefulness by determining the selectivity of the clause (that is, how many rows will be returned), and estimates the cost of finding the qualifying rows. Statistics for a single column index consist of one histogram and one density value. The multicolumn statistics for one set of columns in a composite index consist of one histogram for the first column in the index and density values for each prefix combination of columns (including the first column alone). The fact that density information is kept for all columns helps the optimizer decide how useful the index is for joins. Suppose, for example, that an index is composed of three key fields. The density on the first column might be 0.50, which is not too useful. However, as you look at more key columns in the index, the number of rows pointed to is fewer than (or in the worst case, the same as) the first column, so the density value goes down. If you are looking at both the first and second columns, the density might be 0.25, which is somewhat better. Moreover, if you examine three columns, the density might be 0.03, which is highly selective. It does not make sense to refer to the density of only the second column. The lead column density is always needed. Statistics Maintenance Statistics Information Tracks the Distribution of Key Values SQL Server statistics is basically a histogram that contains up to 200 values of a given key column. In addition to the histogram, the statblob field contains the following information:  The time of the last statistics collection  The number of rows used to produce the histogram and density information  The average key length  Densities for other combinations of columns In the statblob column, up to 200 sample values are stored; the range of key values between each sample value is called a step. The sample value is the endpoint of the range. Three values are stored along with each step: a value called EQ_ROWS, which is the number of rows that have a value equal to that sample value; a value called RANGE_ROWS, which specifies how many other values are inside the range (between two adjacent sample values); and the number of distinct values, or RANGE_DENSITY of the range. DBCC SHOW_STATISTICS The DBCC SHOW_STATISTICS output shows us the first two of these three values, but not the range density. The RANGE_DENSITY is instead used to compute two additional values:  DISTINCT_RANGE_ROWS—the number of distinct rows inside this range (not counting the RANGE_HI_KEY value itself. This is computed as 1/RANGE_DENSITY.  AVG_RANGE_ROWS—the average number of rows per distinct value, computed as RANGE_DENSITY * RANGE_ROWS. In addition to statistics on indexes, SQL Server can also keep track of statistics on columns with no indexes. Knowing the density, or the likelihood of a particular value occurring, can help the optimizer determine an optimum processing strategy, even if SQL Server can’t use an index to actually locate the values. Statistics on Columns Column statistics can be useful for two main purposes  When the SQL Server optimizer is determining the optimal join order, it frequently is best to have the smaller input processed first. By ‘input’ we mean table after all filters in the WHERE clause have been applied. Even if there is no useful index on a column in the WHERE clause, statistics could tell us that only a few rows will quality, and those the resulting input will be very small.  The SQL Server query optimizer can use column statistics on non-initial columns in a composite nonclustered index to determine if scanning the leaf level to obtain the bookmarks will be an efficient processing strategy. For example, in the member table in the credit database, the first name column is almost unique. Suppose we have a nonclustered index on (lastname, firstname), and we issue this query: select * from member where firstname = 'MPRO' In this case, statistics on the firstname column would indicate very few rows satisfying this condition, so the optimizer will choose to scan the nonclustered index, since it is smaller than the clustered index (the table). The small number of bookmarks will then be followed to retrieve the actual data. Manually Updating Statistics You can also manually force statistics to be updated in one of two ways. You can run the UPDATE STATISTICS command on a table or on one specific index or column statistics, or you can also execute the procedure sp_updatestats, which runs UPDATE STATISTICS against all user-defined tables in the current database. You can create statistics on unindexed columns using the CREATE STATISTICS command or by executing sp_createstats, which creates single-column statistics for all eligible columns for all user tables in the current database. This includes all columns except computed columns and columns of the ntext, text, or image datatypes, and columns that already have statistics or are the first column of an index. Autostats By Default SQL Server Will Update Statistics on Any Index or Column as Needed Every database is created with the database options auto create statistics and auto update statistics set to true, but you can turn either one off. You can also turn off automatic updating of statistics for a specific table in one of two ways:  UPDATE STATISTICS In addition to updating the statistics, the option WITH NORECOMPUTE indicates that the statistics should not be automatically recomputed in the future. Running UPDATE STATISTICS again without the WITH NORECOMPUTE option enables automatic updates.  sp_autostats This procedure sets or unsets a flag for a table to indicate that statistics should or should not be updated automatically. You can also use this procedure with only the table name to find out whether the table is set to automatically have its index statistics updated. ' However, setting the database option auto update statistics to FALSE overrides any individual table settings. In other words, no automatic updating of statistics takes place. This is not a recommended practice unless thorough testing has shown you that you do not need the automatic updates or that the performance overhead is more than you can afford. Trace Flags Trace flag 205 – reports recompile due to autostats. Trace flag 8721 – writes information to the errorlog when AutoStats has been run. For more information, see the following Knowledge Base article: Q195565 “INF: How SQL Server 7.0 Autostats Work.” Statistics and Performance The Performance Penalty of NOT Having Up-To-Date Statistics Far Outweighs the Benefit of Avoiding Automatic Updating Autostats should be turned off only after thorough testing shows it to be necessary. Because autostats only forces a recompile after a certain number or percentage of rows has been changed, you do not have to make any adjustments for a read-only database. Lesson 3: Concepts – Query Optimization What You Will Learn After completing this lesson, you will be able to:  Describe the phases of query optimization.  Discuss how SQL Server estimates the selectivity of indexes and column and how this estimate is used in query optimization. Recommended Reading  Chapter 15: “The Query Processor”, Inside SQL Server 2000 by Kalen Delaney  Chapter 16: “Query Tuning”, Inside SQL Server 2000 by Kalen Delaney  Whitepaper about SQL Server Query Processor Architecture by Hal Berenson and Kalen Delaney http://msdn.microsoft.com/library/backgrnd/html/sqlquerproc.htm Phases of Query Optimization Query Optimization Involves several phases Trivial Plan Optimization Optimization itself goes through several steps. The first step is something called Trivial Plan Optimization. The whole idea of trivial plan optimization is that cost based optimization is a bit expensive to run. The optimizer can try a great many possible variations trying to find the cheapest plan. If SQL Server knows that there is only one really viable plan for a query, it could avoid a lot of work. A prime example is a query that consists of an INSERT with a VALUES clause. There is only one possible plan. Another example is a SELECT where all the columns are in a unique covering index, and that index is the only one that is useable. There is no other index that has that set of columns in it. These two examples are cases where SQL Server should just generate the plan and not try to find something better. The trivial plan optimizer finds the really obvious plans, which are typically very inexpensive. In fact, all the plans that get through the autoparameterization template result in plans that the trivial plan optimizer can find. Between those two mechanisms, the plans that are simple tend to be weeded out earlier in the process and do not pay a lot of the compilation cost. This is a good thing, because the number of potential plans in 7.0 went up astronomically as SQL Server added hash joins, merge joins and index intersections, to its list of processing techniques. Simplification and Statistics Loading If a plan is not found by the trivial plan optimizer, SQL Server can perform some simplifications, usually thought of as syntactic transformations of the query itself, looking for commutative properties and operations that can be rearranged. SQL Server can do constant folding, and other operations that do not require looking at the cost or analyzing what indexes are, but that can result in a more efficient query. SQL Server then loads up the metadata including the statistics information on the indexes, and then the optimizer goes through a series of phases of cost based optimization. Cost Based Optimization Phases The cost based optimizer is designed as a set of transformation rules that try various permutations of indexes and join strategies. Because of the number of potential plans in SQL Server 7.0 and SQL Server 2000, if the optimizer just ran through all the combinations and produced a plan, the optimization process would take a very long time to run. Therefore, optimization is broken up into phases. Each phase is a set of rules. After each phase is run, the cost of any resulting plan is examined, and if SQL Server determines that the plan is cheap enough, that plan is kept and executed. If the plan is not cheap enough, the optimizer runs the next phase, which is another set of rules. In the vast majority of cases, a good plan will be found in the preliminary phases. Typically, if the plan that a query would have had in SQL Server 6.5 is also the optimal plan in SQL Server 7.0 and SQL Server 2000, the plan will tend to be found either by the trivial plan optimizer or by the first phase of the cost based optimizer. The rules were intentionally organized to try to make that be true. The plan will probably consist of using a single index and using nested loops. However, every once in a while, because of lack of statistical information, or some other nuance, the optimizer will have to proceed with the later phases of optimization. Sometimes this is because there is a real possibility that the optimizer could find a better plan. When a plan is found, it becomes the optimizer’s output, and then SQL Server goes through all the caching mechanisms that we have already discussed in Module 5. Full Optimization At some point, the optimizer determines that it has gone through enough preliminary phases, and it reverts to a phase called full optimization. If the optimizer goes through all the preliminary phases, and still has not found a cheap plan, it examines the cost for the plan that it has so far. If the cost is above the threshold, the optimizer goes into a phase called full optimization. This threshold is configurable, as the configuration option ‘cost threshold for parallelism’. The full optimization phase assumes that this plan should be run this in parallel. If the machine is very busy, the plan will end up running it in serial, but the optimizer has a goal to produce a good parallel. If the cost is below the threshold (or a single processor machine), the full optimization phase just uses a brute force method to find a serial plan. Selectivity Estimation Selectivity Is One of The Most Important Pieces of Information One of the most import things the optimizer needs to know is the number of rows from any table that will meet all the conditions in the query. If there are no restrictions on a table, and all the rows will be needed, the optimizer can determine the number of rows from the sysindexes table. This number is not absolutely guaranteed to be accurate, but it is the number the optimizer uses. If there is a filter on the table in a WHERE clause, the optimizer needs statistics information. Indexes automatically maintain statistics, and the optimizer will use these values to determine the usefulness of the index. If there is no index on the column involved in the filter, then column statistics can be used or generated. Optimizing Search Arguments In General, the Filters in the WHERE Clause Determine Which Indexes Will Be Useful If an indexed column is referenced in a Search Argument (SARG), the optimizer will analyze the cost of using that index. A SARG has the form:  column value  value column  Operator must be one of =, >, >= <, <= The value can be a constant, an operation, or a variable. Some functions also will be treated as SARGs. These queries have SARGs, and a nonclustered index on firstname will be used in most cases: select * from member where firstname < 'AKKG' select * from member where firstname = substring('HAAKGALSFJA', 2,5) select * from member where firstname = 'AA' + 'KG' declare @name char(4) set @name = 'AKKG' select * from member where firstname < @name Not all functions can be used in SARGs. select * from charge where charge_amt < 2*2 select * from charge where charge_amt < sqrt(16) Compare these queries to ones using = instead of <. With =, the optimizer can use the density information to come up with a good row estimate, even if it’s not going to actually perform the function’s calculations. A filter with a variable is usually a SARG The issue is, can the optimizer come up with useful costing information? A filter with a variable is not a SARG if the variable is of a different datatype, and the column must be converted to the variable’s datatype For more information, see the following Knowledge Base article: Q198625 Enter Title of KB Article Here Use credit go CREATE TABLE [member2] ( [member_no] [smallint] NOT NULL , [lastname] [shortstring] NOT NULL , [firstname] [shortstring] NOT NULL , [middleinitial] [letter] NULL , [street] [shortstring] NOT NULL , [city] [shortstring] NOT NULL , [state_prov] [statecode] NOT NULL , [country] [countrycode] NOT NULL , [mail_code] [mailcode] NOT NULL ) GO insert into member2 select member_no, lastname, firstname, middleinitial, street, city, state_prov, country, mail_code from member alter table member2 add constraint pk_member2 primary key clustered (lastname, member_no, firstname, country) declare @id int set @id = 47 update member2 set city = city + ' City', state_prov = state_prov + ' State' where lastname = 'Barr' and member_no = @id and firstname = 'URQYJBFVRRPWKVW' and country = 'USA' These queries don’t have SARGs, and a table scan will be done: select * from member where substring(lastname, 1,2) = ‘BA’ Some non-SARGs can be converted select * from member where lastname like ‘ba%’ In some cases, you can rewrite your query to turn a non-SARG into a SARG; for example, you can rewrite the substring query above and the LIKE query that follows it. Join Order and Types of Joins Join Order and Strategy Is Determined By the Optimizer The execution plan output will display the join order from top to bottom; i.e. the table listed on top is the first one accessed in a join. You can override the optimizer’s join order decision in two ways:  OPTION (FORCE ORDER) applies to one query  SET FORCEPLAN ON applies to entire session, until set OFF If either of these options is used, the join order is determined by the order the tables are listed in the query’s FROM clause, and no optimizer on JOIN ORDER is done. Forcing the JOIN order may force a particular join strategy. For example, in most outer join operations, the outer table is processed first, and a nested loops join is done. However, if you force the inner table to be accessed first, a merge join will need to be done. Compare the query plan for this query with and without the FORCE ORDER hint: select * from titles right join publishers on titles.pub_id = publishers.pub_id -- OPTION (FORCE ORDER) Nested Loop Join A nested iteration is when the query optimizer constructs a set of nested loops, and the result set grows as it progresses through the rows. The query optimizer performs the following steps. 1. Finds a row from the first table. 2. Uses that row to scan the next table. 3. Uses the result of the previous table to scan the next table. Evaluating Join Combinations The query optimizer automatically evaluates at least four or more possible join combinations, even if those combinations are not specified in the join predicate. You do not have to add redundant clauses. The query optimizer balances the cost and uses statistics to determine the number of join combinations that it evaluates. Evaluating every possible join combination is inefficient and costly. Evaluating Cost of Query Performance When the query optimizer performs a nested join, you should be aware that certain costs are incurred. Nested loop joins are far superior to both merge joins and hash joins when executing small transactions, such as those affecting only a small set of rows. The query optimizer:  Uses nested loop joins if the outer input is quite small and the inner input is indexed and quite large.  Uses the smaller input as the outer table.  Requires that a useful index exist on the join predicate for the inner table.  Always uses a nested loop join strategy if the join operation uses an operator other than an equality operator. Merge Joins The columns of the join conditions are used as inputs to process a merge join. SQL Server performs the following steps when using a merge join strategy: 1. Gets the first input values from each input set. 2. Compares input values. 3. Performs a merge algorithm. • If the input values are equal, the rows are returned. • If the input values are not equal, the lower value is discarded, and the next input value from that input is used for the next comparison. 4. Repeats the process until all of the rows from one of the input sets have been processed. 5. Evaluates any remaining search conditions in the query and returns only rows that qualify. Note Only one pass per input is done. The merge join operation ends after all of the input values of one input have been evaluated. The remaining values from the other input are not processed. Requires That Joined Columns Are Sorted If you execute a query with join operations, and the joined columns are in sorted order, the query optimizer processes the query by using a merge join strategy. A merge join is very efficient because the columns are already sorted, and it requires fewer page I/O. Evaluates Sorted Values For the query optimizer to use the merge join, the inputs must be sorted. The query optimizer evaluates sorted values in the following order: 1. Uses an existing index tree (most typical). The query optimizer can use the index tree from a clustered index or a covered nonclustered index. 2. Leverages sort operations that the GROUP BY, ORDER BY, and CUBE clauses use. The sorting operation only has to be performed once. 3. Performs its own sort operation in which a SORT operator is displayed when graphically viewing the execution plan. The query optimizer does this very rarely. Performance Considerations Consider the following facts about the query optimizer's use of the merge join:  SQL Server performs a merge join for all types of join operations (except cross join or full join operations), including UNION operations.  A merge join operation may be a one-to-one, one-to-many, or many-to-many operation. If the merge join is a many-to-many operation, SQL Server uses a temporary table to store the rows. If duplicate values from each input exist, one of the inputs rewinds to the start of the duplicates as each duplicate value from the other input is processed.  Query performance for a merge join is very fast, but the cost can be high if the query optimizer must perform its own sort operation. If the data volume is large and the desired data can be obtained presorted from existing Balanced-Tree (B-Tree) indexes, merge join is often the fastest join algorithm.  A merge join is typically used if the two join inputs have a large amount of data and are sorted on their join columns (for example, if the join inputs were obtained by scanning sorted indexes).  Merge join operations can only be performed with an equality operator in the join predicate. Hashing is a strategy for dividing data into equal sets of a manageable size based on a given property or characteristic. The grouped data can then be used to determine whether a particular data item matches an existing value. Note Duplicate data or ranges of data are not useful for hash joins because the data is not organized together or in order. When a Hash Join Is Used The query optimizer uses a hash join option when it estimates that it is more efficient than processing queries by using a nested loop or merge join. It typically uses a hash join when an index does not exist or when existing indexes are not useful. Assigns a Build and Probe Input The query optimizer assigns a build and probe input. If the query optimizer incorrectly assigns the build and probe input (this may occur because of imprecise density estimates), it reverses them dynamically. The ability to change input roles dynamically is called role reversal. Build input consists of the column values from a table with the lowest number of rows. Build input creates a hash table in memory to store these values. The hash bucket is a storage place in the hash table in which each row of the build input is inserted. Rows from one of the join tables are placed into the hash bucket where the hash key value of the row matches the hash key value of the bucket. Hash buckets are stored as a linked list and only contain the columns that are needed for the query. A hash table contains hash buckets. The hash table is created from the build input. Probe input consists of the column values from the table with the most rows. Probe input is what the build input checks to find a match in the hash buckets. Note The query optimizer uses column or index statistics to help determine which input is the smaller of the two. Processing a Hash Join The following list is a simplified description of how the query optimizer processes a hash join. It is not intended to be comprehensive because the algorithm is very complex. SQL Server: 1. Reads the probe input. Each probe input is processed one row at a time. 2. Performs the hash algorithm against each probe input and generates a hash key value. 3. Finds the hash bucket that matches the hash key value. 4. Accesses the hash bucket and looks for the matching row. 5. Returns the row if a match is found. Performance Considerations Consider the following facts about the hash joins that the query optimizer uses:  Similar to merge joins, a hash join is very efficient, because it uses hash buckets, which are like a dynamic index but with less overhead for combining rows.  Hash joins can be performed for all types of join operations (except cross join operations), including UNION and DIFFERENCE operations.  A hash operator can remove duplicates and group data, such as SUM (salary) GROUP BY department. The query optimizer uses only one input for both the build and probe roles.  If join inputs are large and are of similar size, the performance of a hash join operation is similar to a merge join with prior sorting. However, if the size of the join inputs is significantly different, the performance of a hash join is often much faster.  Hash joins can process large, unsorted, non-indexed inputs efficiently. Hash joins are useful in complex queries because the intermediate results: • Are not indexed (unless explicitly saved to disk and then indexed). • Are often not sorted for the next operation in the execution plan.  The query optimizer can identify incorrect estimates and make corrections dynamically to process the query more efficiently.  A hash join reduces the need for database denormalization. Denormalization is typically used to achieve better performance by reducing join operations despite redundancy, such as inconsistent updates. Hash joins give you the option to vertically partition your data as part of your physical database design. Vertical partitioning represents groups of columns from a single table in separate files or indexes. Subquery Performance Joins Are Not Inherently Better Than Subqueries Here is an example showing three different ways to update a table, using a second table for lookup purposes. The first uses a JOIN with the update, the second uses a regular introduced with IN, and the third uses a correlated subquery. All three yield nearly identical performance. Note Note that performance comparisons cannot just be made based on I/Os. With HASHING and MERGING techniques, the number of reads may be the same for two queries, yet one may take a lot longer and use more memory resources. Also, always be sure to monitor statistics time. Suppose you want to add a 5 percent discount to order items in the Order Details table for which the supplier is Exotic Liquids, whose supplierid is 1. -- JOIN solution BEGIN TRAN UPDATE OD SET discount = discount + 0.05 FROM [Order Details] AS OD JOIN Products AS P ON OD.productid = P.productid WHERE supplierid = 1 ROLLBACK TRAN -- Regular subquery solution BEGIN TRAN UPDATE [Order Details] SET discount = discount + 0.05 WHERE productid IN (SELECT productid FROM Products WHERE supplierid = 1) ROLLBACK TRAN -- Correlated Subquery Solution BEGIN TRAN UPDATE [Order Details] SET discount = discount + 0.05 WHERE EXISTS(SELECT supplierid FROM Products WHERE [Order Details].productid = Products.productid AND supplierid = 1) ROLLBACK TRAN Internally, Your Join May Be Rewritten SQL Server’s query processor had many different ways of resolving your JOIN expressions. Subqueries may be converted to a JOIN with an implied distinct, which may result in a logical operator of SEMI JOIN. Compare the plans of the first two queries: USE credit select member_no from member where member_no in (select member_no from charge) select distinct m.member_no from member m join charge c on m.member_no = c.member_no The second query uses a HASH MATCH as the final step to remove the duplicates. The first query only had to do a semi join. For these queries, although the I/O values are the same, the first query (with the subquery) runs much faster (almost twice as fast). Another similar looking join is
View Assessment Result: Multiple-Choice Quiz 2 Your performance was as follows: 1. The degree of a table is the number of _____ in the table. (a) keys (b) columns (c) rows (d) foreign keys Correct answer is (b) Your score on this question is: 10.00 Feedback: (b) -------------------------------------------------------------------------------- 2. The arity of a table is the number of _____ in the table. (a) keys (b) columns (c) foreign keys (d) rows Correct answer is (b) Your score on this question is: 10.00 Feedback: (b) -------------------------------------------------------------------------------- 3. What information is necessary when specifying the structure of a table? (a) the name of the table and the amount of storage space to be allocated to the table (b) the name of the table, the names of the table's attributes, the data types of the table's attributes, the formats of the table's attributes, and the maximum number of rows that the table can have (c) the name of the table and the names of the table's attributes (d) the name of the table, the names of the table's attributes, the data types of attributes, and the formats of attributes Correct answer is (d) Your score on this question is: 10.00 Feedback: (d) -------------------------------------------------------------------------------- 4. The foreign key in a table T1 _____ the same _____ as the corresponding primary key in table T2. must have, name need not have, name must have, domain (a) I, II, and III (b) I and II (c) I and III (d) II and III Correct answer is (d) Your score on this question is: 10.00 Feedback: (d) -------------------------------------------------------------------------------- 5. Which of the following SQL statements can be used to add a row to a table? (a) CREATE (b) INSERT (c) APPEND (d) ADD Correct answer is (b) Your score on this question is: 10.00 Feedback: (b) -------------------------------------------------------------------------------- 6. A difference operation can be applied to tables that (a) are union compatible (b) have the same column names (c) have the same name (d) are the same size Correct answer is (a) Your score on this question is: 10.00 Feedback: (a) -------------------------------------------------------------------------------- 7. Which of the following SQL statements can be used to create a relational table? (a) INSERT (b) ADD (c) CREATE (d) APPEND Correct answer is (c) Your score on this question is: 10.00 Feedback: (c) -------------------------------------------------------------------------------- 8. For two tables to be union compatible, the tables should be the same with respect to which of the following? (a) keys (b) cardinality (c) name (d) degree Correct answer is (d) Your score on this question is: 0.00 Feedback: (b) -------------------------------------------------------------------------------- 9. A deletion operation will _____ if the deletion leads to the violation of a referential integrity constraint. (a) fail (b) succeed with warning (c) succeed without warning (d) crash the system Correct answer is (a) Your score on this question is: 10.00 Feedback: (a) -------------------------------------------------------------------------------- 10. With Query By Example, a user enters a query by (a) filling in skeleton tables of the database with examples of what is to be retrieved (b) placing SQL keywords, such as select, under the column names they want to retrieve (c) typing a syntactically correct SQL query that uses column and table names similar to the correct column and table names in a database (d) writing an English description of the data that the user needs Correct answer is (a) Your score on this question is: 10.00 Feedback: See section 1.2.3 in the course notes. (a) -------------------------------------------------------------------------------- Go to top of assessment. Total score: 90.00 ? Copyright 2008 iCarnegie, Inc. All rights reserved. 1. In the Entity-Relationship model, the degree of a relationship specifies which of the following? (a) The cardinality ratio of the relationship (b) The number of integrity constraints required to implement the relationship (c) The number of attributes that characterize the relationship (d) The number of entities that participate in the relationship Correct answer is (d) 2. In an ER model, which of the following is true about a component attribute? (a) A component attribute is always atomic. (b) Component attributes must always be combined by an aggregation operation. (c) A component attribute can be a composite attribute. (d) A component attribute always contains other components. Correct answer is (c) 3. In the Entity-Relationship model, properties that characterize entities and relationships are modeled as (a) attributes (b) participation constraints (c) entity types (d) weak entities Correct answer is (a) 4. What is an identifying owner in an ER model? (a) The entity upon which a weak entity's existence depends (b) The relationship that identifies a weak entity's owner (c) The entity upon which a strong entity's existence depends (d) The relationship that identifies a strong entity's owner Correct answer is (a) 5. In an ER model, the cardinality ratio of a relationship type is (a) the number of instances of relationships of that relationship type (b) the number of entity types involved in that relationship type (c) the number of relationships of that relationship type in which an entity can participate (d) the minimum number of entities that can participate in that relationship type Correct answer is (c) 6. Which of the following is true about storage for derived attributes? (a) Derived attributes must not be stored. (b) Derived attributes are usually stored because storage improves retrieval performance. (c) Derived attributes must be stored. (d) Derived attributes are usually not stored because they can be computed. Correct answer is (d) 7. In an ER model, what is a recursive relationship type? (a) A never-ending type of relationship (b) The type of relationship that does not belong anywhere (c) The type of relationship between entities of one entity type (d) The relationship type where the related entities are one and the same Correct answer is (c) 8. In EER modeling, generalization is the process of generating (a) superclasses out of subclasses (b) subclasses out of superclasses (c) entities out of attributes (d) attributes out of entities Correct answer is (a) 9. When mapping from an ER model to a relational model, a strong entity is mapped into a (a) table (b) row (c) column (d) key Correct answer is (a) 10. Which of the following is true about attributes in a relational model? Attributes can be multi-valued. Attributes can be composite. (a) Both I and II (b) II only (c) Neither I nor II (d) I only Correct answer is (c) 1. In an ER model, what is a recursive relationship type? (a) The relationship type where the related entities are one and the same (b) The type of relationship that does not belong anywhere (c) The type of relationship between entities of one entity type (d) A never-ending type of relationship Correct answer is (c) 2. In an ER model, the cardinality ratio of a relationship type is (a) the number of relationships of that relationship type in which an entity can participate (b) the minimum number of entities that can participate in that relationship type (c) the number of entity types involved in that relationship type (d) the number of instances of relationships of that relationship type Correct answer is (a) 3. In the Entity-Relationship model, a derived attribute is one (a) that is composed of multiple atomic attributes (b) that characterizes a relationship instead of an entity (c) that may have multiple values simultaneously (d) whose value can be computed from the values of other attributes Correct answer is (d) 4. In the Entity-Relationship model, properties that characterize entities and relationships are modeled as (a) entity types (b) weak entities (c) attributes (d) participation constraints Correct answer is (c) 5. Which of the following is true about storage for derived attributes? (a) Derived attributes must be stored. (b) Derived attributes are usually stored because storage improves retrieval performance. (c) Derived attributes must not be stored. (d) Derived attributes are usually not stored because they can be computed. Correct answer is (d) 6. What is an identifying owner in an ER model? (a) The relationship that identifies a weak entity's owner (b) The relationship that identifies a strong entity's owner (c) The entity upon which a strong entity's existence depends (d) The entity upon which a weak entity's existence depends Correct answer is (d) 7. In an ER model, which of the following is true about a component attribute? (a) A component attribute always contains other components. (b) A component attribute can be a composite attribute. (c) A component attribute is always atomic. (d) Component attributes must always be combined by an aggregation operation. Correct answer is (b) 8. In EER modeling, generalization is the process of generating (a) attributes out of entities (b) superclasses out of subclasses (c) subclasses out of superclasses (d) entities out of attributes Correct answer is (b) 9. When mapping from an ER model to a relational model, a strong entity is mapped into a (a) key (b) row (c) column (d) table Correct answer is (d) 10. Which of the following is true about attributes in a relational model? Attributes can be multi-valued. Attributes can be composite. (a) I only (b) II only (c) Neither I nor II (d) Both I and II Correct answer is (c) 1. Through normalization, update anomalies (a) can be eliminated (b) is usually left unchanged (c) can be maximized (d) can be minimized but not eliminated Correct answer is (a) 2. Which of the following is a property (are properties) exhibited by good relational schemas? The use of null values in tuples The grouping of as many attributes as possible into one main table The elimination of data redundancy to avoid update anomalies (a) III only (b) None (c) I and II only (d) II and III only Correct answer is (a) 3. Which of the following statements concerning normal forms is true? (a) A relation that is in second normal form is also in first normal form. (b) The lower the normal form number, the better the schema design is. (c) Each normal form contains a state of independent properties, unrelated to other normal forms. (d) Schemas that are in second normal form are considered the best. Correct answer is (a) 4. Consider the following functional dependency. {A, B} -> {C} Regarding this dependency, which of the following statements is (are) true? The values of C are uniquely determined by the values of A. The values of A are uniquely determined by the values of C. (a) None (b) II only (c) I only (d) I and II Correct answer is (a) 5. Which of the following problems can be caused by data redundancy in a relational schema? Inefficient use of space Update anomalies and possible loss of data Inefficient use of processing time (a) I and II only (b) I and III only (c) I, II, and III (d) II only Correct answer is (c) 6. Consider a table with atomic attributes A, B, and C and the following functional dependencies. A -> B B -> C If the primary key of this table is attribute A, then this relation satisfies which of the following normal forms? First Second Third (a) None (b) I only (c) I, II and III (d) I and II only Correct answer is (d) 7. For a relation to be in 3NF, it should not contain _____ attribute that is transitively dependent on _____. (a) a non-primary key, a foreign key (b) a primary key, a non-primary key (c) a primary key, a foreign key (d) a non-primary key, the primary key Correct answer is (d) 8. The FD X -> Y is a full dependency in a relation R, if there is _____ attribute A that can be _____ X and the dependency still holds. (a) no, added to (b) no, removed from (c) at least one, removed from (d) at least one, added to Correct answer is (b) 9. For a relation to be in 2NF, _____ attribute must be fully functionally dependent on _____. (a) every non-primary-key, the primary key (b) every alternate key, the primary key (c) every non-key, every key (d) every non-key, at least one key Correct answer is (a) 10. The FD X -> Y is a partial dependency in a relation R, if there is _____ attribute A that can be _____ X and the dependency still holds. (a) at least one, removed from (b) at least one, added to (c) no, added to (d) no, removed from Correct answer is (a) 1. Through normalization, update anomalies (a) can be eliminated (b) is usually left unchanged (c) can be minimized but not eliminated (d) can be maximized Correct answer is (a) 2. Consider the following functional dependency. {A, B} -> {C} Regarding this dependency, which of the following statements is (are) true? The values of C are uniquely determined by the values of A. The values of A are uniquely determined by the values of C. (a) None (b) I and II (c) I only (d) II only Correct answer is (a) 3. Which of the following is a property (are properties) exhibited by good relational schemas? The use of null values in tuples The grouping of as many attributes as possible into one main table The elimination of data redundancy to avoid update anomalies (a) III only (b) None (c) II and III only (d) I and II only Correct answer is (a) 4. Through normalization, data redundancy (a) can be eliminated (b) can be maximized (c) can be minimized but not eliminated (d) are usually left unchanged Correct answer is (a) 5. Which of the following statements concerning normal forms is true? (a) A relation that is in second normal form is also in first normal form. (b) Each normal form contains a state of independent properties, unrelated to other normal forms. (c) Schemas that are in second normal form are considered the best. (d) The lower the normal form number, the better the schema design is. Correct answer is (a) 6. For a relation to be in 3NF, it should not contain _____ attribute that is transitively dependent on _____. (a) a primary key, a foreign key (b) a primary key, a non-primary key (c) a non-primary key, a foreign key (d) a non-primary key, the primary key Correct answer is (d) 7. The FD X -> Y is a full dependency in a relation R, if there is _____ attribute A that can be _____ X and the dependency still holds. (a) no, removed from (b) at least one, removed from (c) at least one, added to (d) no, added to Correct answer is (a) 8. Consider a table with atomic attributes A, B, and C and the following functional dependencies. A -> B B -> C If the primary key of this table is attribute A, then this relation satisfies which of the following normal forms? First Second Third (a) I, II and III (b) None (c) I and II only (d) I only Correct answer is (c) 9. For a relation to be in 2NF, _____ attribute must be fully functionally dependent on _____. (a) every alternate key, the primary key (b) every non-key, at least one key (c) every non-key, every key (d) every non-primary-key, the primary key Correct answer is (d) 10. The FD X -> Y is a partial dependency in a relation R, if there is _____ attribute A that can be _____ X and the dependency still holds. (a) no, added to (b) no, removed from (c) at least one, added to (d) at least one, removed from Correct answer is (d) 1. What is an identifying owner in an ER model? (a) The entity upon which a weak entity's existence depends (b) The relationship that identifies a weak entity's owner (c) The relationship that identifies a strong entity's owner (d) The entity upon which a strong entity's existence depends Correct answer is (a) 2. In an ER model, the cardinality ratio of a relationship type is (a) the minimum number of entities that can participate in that relationship type (b) the number of instances of relationships of that relationship type (c) the number of entity types involved in that relationship type (d) the number of relationships of that relationship type in which an entity can participate Correct answer is (d) 3. In the Entity-Relationship model, properties that characterize entities and relationships are modeled as (a) entity types (b) participation constraints (c) weak entities (d) attributes Correct answer is (d) 4. In an ER model, what is a recursive relationship type? (a) A never-ending type of relationship (b) The relationship type where the related entities are one and the same (c) The type of relationship between entities of one entity type (d) The type of relationship that does not belong anywhere Correct answer is (c) 5. In the Entity-Relationship model, a derived attribute is one (a) that characterizes a relationship instead of an entity (b) that may have multiple values simultaneously (c) whose value can be computed from the values of other attributes (d) that is composed of multiple atomic attributes Correct answer is (c) 6. In the Entity-Relationship model, the degree of a relationship specifies which of the following? (a) The number of attributes that characterize the relationship (b) The number of entities that participate in the relationship (c) The cardinality ratio of the relationship (d) The number of integrity constraints required to implement the relationship Correct answer is (b) 7. Which of the following is true about storage for derived attributes? (a) Derived attributes are usually not stored because they can be computed. (b) Derived attributes are usually stored because storage improves retrieval performance. (c) Derived attributes must be stored. (d) Derived attributes must not be stored. Correct answer is (a) 8. In EER modeling, generalization is the process of generating (a) superclasses out of subclasses (b) entities out of attributes (c) subclasses out of superclasses (d) attributes out of entities Correct answer is (a) 9. When mapping from an ER model to a relational model, a strong entity is mapped into a (a) key (b) table (c) row (d) column Correct answer is (b) 10. Which of the following is true about attributes in a relational model? Attributes can be multi-valued. Attributes can be composite. (a) II only (b) I only (c) Both I and II (d) Neither I nor II Correct answer is (d) 1. Which of the following is true about storage for derived attributes? (a) Derived attributes are usually stored because storage improves retrieval performance. (b) Derived attributes must be stored. (c) Derived attributes are usually not stored because they can be computed. (d) Derived attributes must not be stored. Correct answer is (c) 2. In an ER model, the cardinality ratio of a relationship type is (a) the minimum number of entities that can participate in that relationship type (b) the number of entity types involved in that relationship type (c) the number of relationships of that relationship type in which an entity can participate (d) the number of instances of relationships of that relationship type Correct answer is (c) 3. In the Entity-Relationship model, the degree of a relationship specifies which of the following? (a) The number of attributes that characterize the relationship (b) The number of integrity constraints required to implement the relationship (c) The cardinality ratio of the relationship (d) The number of entities that participate in the relationship Correct answer is (d) 4. In the Entity-Relationship model, properties that characterize entities and relationships are modeled as (a) weak entities (b) participation constraints (c) attributes (d) entity types Correct answer is (c) Your score on this question is: 0.00 5. A weak entity type implies a (a) weak relationship type (b) relationship with total participation constraint (c) strong relationship type (d) relationship with partial participation constraint Correct answer is (b) 6. In an ER model, which of the following is true about a component attribute? (a) A component attribute can be a composite attribute. (b) Component attributes must always be combined by an aggregation operation. (c) A component attribute always contains other components. (d) A component attribute is always atomic. Correct answer is (a) 7. In the Entity-Relationship model, a derived attribute is one (a) that characterizes a relationship instead of an entity (b) that is composed of multiple atomic attributes (c) whose value can be computed from the values of other attributes (d) that may have multiple values simultaneously Correct answer is (c) 1. Through normalization, update anomalies (a) is usually left unchanged (b) can be minimized but not eliminated (c) can be maximized (d) can be eliminated Correct answer is (d) 2. Which of the following problems can be caused by data redundancy in a relational schema? Inefficient use of space Update anomalies and possible loss of data Inefficient use of processing time (a) I and II only (b) I and III only (c) II only (d) I, II, and III Correct answer is (d) 3. Consider the following functional dependency. {A, B} -> {C} Regarding this dependency, which of the following statements is (are) true? The values of C are uniquely determined by the values of A. The values of A are uniquely determined by the values of C. (a) I only (b) I and II (c) II only (d) None Correct answer is (d) 4. Which of the following is a property (are properties) exhibited by good relational schemas? The use of null values in tuples The grouping of as many attributes as possible into one main table The elimination of data redundancy to avoid update anomalies (a) III only (b) II and III only (c) I and II only (d) None Correct answer is (a) 5. Which of the following statements concerning normal forms is true? (a) Schemas that are in second normal form are considered the best. (b) Each normal form contains a state of independent properties, unrelated to other normal forms. (c) A relation that is in second normal form is also in first normal form. (d) The lower the normal form number, the better the schema design is. Correct answer is (c) 6. The FD X -> Y is a partial dependency in a relation R, if there is _____ attribute A that can be _____ X and the dependency still holds. (a) at least one, added to (b) at least one, removed from (c) no, removed from (d) no, added to Correct answer is (b) 7. For a relation to be in 2NF, _____ attribute must be fully functionally dependent on _____. (a) every non-primary-key, the primary key (b) every non-key, at least one key (c) every non-key, every key (d) every alternate key, the primary key Correct answer is (a) 8. Consider a table with atomic attributes A, B, and C and the following functional dependencies. A -> B B -> C If the primary key of this table is attribute A, then this relation satisfies which of the following normal forms? First Second Third (a) I only (b) None (c) I and II only (d) I, II and III Correct answer is (c) 9. The FD X -> Y is a full dependency in a relation R, if there is _____ attribute A that can be _____ X and the dependency still holds. (a) no, removed from (b) at least one, removed from (c) at least one, added to (d) no, added to Correct answer is (a) 10. For a relation to be in 3NF, it should not contain _____ attribute that is transitively dependent on _____. (a) a primary key, a foreign key (b) a non-primary key, a foreign key (c) a non-primary key, the primary key (d) a primary key, a non-primary key Correct answer is (c) 1. Which of the following statements concerning normal forms is true? (a) The lower the normal form number, the better the schema design is. (b) A relation that is in second normal form is also in first normal form. (c) Schemas that are in second normal form are considered the best. (d) Each normal form contains a state of independent properties, unrelated to other normal forms. Correct answer is (b) 2. Consider the following functional dependency. {A, B} -> {C} Regarding this dependency, which of the following statements is (are) true? The values of C are uniquely determined by the values of A. The values of A are uniquely determined by the values of C. (a) I only (b) II only (c) I and II (d) None Correct answer is (d) 3. Which of the following problems can be caused by data redundancy in a relational schema? Inefficient use of space Update anomalies and possible loss of data Inefficient use of processing time (a) I, II, and III (b) I and II only (c) I and III only (d) II only Correct answer is (a) Y 4. Through normalization, update anomalies (a) can be eliminated (b) can be maximized (c) is usually left unchanged (d) can be minimized but not eliminated Correct answer is (a) 5. Which of the following is a property (are properties) exhibited by good relational schemas? The use of null values in tuples The grouping of as many attributes as possible into one main table The elimination of data redundancy to avoid update anomalies (a) I and II only (b) III only (c) None (d) II and III only Correct answer is (b) 6. Consider a table with atomic attributes A, B, and C and the following functional dependencies. A -> B B -> C If the primary key of this table is attribute A, then this relation satisfies which of the following normal forms? First Second Third (a) I and II only (b) I only (c) I, II and III (d) None Correct answer is (a) 7. For a relation to be in 3NF, it should not contain _____ attribute that is transitively dependent on _____. (a) a non-primary key, a foreign key (b) a primary key, a foreign key (c) a primary key, a non-primary key (d) a non-primary key, the primary key Correct answer is (d) 8. The FD X -> Y is a partial dependency in a relation R, if there is _____ attribute A that can be _____ X and the dependency still holds. (a) at least one, added to (b) no, removed from (c) no, added to (d) at least one, removed from Correct answer is (d) 9. For a relation to be in 2NF, _____ attribute must be fully functionally dependent on _____. (a) every non-primary-key, the primary key (b) every alternate key, the primary key (c) every non-key, every key (d) every non-key, at least one key Correct answer is (a) 10. The FD X -> Y is a full dependency in a relation R, if there is _____ attribute A that can be _____ X and the dependency still holds. (a) no, added to (b) at least one, removed from (c) at least one, added to (d) no, removed from Correct answer is (d) 1. In an ER model, which of the following is true about a composite attribute? (a) A composite attribute can have a method attached to it. (b) A composite attribute cannot be broken into more basic attributes. (c) A composite attribute can be broken into more basic attributes. (d) A composite attribute can only be designed by users with special privileges. Correct answer is (c) 2. The term physical data independence refers to the ability to change (a) the physical layout of the data without changing the external schemas, the conceptual schemas, or the application programs (b) the data without physically relocating the tables (c) the conceptual schema without changing the application programs (d) the application programs without changing the conceptual schema Correct answer is (a) 3. What attributes does a subclass have? (a) None of the attributes of its superclass (b) All the attributes of its superclass, and possibly more (c) Just the attributes from the superclass (d) A subset of the attributes of its superclass Correct answer is (b) 4. If X -> Y, which of the following would make Y fully dependent on X? (a) Y is a single attribute (b) X is a single attribute (c) X consists of multiple attributes (d) Y consists of multiple attributes Correct answer is (b) 5. In an ER model, what is the degree of a relationship type? (a) The validity of the relationship type (b) The strength of the relationship type (c) The number of entity types participating in the relationship type (d) The number of instances of the relationship type Correct answer is (c) 6. Database design typically consists of which of the following phases? Conceptual design Logical design Physical design (a) II only (b) I, II, and III (c) II and III only (d) I only Correct answer is (b) 7. A relational schema is in first normal form, if the domain of all of its (a) primary keys are not multi-valued (b) primary keys and alternate keys are not multi-valued (c) primary keys are not composite (d) attributes can take on only atomic values Correct answer is (d) 8. In an ER model, a derived attribute is one whose values (a) have been derived at some time in the past (b) can be derived from the values of some other attributes (c) can be derived from the system tables (d) can be derived from another table Correct answer is (b) 9. Y is transitively dependent on X, if (a) X -> Y and A -> Y (b) X -> A, B and A -> Y (c) X -> Y and Y -> A (d) X -> A, B and Y -> A, B Correct answer is (b) 10. Relationships in an ER model are primarily translated to which of the following in a relational model? (a) relationships (b) primary keys and foreign keys (c) three-way tables (d) dummy relationship tables Correct answer is (b) View Assessment Result With Query By Example, a user enters a query by (a) filling in skeleton tables of the database with examples of what is to be retrieved (b) placing SQL keywords, such as select, under the column names they want to retrieve (c) writing an English description of the data that the user needs (d) typing a syntactically correct SQL query that uses column and table names similar to the correct column and table names in a database F Your performance was as follows: You took 2 minutes on this assessment from Tue Mar 17 05:22:13 UTC+0800 2009 to Tue Mar 17 05:24:13 UTC+0800 2009. Total score: 100.00 1. An E-Commerce system consists of the following components. Which of the same components must be included in a database management system? 1 The data, such as information about the goods available for sale, customers, orders placed, shipping information, etc. 2 A collection of programs must be included that control the data, such as programs to create, maintain, and manipulate the data. These programs can be easily used to create, maintain, and manipulate data in other domains, such as in a library information system. 3 A collection of programs that operate on the data, but are specific to the E-commerce system. These programs enable users to browse through the store-items, place orders, track shipping, etc. (a) II only (b) I, II, and III (c) I only (d) II and III only Correct answer is (a) Your score on this question is: 14.29 Feedback: A DBMS refers to just the set of general-purpose programs to control data. (a) 2. An E-Commerce system consists of the following components. Which of these same components will constitute a database system? 4 The data, such as information about the goods available for sale, customers, orders placed, shipping information, etc. 5 A collection of programs that control the data, such as programs to create, maintain, and manipulate the data constitutes a database system. These programs can be easily used to create, maintain, and manipulate data in other domains such as in a library information system. 6 A collection of programs that operate on the data, but are specific to the E-commerce system, constitutes a database system. These programs enable users to browse through the store-items, place orders, track shipping, etc. (a) I only (b) I, II, and III (c) I and II only (d) II only Correct answer is (b) Your score on this question is: 14.29 Feedback: A database system includes the data, the DBMS, and the application-specific programs that operate on that data. (b) 3. An E-Commerce system consists of the following components. Which of these same components must be included in a database? 7 The data, such as information about the goods available for sale, customers, orders placed, shipping information, etc. 8 A database must include a collection of programs that control the data, such as programs to create, maintain, and manipulate the data. These programs can be easily used to create, maintain, and manipulate data in other domains. 9 A database must include a collection of programs that operate on the data, but are specific to the E-commerce system. These programs enable users to browse through the store-items, place orders, track shipping, etc. (a) I and II only (b) I only (c) II only (d) I, II, and III Correct answer is (b) Your score on this question is: 14.29 Feedback: Database refers to just the data (b) 4. An E-Commerce database contains data about customers, products, orders, system response times, etc. Which of the following can be specified as integrity constraints in an E-Commerce database system? 10 No two products can have the same product ID. 11 The DBMS response time for all Web requests should be at most 2 seconds. 12 A customer order cannot have more than one shipping address. (a) I and III only (b) I and II only (c) I only (d) I, II, and III Correct answer is (a) Your score on this question is: 14.29 Feedback: The constraints I, II and III specify the application semantics of the data captured in the E-Commerce database. Constraint II, although it seems contrary to common sense, is not something that can be prohibited by the DBMS because the DBMS is general purpose. The response time of the DBMS cannot be enforced by the DBMS. It depends on factors such the processor speed, memory available, etc. (a) 5. In a database system, whose responsibility is it to provide data consistency? (a) the user's (b) the application programmer's (c) the DBMS's (d) the database administrator's Correct answer is (c) Your score on this question is: 14.29 Feedback: (c) 6. A database is needed for which of the following application scenarios? 13 A video store that needs to keep track of data about members, about videos carried by the store, about videos rented by members, as well as data concerning borrow-date, return-date, and payment information. 14 In the human resources department of a company, information about employees, their titles, their salaries and sick days, and about vacation days taken by each employee. 15 A computer-simulated video game which needs to calculate and display, the physical (x, y) location of each actor in the game, the speed with which they are moving at the current instant, the direction in which they are moving, the action they are performing, the angle at which the game-player is viewing the scene. (a) I only (b) I, II, and III (c) I and II only (d) I and III only Correct answer is (c) Your score on this question is: 14.29 Feedback: (c) 7. The physical storage structure will be _____ to the application programmer in a database approach, and will be _____ to the application programmer in a file system approach. (a) hidden, hidden (b) hidden, visible (c) visible, visible (d) visible, hidden Correct answer is (b) Your score on this question is: 14.29 Feedback: The layer of abstraction offered by a DBMS hides the physical storage structure from the application programmer. (b) Go to top of assessment. Total score: 100.00 Your performance was as follows: You took 3 minutes on this assessment from Tue Mar 17 04:27:27 UTC+0800 2009 to Tue Mar 17 04:30:02 UTC+0800 2009. Total score: 85.71 1. An E-Commerce system consists of the following components. Which of these same components must be included in a database? 1 The data, such as information about the goods available for sale, customers, orders placed, shipping information, etc. 2 A database must include a collection of programs that control the data, such as programs to create, maintain, and manipulate the data. These programs can be easily used to create, maintain, and manipulate data in other domains. 3 A database must include a collection of programs that operate on the data, but are specific to the E-commerce system. These programs enable users to browse through the store-items, place orders, track shipping, etc. (a) II only (b) I and II only (c) I only (d) I, II, and III Correct answer is (c) Your score on this question is: 14.29 Feedback: Database refers to just the data (c) 2. In a database system, whose responsibility is it to provide data consistency? (a) the database administrator's (b) the user's (c) the application programmer's (d) the DBMS's Correct answer is (d) Your score on this question is: 14.29 Feedback: (d) 3. An E-Commerce system consists of the following components. Which of these same components will constitute a database system? 4 The data, such as information about the goods available for sale, customers, orders placed, shipping information, etc. 5 A collection of programs that control the data, such as programs to create, maintain, and manipulate the data constitutes a database system. These programs can be easily used to create, maintain, and manipulate data in other domains such as in a library information system. 6 A collection of programs that operate on the data, but are specific to the E-commerce system, constitutes a database system. These programs enable users to browse through the store-items, place orders, track shipping, etc. (a) I, II, and III (b) I only (c) I and II only (d) II only Correct answer is (a) Your score on this question is: 14.29 Feedback: A database system includes the data, the DBMS, and the application-specific programs that operate on that data. (a) 4. An E-Commerce system consists of the following components. Which of the same components must be included in a database management system? 7 The data, such as information about the goods available for sale, customers, orders placed, shipping information, etc. 8 A collection of programs must be included that control the data, such as programs to create, maintain, and manipulate the data. These programs can be easily used to create, maintain, and manipulate data in other domains, such as in a library information system. 9 A collection of programs that operate on the data, but are specific to the E-commerce system. These programs enable users to browse through the store-items, place orders, track shipping, etc. (a) I only (b) I, II, and III (c) II only (d) II and III only Correct answer is (c) Your score on this question is: 0.00 Feedback: A DBMS refers to just the set of general-purpose programs to control data. (d) 5. An E-Commerce database contains data about customers, products, orders, system response times, etc. Which of the following can be specified as integrity constraints in an E-Commerce database system? 10 No two products can have the same product ID. 11 The DBMS response time for all Web requests should be at most 2 seconds. 12 A customer order cannot have more than one shipping address. (a) I, II, and III (b) I only (c) I and II only (d) I and III only Correct answer is (d) Your score on this question is: 14.29 Feedback: The constraints I, II and III specify the application semantics of the data captured in the E-Commerce database. Constraint II, although it seems contrary to common sense, is not something that can be prohibited by the DBMS because the DBMS is general purpose. The response time of the DBMS cannot be enforced by the DBMS. It depends on factors such the processor speed, memory available, etc. (d) 6. A database is needed for which of the following application scenarios? 13 A video store that needs to keep track of data about members, about videos carried by the store, about videos rented by members, as well as data concerning borrow-date, return-date, and payment information. 14 In the human resources department of a company, information about employees, their titles, their salaries and sick days, and about vacation days taken by each employee. 15 A computer-simulated video game which needs to calculate and display, the physical (x, y) location of each actor in the game, the speed with which they are moving at the current instant, the direction in which they are moving, the action they are performing, the angle at which the game-player is viewing the scene. (a) I and II only (b) I only (c) I, II, and III (d) I and III only Correct answer is (a) Your score on this question is: 14.29 Feedback: (a) 7. The physical storage structure will be _____ to the application programmer in a database approach, and will be _____ to the application programmer in a file system approach. (a) visible, hidden (b) hidden, hidden (c) hidden, visible (d) visible, visible Correct answer is (c) Your score on this question is: 14.29 Feedback: The layer of abstraction offered by a DBMS hides the physical storage structure from the application programmer. (c) Go to top of assessment. Total score: 85.71 Total score: 42.86 1. An E-Commerce system consists of the following components. Which of these same components must be included in a database? 1 The data, such as information about the goods available for sale, customers, orders placed, shipping information, etc. 2 A database must include a collection of programs that control the data, such as programs to create, maintain, and manipulate the data. These programs can be easily used to create, maintain, and manipulate data in other domains. 3 A database must include a collection of programs that operate on the data, but are specific to the E-commerce system. These programs enable users to browse through the store-items, place orders, track shipping, etc. (a) I and II only (b) I only (c) II only (d) I, II, and III Correct answer is (b) Your score on this question is: 14.29 Feedback: Database refers to just the data (b) 2. In a database system, whose responsibility is it to provide data consistency? (a) the DBMS's (b) the user's (c) the application programmer's (d) the database administrator's Correct answer is (a) Your score on this question is: 0.00 Feedback: (d) 3. An E-Commerce system consists of the following components. Which of these same components will constitute a database system? 4 The data, such as information about the goods available for sale, customers, orders placed, shipping information, etc. 5 A collection of programs that control the data, such as programs to create, maintain, and manipulate the data constitutes a database system. These programs can be easily used to create, maintain, and manipulate data in other domains such as in a library information system. 6 A collection of programs that operate on the data, but are specific to the E-commerce system, constitutes a database system. These programs enable users to browse through the store-items, place orders, track shipping, etc. (a) II only (b) I and II only (c) I, II, and III (d) I only Correct answer is (c) Your score on this question is: 0.00 Feedback: A database system includes the data, the DBMS, and the application-specific programs that operate on that data. (a) 4. An E-Commerce system consists of the following components. Which of the same components must be included in a database management system? 7 The data, such as information about the goods available for sale, customers, orders placed, shipping information, etc. 8 A collection of programs must be included that control the data, such as programs to create, maintain, and manipulate the data. These programs can be easily used to create, maintain, and manipulate data in other domains, such as in a library information system. 9 A collection of programs that operate on the data, but are specific to the E-commerce system. These programs enable users to browse through the store-items, place orders, track shipping, etc. (a) I, II, and III (b) II only (c) I only (d) II and III only Correct answer is (b) Your score on this question is: 0.00 Feedback: A DBMS refers to just the set of general-purpose programs to control data. (d) 5. An E-Commerce database contains data about customers, products, orders, system response times, etc. Which of the following can be specified as integrity constraints in an E-Commerce database system? 10 No two products can have the same product ID. 11 The DBMS response time for all Web requests should be at most 2 seconds. 12 A customer order cannot have more than one shipping address. (a) I only (b) I and III only (c) I and II only (d) I, II, and III Correct answer is (b) Your score on this question is: 0.00 Feedback: The constraints I, II and III specify the application semantics of the data captured in the E-Commerce database. Constraint II, although it seems contrary to common sense, is not something that can be prohibited by the DBMS because the DBMS is general purpose. The response time of the DBMS cannot be enforced by the DBMS. It depends on factors such the processor speed, memory available, etc. (d) 6. A database is needed for which of the following application scenarios? 13 A video store that needs to keep track of data about members, about videos carried by the store, about videos rented by members, as well as data concerning borrow-date, return-date, and payment information. 14 In the human resources department of a company, information about employees, their titles, their salaries and sick days, and about vacation days taken by each employee. 15 A computer-simulated video game which needs to calculate and display, the physical (x, y) location of each actor in the game, the speed with which they are moving at the current instant, the direction in which they are moving, the action they are performing, the angle at which the game-player is viewing the scene. (a) I only (b) I and II only (c) I, II, and III (d) I and III only Correct answer is (b) Your score on this question is: 14.29 Feedback: (b) 7. The physical storage structure will be _____ to the application programmer in a database approach, and will be _____ to the application programmer in a file system approach. (a) visible, visible (b) visible, hidden (c) hidden, visible (d) hidden, hidden Correct answer is (c) Your score on this question is: 14.29 Feedback: The layer of abstraction offered by a DBMS hides the physical storage structure from the application programmer. (c) Go to top of assessment. The arity of a table is the number of _____ in the table. (a) rows (b) columns (c) keys (d) foreign keys Correct answer is (b) Your score on this question is: 10.00 Feedback: 2. The cardinality of a table is the number of _____ in the table. (a) rows (b) foreign keys (c) keys (d) columns Correct answer is (a) Your score on this question is: 10.00 Feedback: 3. The degree of a table is the number of _____ in the table. (a) rows (b) columns (c) foreign keys (d) keys Correct answer is (b) Your score on this question is: 10.00 Feedback: 4. The foreign key in a table T1 _____ the same _____ as the corresponding primary key in table T2. 1 must have, name 2 need not have, name 3 must have, domain (a) I and III (b) II and III (c) I, II, and III (d) I and II Correct answer is (b) Your score on this question is: 10.00 Feedback: 5. The SQL clause to perform a set UNION operation is (a) MELD (b) UNITE (c) UNION (d) COMBINE Correct answer is (c) Your score on this question is: 10.00 Feedback: 6. DML is used to (a) manipulate the structure of database applications. (b) add/modify/delete data in the database. (c) specify the structure of a database. (d) add and delete tables. Correct answer is (b) Your score on this question is: 10.00 Feedback: 7. DDL is used to (a) specify the structure of a database. (b) add contents to tables. (c) access the contents of tables. (d) define the structure of database applications. Correct answer is (a) Your score on this question is: 10.00 Feedback: 8. Which of the following SQL statements can be used to create a relational table? (a) APPEND (b) CREATE (c) ADD (d) INSERT Correct answer is (b) Your score on this question is: 10.00 Feedback: 9. Which of the following SQL statements can be used to modify just one row (out of many rows) in a table? (a) CHANGE (b) UPDATE (c) ALTER (d) MODIFY Correct answer is (b) Your score on this question is: 0.00 Feedback: 10. The term query by example refers to (a) a visual query language developed by IBM (b) a query for SQL examples (c) example SQL queries provided by the DBMS that users can modify to suit their current needs (d) example SQL queries provided by other users that can be modified to suit current needs Correct answer is (a) Your score on this question is: 10.00 Feedback: See section 1.2.3 in the course notes. Your performance was as follows: You took 4 minutes on this assessment from Wed Mar 29 08:46:41 UTC+0800 2006 to Wed Mar 29 08:50:36 UTC+0800 2006. Total score: 90.00 1. What information is necessary when specifying the structure of a table? (a) the name of the table, the names of the table's attributes, the data types of attributes, and the formats of attributes (b) the name of the table, the names of the table's attributes, the data types of the table's attributes, the formats of the table's attributes, and the maximum number of rows that the table can have (c) the name of the table and the names of the table's attributes (d) the name of the table and the amount of storage space to be allocated to the table Correct answer is (a) Your score on this question is: 0.00 Feedback: 2. The cardinality of a table is the number of _____ in the table. (a) columns (b) foreign keys (c) rows (d) keys Correct answer is (c) Your score on this question is: 10.00 Feedback: 3. The arity of a table is the number of _____ in the table. (a) foreign keys (b) keys (c) rows (d) columns Correct answer is (d) Your score on this question is: 10.00 Feedback: 4. The degree of a table is the number of _____ in the table. (a) rows (b) foreign keys (c) columns (d) keys Correct answer is (c) Your score on this question is: 10.00 Feedback: 5. A difference operation can be applied to tables that (a) are union compatible (b) have the same name (c) are the same size (d) have the same column names Correct answer is (a) Your score on this question is: 10.00 Feedback: 6. Which of the following SQL statements can be used to remove a row from a table? (a) DESTROY (b) DELETE (c) ERASE (d) REMOVE Correct answer is (b) Your score on this question is: 10.00 Feedback: 7. DML is used to (a) add/modify/delete data in the database. (b) add and delete tables. (c) manipulate the structure of database applications. (d) specify the structure of a database. Correct answer is (a) Your score on this question is: 10.00 Feedback: 8. A deletion operation will _____ if the deletion leads to the violation of a referential integrity constraint. (a) fail (b) succeed with warning (c) succeed without warning (d) crash the system Correct answer is (a) Your score on this question is: 10.00 Feedback: 9. DDL is used to (a) access the contents of tables. (b) add contents to tables. (c) define the structure of database applications. (d) specify the structure of a database. Correct answer is (d) Your score on this question is: 10.00 Feedback: 10. With Query By Example, a user enters a query by (a) writing an English description of the data that the user needs (b) typing a syntactically correct SQL query that uses column and table names similar to the correct column and table names in a database (c) filling in skeleton tables of the database with examples of what is to be retrieved (d) placing SQL keywords, such as select, under the column names they want to retrieve Correct answer is (c) Your score on this question is: 10.00 1. What information is necessary when specifying the structure of a table? (a) the name of the table, the names of the table's attributes, the data types of attributes, and the formats of attributes (b) the name of the table, the names of the table's attributes, the data types of the table's attributes, the formats of the table's attributes, and the maximum number of rows that the table can have (c) the name of the table and the names of the table's attributes (d) the name of the table and the amount of storage space to be allocated to the table Correct answer is (a) Your score on this question is: 0.00 Feedback: 2. The cardinality of a table is the number of _____ in the table. (a) columns (b) foreign keys (c) rows (d) keys Correct answer is (c) Your score on this question is: 10.00 Feedback: 3. The arity of a table is the number of _____ in the table. (a) foreign keys (b) keys (c) rows (d) columns Correct answer is (d) Your score on this question is: 10.00 Feedback: 4. The degree of a table is the number of _____ in the table. (a) rows (b) foreign keys (c) columns (d) keys Correct answer is (c) Your score on this question is: 10.00 Feedback: 5. A difference operation can be applied to tables that (a) are union compatible (b) have the same name (c) are the same size (d) have the same column names Correct answer is (a) Your score on this question is: 10.00 Feedback: 6. Which of the following SQL statements can be used to remove a row from a table? (a) DESTROY (b) DELETE (c) ERASE (d) REMOVE Correct answer is (b) Your score on this question is: 10.00 Feedback: 7. DML is used to (a) add/modify/delete data in the database. (b) add and delete tables. (c) manipulate the structure of database applications. (d) specify the structure of a database. Correct answer is (a) Your score on this question is: 10.00 Feedback: 8. A deletion operation will _____ if the deletion leads to the violation of a referential integrity constraint. (a) fail (b) succeed with warning (c) succeed without warning (d) crash the system Correct answer is (a) Your score on this question is: 10.00 Feedback: 9. DDL is used to (a) access the contents of tables. (b) add contents to tables. (c) define the structure of database applications. (d) specify the structure of a database. Correct answer is (d) Your score on this question is: 10.00 Feedback: 10. With Query By Example, a user enters a query by (a) writing an English description of the data that the user needs (b) typing a syntactically correct SQL query that uses column and table names similar to the correct column and table names in a database (c) filling in skeleton tables of the database with examples of what is to be retrieved (d) placing SQL keywords, such as select, under the column names they want to retrieve Correct answer is (c) The cardinality of a table is the number of _____ in the table. (a) rows (b) keys (c) foreign keys (d) columns Correct answer is (a) Your score on this question is: 10.00 Feedback: 2. The foreign key in a table T1 _____ the same _____ as the corresponding primary key in table T2. 1 must have, name 2 need not have, name 3 must have, domain (a) I and II (b) I, II, and III (c) II and III (d) I and III Correct answer is (c) Your score on this question is: 10.00 Feedback: 3. What information is necessary when specifying the structure of a table? (a) the name of the table and the names of the table's attributes (b) the name of the table, the names of the table's attributes, the data types of attributes, and the formats of attributes (c) the name of the table, the names of the table's attributes, the data types of the table's attributes, the formats of the table's attributes, and the maximum number of rows that the table can have (d) the name of the table and the amount of storage space to be allocated to the table Correct answer is (b) Your score on this question is: 10.00 Feedback: 4. The arity of a table is the number of _____ in the table. (a) columns (b) foreign keys (c) keys (d) rows Correct answer is (a) Your score on this question is: 10.00 Feedback: 5. A difference operation can be applied to tables that (a) are union compatible (b) are the same size (c) have the same name (d) have the same column names Correct answer is (a) Your score on this question is: 10.00 Feedback: 6. What can be specified in the selection condition of a SELECT statement? (a) a Boolean operation (b) an arithmetic operation (c) the conditions under which the statement should be executed (d) the time at which the selection should be performed Correct answer is (a) Your score on this question is: 0.00 Feedback: 7. The SQL clause to perform a set UNION operation is (a) MELD (b) UNION (c) UNITE (d) COMBINE Correct answer is (b) Your score on this question is: 10.00 Feedback: 8. Which of the following SQL statements can be used to add a row to a table? (a) APPEND (b) CREATE (c) ADD (d) INSERT Correct answer is (d) Your score on this question is: 10.00 Feedback: 9. A join operation joins _____ tables into _____. (a) two, one (b) four, two (c) three, one (d) three, two Correct answer is (a) Your score on this question is: 10.00 Feedback: 10. With Query By Example, a user enters a query by (a) placing SQL keywords, such as select, under the column names they want to retrieve (b) writing an English description of the data that the user needs (c) typing a syntactically correct SQL query that uses column and table names similar to the correct column and table names in a database (d) filling in skeleton tables of the database with examples of what is to be retrieved Correct answer is (d) Your score on this question is: 10.00 The degree of a table is the number of _____ in the table. (a) foreign keys (b) columns (c) rows (d) keys Correct answer is (b) Your score on this question is: 10.00 Feedback: 2. The arity of a table is the number of _____ in the table. (a) rows (b) keys (c) columns (d) foreign keys Correct answer is (c) Your score on this question is: 10.00 Feedback: 3. What information is necessary when specifying the structure of a table? (a) the name of the table and the amount of storage space to be allocated to the table (b) the name of the table and the names of the table's attributes (c) the name of the table, the names of the table's attributes, the data types of the table's attributes, the formats of the table's attributes, and the maximum number of rows that the table can have (d) the name of the table, the names of the table's attributes, the data types of attributes, and the formats of attributes Correct answer is (d) Your score on this question is: 10.00 Feedback: 4. The cardinality of a table is the number of _____ in the table. (a) foreign keys (b) columns (c) keys (d) rows Correct answer is (d) Your score on this question is: 10.00 Feedback: 5. DML is used to (a) specify the structure of a database. (b) add and delete tables. (c) manipulate the structure of database applications. (d) add/modify/delete data in the database. Correct answer is (d) Your score on this question is: 10.00 Feedback: 6. The SQL clause to perform a set UNION operation is (a) COMBINE (b) UNION (c) UNITE (d) MELD Correct answer is (b) Your score on this question is: 10.00 Feedback: 7. Which of the following SQL statements can be used to create a relational table? (a) ADD (b) APPEND (c) CREATE (d) INSERT Correct answer is (c) Your score on this question is: 10.00 Feedback: 8. DDL is used to (a) access the contents of tables. (b) specify the structure of a database. (c) add contents to tables. (d) define the structure of database applications. Correct answer is (b) Your score on this question is: 10.00 Feedback: 9. What can be specified in the selection condition of a SELECT statement? (a) the time at which the selection should be performed (b) an arithmetic operation (c) the conditions under which the statement should be executed (d) a Boolean operation Correct answer is (d) Your score on this question is: 10.00 Feedback: 10. The term query by example refers to (a) a query for SQL examples (b) example SQL queries provided by other users that can be modified to suit current needs (c) a visual query language developed by IBM (d) example SQL queries provided by the DBMS that users can modify to suit their current needs Correct answer is (c) Your score on this question is: 10.00 Feedback: See section 1.2.3 in the course notes. Go to top of assessment. Your performance was as follows: 1. What information is necessary when specifying the structure of a table? (a) the name of the table, the names of the table's attributes, the data types of attributes, and the formats of attributes (b) the name of the table and the amount of storage space to be allocated to the table (c) the name of the table and the names of the table's attributes (d) the name of the table, the names of the table's attributes, the data types of the table's attributes, the formats of the table's attributes, and the maximum number of rows that the table can have Correct answer is (a) Your score on this question is: 10.00 Feedback: (a) 2. The foreign key in a table T1 _____ the same _____ as the corresponding primary key in table T2. 1 must have, name 2 need not have, name 3 must have, domain (a) I and II (b) II and III (c) I and III (d) I, II, and III Correct answer is (b) Your score on this question is: 10.00 Feedback: (b) 3. The arity of a table is the number of _____ in the table. (a) foreign keys (b) rows (c) keys (d) columns Correct answer is (d) Your score on this question is: 10.00 Feedback: (d) 4. The cardinality of a table is the number of _____ in the table. (a) keys (b) columns (c) rows (d) foreign keys Correct answer is (c) Your score on this question is: 10.00 Feedback: (c) 5. Which of the following SQL statements can be used to create a relational table? (a) INSERT (b) ADD (c) CREATE (d) APPEND Correct answer is (c) Your score on this question is: 10.00 Feedback: (c) 6. The SQL clause to perform a set difference operation is (a) EXCEPT (b) OMIT (c) DIFFER (d) REJECT Correct answer is (a) Your score on this question is: 10.00 Feedback: (a) 7. Which of the following SQL statements can be used to remove a row from a table? (a) ERASE (b) REMOVE (c) DESTROY (d) DELETE Correct answer is (d) Your score on this question is: 10.00 Feedback: (d) 8. Which of the following SQL statements can be used to add a row to a table? (a) ADD (b) APPEND (c) CREATE (d) INSERT Correct answer is (d) Your score on this question is: 10.00 Feedback: (d) 9. What can be specified in the selection condition of a SELECT statement? (a) the time at which the selection should be performed (b) a Boolean operation (c) an arithmetic operat
JSP Simple Examples Index 1. Creating a String In jsp we create a string as we does in a java. In jsp we can declare it inside the declaration directive or a scriptlet directive. String Length In java, Strings are objects that belong to class java.lang.String. A string is a sequence of simple characters. We can get the length of the string by using the method length() of java.lang.String. Declaring string array in java An array is the collection of same data type. Suppose if we have a declare an array of type String, then it will store only the String value not any other data type. When we have a closely related data of the same type and scope, it is better to declare it in an array. Multidimensional array java A two dimensional array can be thought as a grid of rows and columns. The first array will reflect to a row and the second one is column. int array Array is a collection of same data type. Suppose if we have declared an array of type int then the array will take only the int values and not any other data types. We can find find out the length of the variable by using the variable length . JSP string array String array cannot hold numbers or vice- versa. Arrays can only store the type of data specified at the time of declaring the array variable. Custom exceptions Custom Exception inherits the properties from the Exception class. Whenever we have declare our own exceptions then we call it custom exceptions. Throwing an exception All methods use the throw statement to throw an exception. The throw statement requires a single argument a throwable object. Here is an example of a throw statement. Arrayindexoutofboundsexception ArrayIndexOutOfBoundException is thrown when we have to indicate that an array has been accessed with an illegal index. printStackTrace in jsp printStackTrace is a method of the Throwable class. By using this method we can get more information about the error process if we print a stack trace from the exception. Runtime Errors Errors are arised when there is any logic problem with the logic of the program. Try catch in jsp In try block we write those code which can throw exception while code execution and when the exception is thrown it is caught inside the catch block. Multiple try catch We can have more than one try/catch block. The most specific exception which can be thrown is written on the top in the catch block following by the less specific least. Nested try catch We can declare multiple try blocks inside the try block. The most specific exception which can be thrown is written on the top in the catch block following by the less specific least. kilometers per liter to miles per gallon Kilometers per liter : The distance traveled by a vehicle which is running on gasoline or diesel fuel in a kilometer. Miles per Gallon: The distance traveled by a vehicle which is running on gasoline or diesel fuel in a mile. Ascii values table ASCII stands for American Standard Code for Information Interchange. Computers can only understand numbers, so an ASCII code is the numerical representation of a character such as @, #, $, and so on. ASCII was developed when non- printing characters were rarely used. life cycle of a jsp page Life of the the jsp page is just same as the servlet life cycle. After get translated the jsp file is just like a servlet. Page directive attributes A directive is a way to give special instructions to the container at page translation time. The page directive is written on the top of the jsp page. Html tags in jsp In this example we have used the html tag inside the println() method of the out implicit object which is used to write the content on the browser. Password Controls In this program we are going to know how the server determines whether the password entered by the user is correct or not. This whole process is controlled on the server side. Multiple forms in jsp The form tag creates a form for user input. A form can contain checkboxes, textfields, radio- buttons and many more. Forms are used to pass user- data to a specified URL which is specified in the action attribute of the form tag. Interface in jsp In interface none of its methods are implemented. All the methods are abstract. There is no code associated with an interface. In an interface all the instance methods are public and abstract. Interfaces are always implemented in the class. They add extra behaviors to the class. Inheritance in java with example Inheritance is one of the concept of the Object- Oriented programming. It allows you to define a general class, and later more specialized classes by simply adding some new details. Constructor inheritance Constructors are used to create objects from the class. Constructor declaration are just like method declaration, except that they do not have any return type and they use the name of the class. The compiler provides us with a default constructor to the class having no arguments. Abstract classes We does not make a object of the abstract class. This class must be inherited. Unlike interface the abstract class may implement some of the methods defined in the class, but in this class at least one method should be abstract. Using Super class Variables With Sub-classed Objects One of the strong features of java is that it is follows a OOPs concept, and one of the feature of OOP in java is that, we can assign a subclass object or variable to the variable of the superclass type. Log files Log files keeps a records of internet protocol addresses (IP), Http status, date, time, bytes sent, bytes recieved, number of clicks etc. Calculate a factorial by using while loop In this example we are going to find out the factorial of 12 by using the while loop. In while loop the loop will run until the condition we have given gets true. Calculating factorial After going through this example you will be understand how you can calculate the factorial by using recursion in jsp. To make a program on factorial, firstly it must be clear what is recursion. Celsius Fahrenheit Celsius is a unit to measure temperature scale on which water freezes at 0 degree and boiling point is 100 degree. This unit is discovered by Celsius in 1742, a Swedish astronomer and physicist, he has invented the centigrade, or Celsius thermometer divided between the freezing and boiling points of water into 100 parts. comment in jsp In a jsp we should always try to use jsp- style comments unless you want the comments to appear in the HTML. Jsp comments are converted by the jsp engine into java comments in the source code of the servlet that implements the Jsp page. Html tag inside out implicit object In this program we are going to use a html tag inside a out object. out object is used to display the content on the browser. To make this program run use out object inside which define some html code along with the content you want to display on the browser Jsp methods In this example we are going to show you how we can declare a method and how we can used it. In this example we are making a method named as addNum(int i, int b) which will take two numbers as its parameters and return integer value. Multiple methods Jsp is used mainly for presentation logic. In the jsp we can declare methods just like as we declare methods in java classes. Methods can be declared in either declaration directive or we can declare it in scriptlet. If we declare method inside declaration directive, then the method is applicable in the whole page. Passing Array method Array is a collection of similar data type. It is one of the simplest data structures. Arrays holds equally sized data elements generally of the similar data type. Two index In this example we will show how we can use two indexes in a for loop. We can solve this problem by using for loop defined inside the scriptlet directive. Date in JSP To print a Date in JSP firstly we are importing a class named java.util.Date of the package java.util. This package is imported in the jsp page so that the Date class and its properties can accessed in the JSP page. If- Else Ladder A ladder means a vertical set of steps. It is a computer generated list of pairings used in eliminations. Nested If We use the if condition to check if the particular condition is true then it should perform a certain task, and if a particular condition is not true then it should do some other tasks. Quintessential JSP Quintessential means representing the perfect example of a class or quality. It is pure and concentrated essence of a substance. Include File JSP using directive and include action <%@ include file = " "%>: - This is include directive. This directive has only one attribute named as file, which is used to include a file in the jsp page at the translation time. :- This is known as the include standard action. This standard action is used to include a file at run time. This standard action is evaluated at the run time. Snoop in JSP It mostly contains the request information, ServletContext initialization parameters, ServetContext attributes, request headers, response headers etc. sendRedirect In JSP sendRedirect() method is a method of HttpServletResponse interface. In sendRedirect() the object of request will be generated again with the location of page which will perform the request of the client. Request Header in JSP Whenever an http client sends a request, it sends the request in the form of get or post method or any other HttpRequest methhods. It can also sends the headers with it. Specific request headers in JSP Whenever an http client sends a request, it can also sends the headers with it. All the headers are optional except Content-length, which is required only for POST request. Java class in JSP To use the class inside the jsp page we need to create an object of the class by using the new operator. At last use the instance of the class to access the methods of the java file. Setting Colors in JSP In Jsp also we can set the background color which we want, the font color can be changed. The table can be coloured . By using the colors code we can give colors according to our wish. Sine Table in JSP Mathematically, the sine of an angle is the ratio of the length of the opposite side to the length of the hypotenuse of an imaginary right triangle having that angle in it. Applet In Jsp Applets are small programs or applications written in java. These applets are those small programs that runs on web browsers, usually written in java. We can use the applets in jee also. In jee it runs on the context of web application on a client computer. Creating a Local Variable in JSP Consider a situation where we have to declare a variable as local, then we should declare the methods and variables in tag except the declaration directive. Method in Declaration Tag Anything which will be declared inside declaration tag will be applicable within the whole application. We call this tag a Declaration Tag. The syntax of this tag is <%! --------- %>. Forward a JSP Page The request object goes to the controller then the controller decides by which jsp or servlet this request will be processed, then the request object is passed to that jsp or servlet and the output is displayed to the browser by the response object. Random in JSP Random numbers are the numbers that are determined entirely by chance. User does not have any control over the working of random numbers. random() is a method of Math class which extends java.lang package. JSP include directive By using the include tag the file will be included in the jsp page at the translation time. In this example we have created a jsp file which has to be included in the other jsp file by using the tag <%@ include file = " "%>. Literals in JSP Literals are the values, such as a number or a text string, that are written literally as part of a program code. A literal is a expression of a value, including a number or a text string. Passing Parameter using Request parameters can be passed by using . This tag contains two attributes: 1) name 2) value. Tag Handler Custom tags are usually distributed in the form of a tag library, which defines a set of related custom tags and contains the objects that implement the tags. Custom tag libraries allow the java programmer to write code that provides data access and other services, and they make those features available to the jsp author in a simple to use XML- like fashion. UseBean Syntax: Server Error in '/' Application.-------------------------------------------------------------------------------- Column 'C' does not belong to table Table. Description: An unhandled exception occurr...

62,047

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧