Tasks for Installation / Introduction Concepts. 1. What are the Advantages of SQL Server? Data Integrity

Similar documents
ColumnStore Indexes UNIQUE and NOT DULL

Exact Numeric Data Types

Department of Computer Science University of Cyprus. EPL342 Databases. Lab 1. Introduction to SQL Server Panayiotis Andreou

Lab 4: Tables and Constraints

Constraints. Primary Key Foreign Key General table constraints Domain constraints Assertions Triggers. John Edgar 2

Building Better. SQL Server Databases

Documentation Accessibility. Access to Oracle Support. Supported Browsers

New Features Bulletin Replication Server Options 15.6

Angela Henry. Data Types Do Matter

Tables. Tables. Physical Organization: SQL Server Partitions

Physical Organization: SQL Server 2005

Ebook : Overview of application development. All code from the application series books listed at:

Introduction to SQL Server 2005/2008 and Transact SQL

5. SQL Query Syntax 1. Select Statement. 6. CPS: Database Schema

Configuring the Oracle Network Environment. Copyright 2009, Oracle. All rights reserved.

SQL Server 2014 Column Store Indexes. Vivek Sanil Microsoft Sr. Premier Field Engineer

Survey of the Azure Data Landscape. Ike Ellis

Get Table Schema In Sql Server 2005 Modify. Column Datatype >>>CLICK HERE<<<

Intelligent Caching in Data Virtualization Recommended Use of Caching Controls in the Denodo Platform

SQL Coding Guidelines

Course Topics. Microsoft SQL Server. Dr. Shohreh Ajoudanian. 01 Installing MSSQL Server Data types

Information Systems Engineering. SQL Structured Query Language DDL Data Definition (sub)language

FLAT DATACENTER STORAGE CHANDNI MODI (FN8692)

Alter Changes Default Schema Sql Server 2008 R2 Replicate

TRIM Integration with Data Protector

Get Table Schema In Sql Server 2005 Modify. Column Size >>>CLICK HERE<<<

ColdFusion Summit 2016

System Pages (Setup Admins Only)

T-sql Check If Index Exists Information_schema

6 Months Training Module in MS SQL SERVER 2012

In-Memory Tables and Natively Compiled T-SQL. Blazing Speed for OLTP and MOre

Building Better. SQL Server Databases

Jet Data Manager 2014 SR2 Product Enhancements

Number: Passing Score: 800 Time Limit: 120 min File Version:

About System Setup Pages

Replication. Some uses for replication:

Code Centric: T-SQL Programming with Stored Procedures and Triggers

1. SQL Overview. Allows users to access data in the relational database management systems.

Manual Trigger Sql Server 2008 Update Inserted Rows

Basis Data Terapan. Yoannita

IBM DB2 UDB V7.1 Family Fundamentals.

Developing Microsoft Azure Solutions (70-532) Syllabus

Microsoft Developing Microsoft SQL Server 2012 Databases. Download Full Version :

Exam Questions

Introduction to IBM DB2

CAST(HASHBYTES('SHA2_256',(dbo.MULTI_HASH_FNC( tblname', schemaname'))) AS VARBINARY(32));

Welcome to the presentation. Thank you for taking your time for being here.

BEGINNING T-SQL. Jen McCown MidnightSQL Consulting, LLC MinionWare, LLC

Mobile Data Management Structure Design based on Mobile Database

Sql Server 2008 Query Table Schema Management Studio Create

Ms Sql Server 2008 R2 Check If Temp Table Exists

Scalable Shared Databases for SQL Server 2005

COURSE 10977A: UPDATING YOUR SQL SERVER SKILLS TO MICROSOFT SQL SERVER 2014

Datacenter replication solution with quasardb

Introduction to Databases and SQL

Developing Microsoft Azure Solutions (70-532) Syllabus

Teiid - Scalable Information Integration. Teiid Caching Guide 7.6

TempDB how it works? Dubi Lebel Dubi Or Not To Be

Get Table Schema In Sql Server 2008 To Add Column If Not Exists >>>CLICK HERE<<<

Manual Trigger Sql Server 2008 Insert Multiple Rows At Once

MySQL 5.1 Past, Present and Future MySQL UC 2006 Santa Clara, CA

Guide to Mitigating Risk in Industrial Automation with Database

Maintenance Guide.

DATABASE SYSTEMS. Database programming in a web environment. Database System Course, 2016

System Environment of the Database Engine

SQL Fundamentals. Chapter 3. Class 03: SQL Fundamentals 1

Field Testing Buffer Pool Extension and In-Memory OLTP Features in SQL Server 2014

SQL Server 2014 Training. Prepared By: Qasim Nadeem

A Practical Guide to Migrating from Oracle to MySQL. Robin Schumacher

Best Practices. Deploying Optim Performance Manager in large scale environments. IBM Optim Performance Manager Extended Edition V4.1.0.

Log Manager. Introduction

Db2 Alter Table Alter Column Set Data Type Char

RDBMS Basics: What Makes Up a SQL Server Database?

Introduction. Storage Failure Recovery Logging Undo Logging Redo Logging ARIES

Course Description. Audience. Prerequisites. At Course Completion. : Course 40074A : Microsoft SQL Server 2014 for Oracle DBAs

About the Tutorial. Audience. Prerequisites. Compile/Execute SQL Programs. Copyright & Disclaimer SQL

IBM EXAM QUESTIONS & ANSWERS

Daily, Weekly or Monthly Partitions? A discussion of several factors for this important decision

SQL Data Definition Language: Create and Change the Database Ray Lockwood

Lab # 4. Data Definition Language (DDL)

How to Migrate Microsoft SQL Server Connections from the OLE DB to the ODBC Provider Type

DESIGNING DATABASE SOLUTIONS FOR MICROSOFT SQL SERVER CERTIFICATION QUESTIONS AND STUDY GUIDE

SQL Server 2014: In-Memory OLTP for Database Administrators

TINYINT[(M)] [UNSIGNED] [ZEROFILL] A very small integer. The signed range is -128 to 127. The unsigned range is 0 to 255.

Sql Server Check If Global Temporary Table Exists

Drop Users Syntax In Sql Server 2000 Orphaned

SearchWinIT.com SearchExchange.com SearchSQLServer.com

Jeffrey Garbus. ASE Administration. SAP* ASE 16/Sybase. 9 Rheinwerk. Publishing. Bonn Boston

1Z0-526

How to speed up a database which has gotten slow

Manual Triggers Sql Server 2008 Examples

Change Schema For All Tables In Sql Server 2008

HOW TO CREATE AND MAINTAIN DATABASES AND TABLES. By S. Sabraz Nawaz Senior Lecturer in MIT FMC, SEUSL

Changes Schema Of Table Procedure Sql 2008 R2 Replication

Course 6231A: Maintaining a Microsoft SQL Server 2008 Database

Teiid - Scalable Information Integration. Teiid Caching Guide 7.2

GETTING 1 STARTED. Chapter SYS-ED/ COMPUTER EDUCATION TECHNIQUES, INC.

Enzo Framework Developer Guide

Overview Architecture Sample

Was ist dran an einer spezialisierten Data Warehousing platform?

Transcription:

Tasks for Installation / Introduction Concepts 1. What are the Advantages of SQL Server? Data Integrity Data integrity in SQL Server is enhanced by the use of 'triggers' which can be applied whenever a record is added, updated or deleted. This occurs at the table level and cannot thus be forgotten about, ignored or bypassed by the client machine. For example audit processes cannot be avoided (accidentally or deliberately) with this scenario. Performance With Access all tables involved in a form, report or a query are copied across the network from the server to the client's machine. The tables are then processed and filtered to generate the required recordset. For example if looking up details for one particular order from an orders table containing, say, 50,000 records then the whole table (all 50,000 records) is dragged over the network and then 49,999 of these records are thrown away (this is an over-simplification since indexing can be used to mitigate this to some extent). Contrast this with SQL Server where the filtering takes place on the server (if designed properly) and only 1 record is transmitted over the network. This can affect performance in two ways. Firstly SQL Server is highly optimised and can usually perform the required filtering much more quickly than the client machine and secondly the amount of data sent across the network link is vastly reduced. For most databases the main performance bottleneck is data transmission over the network hence reducing this can give a really dramatic improvement in performance. Predicting likely performance improvements is very difficult but an average overall speed improvement of 3 to 5 times, and possibly much more, would not be unexpected. Network Traffic As can be seen from the previous section, network traffic is greatly reduced in a client/server scenario, often by many orders of magnitude. This both improves network reliability (by reducing collisions, etc.) and also improves the performance of the network for other software (as there is less traffic on the network). Where there is a slow connection, such as over a telephone dial-up, Access is usually so slow as to be all but unusable (obviously this does depend upon the amount of data) whereas a SQL Server application, if designed for this environment, can still be perfectly useable. Low Bandwidth This occurs when you are accessing your database over a connection that only supports low data speeds, which, for all practical situations, means anything other than a LAN. In all low bandwidth situations Access/JET usually performs so slowly as to be unusable whilst a correctly designed SQL Server system can be similar in speed to running it over a LAN. The main low bandwidth situations are: Dial-up

Allowing remote salesmen, off-site workers, home workers, out of hours users and the like to dial into the network over the normal telephone lines. Most file server databases are completely unusable over dial-up unless some additional technology, such as Terminal Server, is used (and this brings it's own complications). WAN If you want to link more than one site to a database then typically you would use a WAN (Wide Area Network). Irrespective of the communications technology used (which would usually be leased line, VPN {Virtual Private Network} or ISDN), WANs tend to have a low bandwidth compared to LANs and in addition are often heavily loaded with traffic. Traditional file server databases do not work well over a WAN and will often have both performance problems and reliability problems (owing to the less than perfect connections that most WANs provide). Internet A database that is being run over the Internet needs to be stable, scalable, able to handle heavy loads and capable of coping with failed connections; none of which are usually associated with file server database architectures. Small scale, non-critical databases can be run over the Internet but in most situations you should migrate to a client/server design. Wireless LAN These are increasingly popular and are usually fine for accessing a spreadsheet or Word document where a wired solution is inconvenient or is just not practical. However file/server databases do not usually work well over most wireless links due to the low bandwidth that they offer (even a 10Mhz wireless link will usually operate at only half of that speed or less). Scalability A file server system such as Access is designed for small workgroups and is scalable to perhaps 10 concurrent clients. Above this level performance starts to degrade rapidly as more users are added. With the SQL Server client/server architecture many hundreds, or even thousands (with the appropriate infrastructure), of concurrent users can be supported without significant performance degradation 2. What are the different Editions of SQL Server? Enterprise Edition Supports Large Enterprise level OLTP and complex environments. Standard Edition Data Management and analysis platform for small and medium sized organizations.

Developer Edition Allows developer to build any type of application on top of SQL Server. Express Edition Free, easy-to-use and simple-to-manage database solution. Workgroup Edition Data management solution for small organization that has no limits of data and users. Mobile Edition Designed exclusively to server Mobile applications. 3. What are the different SYSTEM DATABASES in SQL Server? Purpose of Each? SQL Server System Databases Master o o o Resource o o o TempDB o Purpose - Core system database to manage the SQL Server instance. In SQL Server 2005, the Master database is the logical repository for the system objects residing in the sys schema. In SQL Server 2000 and previous editions of SQL Server, the Master database physically stored all of the system objects. Prominent Functionality Per instance configurations Databases residing on the instance Files for each database Logins Linked\Remote servers Endpoints Additional Information The first database in the SQL Server startup process In SQL Server 2005, needs to reside in the same directory as the Resource database Purpose - The Resource database is responsible for physically storing all of the SQL Server 2005 system objects. This database has been created to improve the upgrade and rollback of SQL Server system objects with the ability to overwrite only this database. Prominent Functionality System object definition Additional Information Introduced in SQL Server 2005 to help manage the upgrade and rollback of system objects Prior to SQL Server 2005 the system related data was stored in the master database Read-only database that is not accessible via the SQL Server 2005 tool set The database ID for the Resource database is 32767 The Resource database does not have an entry in master.sys.databases Purpose - Temporary database to store temporary tables (#temptable or ##temptale), table variables, cursors, work tables, row versioning, create or rebuild indexes sorted in TempDB, etc. Each time the SQL Server instance is restarted all

objects in this database are destroyed, so permanent objects cannot be created in this database. o Prominent Functionality Manage temporary objects listed in the purpose above Model o Purpose - Template database for all user defined databases o Prominent Functionality Objects Columns Users o Additional Information User defined tables, stored procedures, user defined data types, etc can be created in the Model database and will exist in all future user defined databases The database configurations such as the recovery model for the Model database are applied to future user defined databases MSDB o Purpose - Primary database to manage the SQL Server Agent configurations o Prominent Functionality SQL Server Agent Jobs, Operators and Alerts DTS Package storage in SQL Server 7.0 and 2000 SSIS Package storage in SQL Server 2005 Distribution o Purpose - Primary data to support SQL Server replication o Prominent Functionality Database responsible for the replication meta data Supports the data for transaction replication between the publisher and subscriber(s) ReportServer o Purpose - Primary database for Reporting Services to store the meta data and object definitions o Prominent Functionality Reports security Job schedules and running jobs Report notifications Report execution history ReportServerTempDB o Purpose - Temporary storage for Reporting Services o Prominent Functionality Session information Cache System Databases Do's and Don'ts Data Access - Based on the version of SQL Server query only the recommended objects. In general the system database objects are being deprecated to a set of views, so be sure all of your scripts are accessing the right objects. If not, you are going to have a big project in the future to convert all of your scripts. Changing Objects - Do not change system objects. In SQL Server 2005 all of the database objects have been moved to the Resource database which stores the definition for the system objects and can be updated via new SQL Server releases independent of the data.

New Objects - Creating objects in the system databases is not recommended. If you have objects that are needed for the instance i.e. administrative items, just create a separate DBA database to store these objects. Sneaking a Peak - Up to this point, all of the T-SQL code for the tables, views, stored procedures, functions, etc. has been clear text. So you can review the objects and learn from the techniques used by Microsoft. Dropping Objects - The most prominent reason to drop system objects are for specific types of lock downs and auditing in particular industries. Although some of those practices are well documented, be sure you understand the ramifications related to administering and developing applications once those restrictions are in place. Security - Do not forget about the Public role and Guest user, they are the conduit for users to access the system objects. So that should answer the question of how people (logins\users) can access the objects based on the object owner or schema, depending on the SQL Server version. Backups - Be sure to have a consistent backup process for your system databases. Including the system databases with your user defined databases might be the best approach if a disaster occurs. Scope - Each SQL Server instance (including the Express Edition) has its own set of SQL Server system databases. As such, if a single Windows server has multiple SQL Server instances installed, a change to one system database only impacts the single instance, not all instances on the Windows server. 4. What are the new features in SQL Server 2014? In-Memory OLTP: which allows you to move individual tables to special in-memory structures. The performance boost can be as huge as 30x. There are a number of limitations and special requirements for these tables, so they won't work under every circumstance. But when they do, your OLTP performance will go through the roof. This is better than other in-memory solutions that require the entire database to be placed in memory. You can get more performance by converting existing stored procedures into in-memory procedures, too. You'll need to test to make sure your tables are compatible Managed Backup to Azure: Managed Backup automatically backs up your database (or your instance) based on your defined recovery interval and workload patterns. When the system determines the data has changed significantly enough, it takes a backup to Azure. This feature only works with Azure blob storage. But since your backups are already offsite, there's no need to worry about tapes. Azure VMs for Availability replicas: With SQL Server 2014, you can define an Availability Group replica that resides in Azure. When a primary failure happens, you have to fail over manually, but you will be up and running very quickly. And as long as your primary is online you can still push your reporting to the Azure replica to offload that activity from production. If you need reliable, off-site HA but don't have a second site, then this feature is for you. Just pick the location you'd like when you create the Azure VM, and you're set. SQL Server Data Files in Azure: Data Files in Azure is just what it sounds like: Your database runs locally in your data center, while the database files themselves live in an Azure blob container. This can offer advantages in DR and migration. But depending on the size of the database and its workload, the potential performance cost

of pushing the data for every transaction across the Internet could be prohibitive. A better use of this feature may be to store the data files in an Azure VM in the same data center. This can also get you around the current limitation of having only 16 mounted disks in an Azure VM. Updateable columnstore indexes: Columnstore indexes in SQL Server 2014 brought a dramatic boost to data warehouse performance, but with a hitch: They couldn't be updated. With SQL Server 2014, now they can. This means you no longer have to drop and re-create columnstore indexes every time you need to load your warehouse tables. Not only that, but updateability also means you may be able to look at columnstore indexes for certain OLTP applications. The caveat is that you must have a clustered columnstore index on the table. Non-clustered columnstores aren't supported. Resource Governor for I/O: Disk I/O is typically the most constrained resource of a database system, and often a large or rogue query will take up more precious I/O resources than you can afford. Microsoft has finally given us some control over runaway I/O. With Resource Governor for I/O, you can now put queries into their own resource pool and limit the amount of I/O per volume they're allowed. MIN_IOPS_PER_VOLUME and MAX_IOPS_PER_VOLUME set the minimum and maximum reads or writes per second allowed by a process in a disk volume. Resource Governor I/O control, continued: MIN_IOPS_PER_VOLUME reserves a minimum number of I/O transactions per second, while MAX_IOPS_PER_VOLUME provides a maximum number. This maximum doesn't limit the number of I/O operations a query can perform, but merely keeps it from monopolizing a disk. This way your large queries can still run, but other things will run as well. A good use of I/O control is to reserve some IOPS for administrators to be able to investigate issues when the disks are overloaded. Delayed durability: In SQL Server, changes to data are written to the log first. This is called write ahead logging (WAL). Control isn't returned to the application until the log record has been written to disk (a process referred to as "hardening"). Delayed durability allows you to return control back to the application before the log is hardened. This can speed up transactions if you have issues with log performance. Nothing is free, though, and here you sacrifice recoverability. Should the database go down before the log is committed to disk, then you lose those transactions forever. It may be worth the risk if your log performance is severely degrading application response times. SSD buffer pool extension: Creating a buffer pool extension for SQL Server 2014 is like being able to define a different page file in Windows. As data pages move into memory, they begin to fill up the buffer pool. If the buffer pool fills up, the less frequently used pages will be paged to disk. Then when they're needed again, they'll be swapped with something else in the buffer pool and moved back into memory. The buffer pool extension option allows you to define an SSD as a buffer file location. Because SSD is so much faster than spinning disk, the paging is considerably quicker, which increases performance dramatically in some cases. You can define a buffer pool extension file up to 32 times the size of your memory.

Incremental statistics: Updating statistics in SQL Server is the very definition of redundant work. Whenever statistics need to be rebuilt, you can't just update the new items -- you have to update everything. This means that a table with 200 million rows and only 40 million changes will need to update all 200 million rows in order to pick up those changes. Incremental statistics in SQL Server 2014 allow you to update just those rows that have changed and merge them with what's already there. This can have a big impact on query performance in some configurations. Lock priority of online operations: You can now specify a lock priority for online reindexing. In previous versions of SQL Server, long-running queries could block reindexing operations, chewing up your maintenance window while your re-index op sits waiting, doing nothing. In SQL Server 2014, you can specify how your re-index operation will handle being blocked. You specify how long it will wait and what to do when the wait is over. Will you have it follow traditional behavior and wait indefinitely? Will you have it terminate and move to the next table? Or will you kill the blocking query, so your re-indexing can complete? It's your choice. Tasks for DB Design, Table Design and Constraints Concepts 1. What are the data types in SQL Server 2012/2014? Exact Numerics bigint bit decimal int money numeric smallint smallmoney tinyint Approximate Numerics float real Date and Time date datetime2 datetime datetimeoffset smalldatetime time Character Strings char text varchar

Unicode Character Strings nchar ntext nvarchar Binary Strings binary image varbinary Other Data Types cursor hierarchyid sql_variant table timestamp uniqueidentifier xml Spatial Types Exact Numeric Data Types: DATA TYPE FROM TO bigint - 9,223,372,036,854,775,808 9,223,372,036,854,775,807 int -2,147,483,648 2,147,483,647 smallint -32,768 32,767 tinyint 0 255 bit 0 1 decimal -10^38 +1 10^38-1 numeric -10^38 +1 10^38-1 Approximate Numeric Data Types DATA TYPE FROM TO Float -1.79E + 308 1.79E + 308 Real -3.40E + 38 3.40E + 38

Date and Time Data Types DATA TYPE FROM TO datetime Jan 1, 1753 Dec 31, 9999 smalldatetime Jan 1, 1900 Jun 6, 2079 date Stores a date like June 30, 1991 time Stores a time of day like 12:30 P.M. Character Strings Data Types DATA TYPE Description char Maximum length of 8,000 characters.( Fixed length non-unicode characters) varchar Maximum of 8,000 characters.(variable-length non-unicode data). varchar(max) text Maximum length of 231characters, Variablelength non-unicode data (SQL Server 2005 only). Variable-length non- Unicode data with a maximum length of 2,147,483,647 characters. Unicode Character Strings Data Types DATA TYPE Description nchar Maximum length of 4,000 characters.( Fixed length Unicode) nvarchar Maximum length of 4,000 characters.(variable length Unicode)

nvarchar(max) ntext Maximum length of 231characters (SQL Server 2005 only).( Variable length Unicode) Maximum length of 1,073,741,823 characters. ( Variable length Unicode ) Binary Data Types DATA TYPE Description binary Maximum length of 8,000 bytes(fixed-length binary data ) varbinary Maximum length of 8,000 bytes.(variable length binary data) varbinary(max) Maximum length of 231 bytes (SQL Server 2005 only). ( Variable length Binary data) image Maximum length of 2,147,483,647 bytes. ( Variable length Binary Data) Misc Data Types DATA TYPE sql_variant timestamp Description Stores values of various SQL Server-supported data types, except text, ntext, and timestamp. Stores a database-wide unique number that gets updated every time a row gets updated

uniqueidentifier xml cursor table Stores a globally unique identifier (GUID) Stores XML data. You can store xml instances in a column or a variable (SQL Server 2005 only). Reference to a cursor object Stores a result set for later processing 2. What are the Temporary Tables? With Example? SQL Server provides two types of temp tables based on the behaviour and scope of the table. These are: Local Temp Table Global Temp Table Local Temp Table Local temp tables are only available to the current connection for the user; and they are automatically deleted when the user disconnects from instances. Local temporary table name is stared with hash ("#") sign. Global Temp Table Global Temporary tables name starts with a double hash ("##"). Once this table has been created by a connection, like a permanent table it is then available to any user by any connection. It can only be deleted once all connections have been closed. Two types of temporary tables available. Here I am going to describe each of them. Local Temporary Table The syntax given below is used to create a local Temp table in SQL Server: CREATE TABLE #LocalTempTable_SQLSchool(

User_ID int, User_Name varchar(50), User_Address varchar(150)) The above script will create a temporary table in tempdb database. We can insert or delete records in the temporary table similar to a general table like: insert into # LocalTempTable_SQLSchool values ( 1, Sai,'India'); insert into # LocalTempTable_SQLSchool values (2, Phanindra,'India'); Now select records from that table: select * from # LocalTempTable_SQLSchool After execution of all these statements, if we close the query window and again execute "Insert" or "Select" Command, it will throw the following error: Msg 208, Level 16, State 0, Line 1 Invalid object name '#LocalTempTable'. This is because the scope of Local Temporary table is only bounded with the current connection of current user. Global Temporary Table The scope of Global temporary table is the same for the entire user for a particular connection. We need to put "##" with the name of Global temporary tables. Below is the syntax for creating a Global Temporary Table: CREATE TABLE ##NewGlobalTempTable( UserID int, UserName varchar(50), UserAddress varchar(150)) The above script will create a temporary table in tempdb database. We can insert or delete records in the temporary table similar to a general table like: insert into ##NewGlobalTempTable values ( 1, 'Abhijit','India'); Now select records from that table: select * from ##NewGlobalTempTable Global temporary tables are visible to all SQL Server connections. When we create one of these, all the users can see it. 3. How to DISABLE Check Constraints? Syntax and Example.

To disable a check constraint for replication -or- 1. In database diagram, right-click the table containing the constraint, then select Check Constraints from the shortcut menu. Open the table containing the constraint, right-click in the Table Designer, and choose Check Constraints from the shortcut menu. 2. In the Check Constraints dialog box select the constraint from the Selected Check Constraint list. 3. In the properties grid change the value to No. Or -- Disable the constraints on a table called tablename: ALTER TABLE tablename NOCHECK CONSTRAINT ALL -- Re-enable the constraints on a table called tablename: ALTER TABLE tablename WITH CHECK CHECK CONSTRAINT ALL 4. How to add Primary Key for existing tables? Syntax and Example. ALTER TABLE <table-name> ADD CONSTRAINT <constraint-name> PRIMARY KEY <column-name> EXAMPLE: ALTER TABLE CUSTOMERS ADD PRIMARY KEY (CUST_ID) PS: Ensure the column is of type NOT NULL to perform above activity. 5. What is CASCADING of Foreign Keys? Explanation with Example. CREATE TABLE categories ( id int unsigned not null primary key, name VARCHAR(255) default null ); CREATE TABLE products ( id int unsigned not null primary key, name VARCHAR(255) default null ); CREATE TABLE categories_products ( category_id int unsigned not null, product_id int unsigned not null, PRIMARY KEY (category_id, product_id),

KEY pkey (product_id), FOREIGN KEY (category_id) REFERENCES categories (id) ON DELETE CASCADE ON UPDATE CASCADE, FOREIGN KEY (product_id) REFERENCES products (id) ON DELETE CASCADE ON UPDATE CASCADE ); This way, you can delete a product OR a category, and only the associated records in categories_products will die alongside. The cascade won't travel farther up the tree and delete the parent product/category table. e.g. products: boots, mittens, hats, coats categories: red, green, blue, white, black prod/cats: red boots, green mittens, red coats, black hats If you delete the 'red' category, then only the 'red' entry in the categories table dies, as well as the two entries prod/cats: 'red boots' and 'red coats'. The delete will not cascade any farther and will not take out the 'boots' and 'coats' categories. 6. What is the need for making Identity Property as Primary Key? By default Identity will allow duplicates by using a state called IDENTITY REBOUND(), so if we use primary key, it won t allow duplicates. Tasks for Views, Joins, Grouping and Indexes Concepts 1. What are the limitations of WITH CHECK OPTION It won t allow dynamic conditions (condition should be predefined, not depends on the user input) Any updates performed directly to a view's underlying tables are not verified against the view, even if CHECK OPTION is specified. 2. What is the difference between HAVING and WHERE Clause? WHERE and HAVING clauses are using in JOINS.

WHERE clause executes before the GROUPBY statement HAVING clause executes after the GROUP BY statement 3. Can we work with an array of number in SQL Server using T-SQL? If Yes, Any examples and limitations? If no, any alternatives for this? NO. We can use the Functions which return a table values. Example:- CREATE FUNCTION fn_reportcustdetails (@Age tinyint) RETURNS table AS RETURN ( SELECT * FROM CUSTOMERS WHERE CUST_AGE >= @Age) SELECT * FROM fn_reportcustdetails(25) 4. Write a Query to find the THIRD greatest of a given sequence of Numbers. SELECT * FROM tablename tbl1 WHERE (N-1) = ( SELECT COUNT(DISTINCT(Emp2.Salary)) FROM tablename tbl2 WHERE tbl2.salary > tbl1.salary ) /*here, N=3 greatest or highest number of given column*/ 5. How to delete duplicate rows in a table? For this example, we will use the following table with duplicate PK values. In this table the primary key is the two columns (col1, col2). We cannot create a unique index or PRIMARY KEY constraint since two rows have duplicate PKs. This procedure illustrates how to identify and remove the duplicates. create table t1(col1 int, col2 int, col3 char(50)) insert into t1 values (1, 1, 'data value one') insert into t1 values (1, 1, 'data value one') insert into t1 values (1, 2, 'data value two')

The first step is to identify which rows have duplicate primary key values: SELECT col1, col2, count(*) FROM t1 GROUP BY col1, col2 HAVING count(*) > 1 This will return one row for each set of duplicate PK values in the table. The last column in this result is the number of duplicates for the particular PK value. col1 col2 1 1 2 If there are only a few sets of duplicate PK values, the best procedure is to delete these manually on an individual basis. For example: set rowcount 1 delete from t1 where col1=1 and col2=1