Basic SQL Server Questions

Published on November 2016 | Categories: Documents | Downloads: 83 | Comments: 0 | Views: 602
of 20
Download PDF   Embed   Report

Comments

Content

Basic SQL Server Questions
What is RDBMS (Relational database management system)?

RDBMS is a database management system (DBMS) that is based on the relational model. Relationships may be created and maintained across and among the data and tables. In a relational database, relationships between data items are expressed by means of tables. Interdependencies among these tables are expressed by data values
What is the Difference between DBMS and RDBMS?

A DBMS has to be persistent, that is it should be accessible when the program created the data ceases to exist or even the application that created the data restarted. A DBMS also has to provide some uniform methods independent of a specific application for accessing the information that is stored. RDBMS is a Relational Data Base Management System Relational DBMS. This adds the additional condition that the system supports a tabular structure for the data, with enforced relationships between the tables. This excludes the databases that don‟t support a tabular structure or don‟t enforce relationships between tables. What are the properties of the RDBMS tables? 1 2 3 4 5 6 Values are atomic. Column values are of the same kind. Each row is unique. Each column must have a unique name. The sequence of columns is insignificant. The sequence of rows is insignificant.

What is Trigger ? SQL trigger is an SQL statements or a set of SQL statements which is stored to be activated or fired when an event associating with a database table occurs. The event can be any event including INSERT, UPDATE and DELETE. Sometimes a trigger is referred as a special kind of stored procedure in term of procedural code inside its body. What are the advantages and disadvantages of Triggers?
Advantages

Trigger provides an alternative way to check integrity. trigger can catch the errors in business logic in the database level.

trigger provides an alternative way to run scheduled tasks. With SQL trigger, you don‟t have to wait to run the scheduled tasks. You can handle those tasks before or after changes being made to database tables. trigger is very useful when you use it to audit the changes of data in a database table.
Disadvantages

Trigger only can provide extended validation and cannot replace all the validations. Some simple validations can be done in the application level SQL Triggers executes invisibly from client-application which connects to the database server so it is difficult to figure out what happen underlying database layer. SQL Triggers run every updates made to the table therefore it adds workload to the database and cause system runs slower. What is Stored Procedure? A stored procedure is a named group of SQL statements that have been previously created and stored in the server database. Stored procedures accept input parameters so that a single procedure can be used over the network by several clients using different input data. What is Normalization? In relational database design, the process of organizing data to minimize redundancy of data in a table is called normalization. Mention few normalization forms?
1NF: Eliminate Repeating Groups

Make a separate table for each set of related attributes, and give each table a primary key. Each field contains at most one value from its attribute domain.
2NF: Eliminate Redundant Data

If an attribute depends on only part of a multi-valued key, remove it to a separate table.
3NF: Eliminate Columns Not Dependent On Key

If attributes do not contribute to a description of the key, remove them to a separate table. All attributes must be directly dependent on the primary key.
BCNF: Boyce-Codd Normal Form

If there are non-trivial dependencies between candidate key attributes, separate them out into distinct tables. For more types Refer : http://en.wikipedia.org/wiki/Database_normalization

What is ACID Property? ACID (atomicity, consistency, isolation, durability) is a set of properties that guarantee database transactions are processed reliably. In the context of databases, a single logical operation on the data is called a transaction. For example, a transfer of funds from one bank account to another, even though that might involve multiple changes (such as debiting one account and crediting another), is a single transaction. Explain each characteristic of ACID Properties?
Atomicity

It requires that database modifications must follow an “all or nothing” rule. Each transaction is said to be atomic if when one part of the transaction fails, the entire transaction fails and database state is left unchanged. It is critical that the database management system maintains the atomic nature of transactions in spite of any application,
Consistency

This property ensures that the database remains in a consistent state; more precisely, it says that any transaction will take the database from one consistent state to another consistent state. The consistency property does not say how the DBMS should handle an inconsistency other than ensure the database is clean at the end of the transaction
Isolation

It refers to the requirement that other operations cannot access data that has been modified during a transaction that has not yet completed. The question of isolation occurs in case of concurrent transactions (multiple transactions occurring at the same time). Each transaction must remain unaware of other concurrently executing transactions, except that one transaction may be forced to wait for the completion of another transaction that has modified data that the waiting transaction requires
Durability

It is the ability of the DBMS to recover the committed transaction updates against any kind of system failure (hardware or software). Durability is the DBMS‟s guarantee that once the user has been notified of a transaction‟s success the transaction will not be lost, the transaction‟s data changes will survive system failure, and that all integrity constraints have been satisfied, so the DBMS won‟t need to reverse the transaction. What is De-normalization? It is the opposite of Normalization. De-normalization is the process of attempting to optimize the performance of a database by adding redundant data. What is a primary Key? In relational database design, a primary key is used to uniquely identify each row in a table. What is a candidate key ?

A candidate key is a field or combination of fields that can act as a primary key field for that table to uniquely identify each record in that table. What is a surrogate key ? Surrogate keys are keys that have no “business” meaning and are solely used to identify a record in the table. Such keys are either database or system generated values example: Identity in SQL Server , GUIDs What are Superkeys? A superkey is defined in the relational model as a set of attributes of a relation variable (relvar) for which it holds that in all relations assigned to that variable there are no two distinct tuples (rows) that have the same values for the attributes in this set. Equivalently a superkey can also be defined as a set of attributes of a relvar upon which all attributes of the relvar are functionally dependent. What’s the difference between a primary key and a unique key? Both primary key and unique enforce uniqueness of the column on which they are defined. But by default primary key creates a clustered index on the column, where are unique creates a nonclustered index by default. Another major difference is that, primary key doesn‟t allow NULLs, but unique key allows one NULL only. What are the advantages and disadvantages of Surrogate Key ? Pros: 1. Business Logic is not in the keys. 2. Small 4-byte key (the surrogate key will most likely be an integer and SQL Server for example requires only 4 bytes to store it, if a bigint, then 8 bytes). 3. Joins are very fast. 4. No locking contentions because of unique constraint (this refers to the waits that get developed when two sessions are trying to insert the same unique business key) as the surrogates get generated by the DB and are cached – very scalable. Cons: 1. An additional index is needed. In SQL Server, the PK constraint will always creates a unique index, in Oracle, if an index already exists, PK creation will use that index for uniqueness enforcement (not a con in Oracle). 2. Cannot be used as a search key. 3. If it is database controlled, for products that support multiple databases, different implementations are needed, example: identity in SS2k, before triggers and sequences in Oracle, identity/sequence in DB2 UDB. 4. Always requires a join when browsing the child table(s).

What are identity columns? An Identity column is a column (field ) in a database table that is made up of values generated by the database. This is much like an AutoNumber field in Microsoft Access or a sequence in Oracle. Because the concept is so important in database science, many RDBMS systems implement some type of generated key, although each has its own terminology. An identity column differs from a primary key in that its values are managed by the server and usually cannot be modified. In many cases an identity column is used as a primary key, however this is not always the case. What is View? A simple view can be thought of as a subset of a table. It can be used for retrieving data, as well as updating or deleting rows. Rows updated or deleted in the view are updated or deleted in the table the view was created with. It should also be noted that as data in the original table changes, so does data in the view, as views are the way to look at part of the original table. The results of using a view are not permanently stored in the database. The data accessed through a view is actually constructed using standard T-SQL select command and can come from one to many different base tables or even other views. What does @@error return? Returns the error number for the last Transact-SQL statement executed. Returns 0 if the previous Transact-SQL statement encountered no errors. Returns an error number if the previous statement encountered an error. If the error was one of the errors in the sys.messages catalog view, then @@ERROR contains the value from the sys.messages.message_id column for that error. You can view the text associated with an @@ERROR error number in sys.messages. What is the difference between temp tables and CTE and Table variables ?

What are function? A function in sql server is an object that performs an operation and returns a value. What are deterministic or nondeterministic functions? Functions are deterministic when they always return the same result any time they are called by using a specific set of input values. Ex: Replace(), Rtrim(), Substring() Functions are nondeterministic when they could return different results every time they are called, even with the same specific set of input values. Ex: Getdate(), newid() Types of user defined functions (UDF) in SQL server ? Different Kinds of User-Defined Functions created are: Scalar User-Defined Function A Scalar user-defined function returns one of the scalar data types like int, varchar, float etc. You pass in 0 to many parameters and you get a return value. Table-Valued User-Defined Function Table-Value user-defined function returns a table data type and is an alternative to a view Mention the datatypes not supported by scalar UDF? 1. text 2. ntext 3. image What are aggregate functions? Mention few. A function that performs a computation on a set of values rather than on a single value. For example, finding the average or mean of a list of numbers is an aggregate function. Ex: sum(), avg(), count(), max(), Min() What is a stored procedure? A set of Structured Query Language (SQL) statements with an assigned name that‟s stored in the database in compiled form so that it can be shared by a number of programs. Mention few commonly used System stored procedures ? 1. Sp_helptext

2. Sp_spaceused 3. sp_adduser 4. sp_help 5. sp_helpdb 6. sp_helpfile 7. sp_statistics 8. sp_table_privileges 9. sp_sqlexec 10. sp_tables 11. sp_who and many more. How to hide the number of records affected by a query? By using “ set nocount on ” Often it might be necessary to hide the number of records affected by a query. It can be a simple select or insert statement . Ususally, as soon as we execute a query a message pops up on the messages tab as shown below with the number of records affected.

This can be avoided by using a simple statement that hides the number of records affected. Set Nocount On The result will be

To change this back use Set Nocount Off What are linked servers ? A linked server configuration enables SQL Server to execute commands against OLE DB data sources on remote servers. What are the advantages of linked servers ?

Linked servers offer the following advantages: 1. Remote server access. 2. The ability to issue distributed queries, updates, commands, and transactions on heterogeneous data sources across the enterprise. 3. The ability to address diverse data sources similarly. What is a view ? A view is, in essence, is a virtual table. It does not physically exist. Rather, it is created by a query joining one or more tables. What is indexed view? A view with an index is known as indexed view. This index stores the result set of the query separately as an object. This helps in the improvement of the query processing as the query optimizer scans the data in the indexed view rather than the tables used in the query to create the view. In the case of standard view, only view definition is stored but the result set is not stored. What is a synonym in SQL server? Synonym is an alternate name given for a schema (Table most often.). It helps in hiding the underlying objects details from the end user hence providing better security. What are the advantages of procedures over normal script ? Stored procedures are faster in execution, as the plans are already cached in the memory. when the procedure is modified, all clients automatically get the new version. Stored procedures reduce network traffic and improve performance. Stored procedures can be used to help ensure the integrity of the database. What are GUIDs? The GUID (uniqueidentifier) data type is one of the most interesting data types available. uniqueidentifier column holds a GUI, a string of 32 random hexa-decimal characters (0-9, AF) in blocks separated by hyphens. A GUID will look like 5166AA1D-A18F-4D3C-A7CA-3F3CBF8CEE2B EDCF4B8A-4154-449B-972A-2224F8450BF1 CEA4C383-51FD-4B99-A67D-F5C34D5F1013 5D9FDC84-632D-4450-B183-04CBBEE87DC6

GUIDs have both Pros and cons. GUIDs are pretty big in size and require 16 bytes of storage. This usually makes it slow during joins of large dataset. Now you might think, What is so great about GUID? Although it occupies lot of space there are several advantages. First, a GUID will be a completely unique value and no other GUID in the world will share the same string. This means that you can use GUIDs as PKs on your tables if you will be moving data between databases. This technique prevents duplicate PKs when you actually copy data. GUIDs are widely used in Microsoft products to identify interfaces, replica sets, records, and other objects. In Sql Server, you can create a new GUID by using the function NEWID(). This function is a non-deterministic function. It generates a new value every time you execute function . Select NEWID() the datatype is named in SQL as “uniqueidentifier” What are joins ? mention different types and the results. Many have asked me this in the past. so what exactly is the difference between different type of joins? lets consider case by case, this will give you a better understanding. let us consider two tables for this. 1. Inner Join ( also commonly called join) Using INNER JOIN tells database to return only the columns that match the condition provided in the join clause. now if we want to select the employees and their respective team names, all we need to do is to join these two tables.INNER JOIN is often (but not always) created between the primary key column in one table and the foreign key column of another . SELECT E.name AS EmployeeName, T.TeamName FROM SalesTeam T INNER JOIN SalesPerson E ON T.TeamID = E.TeamID Now few more examples of inner joins are as below. SELECT distinct AN.LicenseGroupItemName , B.LicenseGroupName AS PricingLevelName, C.DetailedPricingLevelIDAS DetailedPricingLevelID, C.DetailedPricingLevelNameAS DetailedPricingLevelName FROM vwLicenseGroupHierarchyRelation AS B INNER JOIN

dbo.vwLicenseGroupItem AS AN ON B.ParentLicenseGroupItemSID = AN.LicenseGroupItemSID JOIN dbo.vwLicenseGroupHierarchyRelation AS C ON C.ParentLicenseGroupItemSID = B.ChildLicenseGroupItemSID and AN.Excess = C.Excess select * from vwSalesRevenueAccountTeamUnitAllocation Rev JOIN vwAccount A ON Rev.TPAccountSID=A.AccountSID and A.AccountTypeSID=2
Left / right Outer Join

Now let us consider the same tables as above with out a primary key & foreign key relation. If we run the same query as used earlier with left outer join then we will get all the matches ( as in the result of inner join) + the list of Teams without any match. The columns from the right hand side table will be filled with NULL. lets consider this example below. SELECT T.TeamName, E.name AS EmployeeName FROM SalesTeam T LEFT OUTER JOIN SalesPerson E ON T.TeamID = E.TeamID For right outer join the output will be SELECT T.TeamName, E.name AS EmployeeName FROM SalesTeam T RIGHT OUTER JOIN SalesPerson E ON T.TeamID = E.TeamID

The Result contains all the matches as in inner join + The records that were not mapped from right had side table with NULL inserted for each column in the Left hand side table.

FULL OUTER JOIN Full Outer join is simple to understand once you have got the hang of left & right outer join. full outer join = Inner join + non matching records from Right hand table (with nulls in Left hand table columns) + non matching records from left hand table (with nulls in Right hand table columns) a sample query and result is as given below. SELECT T.TeamName, E.name AS EmployeeName FROM SalesTeam T FULL OUTER JOIN SalesPerson E ON T.TeamID = E.TeamID What is an OLE DB provider? An OLE DB provider is a DLL that manages and interacts with a specific data source. An OLE DB data source identifies the specific database that can be accessed through OLE DB. What is the difference between a “where” clause and a “having” clause? ”Where” is a kind of restiriction statement. You use where clause to restrict all the data from DB.Where clause is used before result retrieving. Ex: Select * from EmployeeTable Where EmpName = „Smith‟ “Having” clause is used after Group by clause. It works the same way as the where clause on the results after applying group by. Ex: Select EmpName, Sum(salary) From SalaryTable Where SalaryDate >‟01/01/2010‟ Group By EmpName

Having Sum(Salary) > „200000‟

What is the basic form of a SQL statement to read data out of a table? The basic form to read data out of table is “SELECT * FROM table_name;” What is a “constraint”? A constraint allows you to apply simple integrity checks on a table. The primary types of constraints that are currently supported by SQL Server are : PRIMARY/UNIQUE – enforces uniqueness of a particular table column. FOREIGN KEY – validates that every value in a referenced column exists in a primary column of another table. CHECK – constraint is used to limit the values that can be placed in a column. The check constraints are used to enforce domain integrity.. NOT NULL constraint enforces that the column will not accept null values. The not null constraints are used to enforce domain integrity, as the check constraints. *Note : DEFAULT – specifies a default value for a column in case an insert operation does not provide one. Default is not a constraint in SQL server ( do remember this). What is a “functional dependency”? Functional dependency relates to how one object depends upon the other in the database. for example, procedure/function sp2 may be called by procedure sp1. Then we say that sp1 has functional dependency on sp2.

Why can a “group by” or “order by” clause be expensive to process? Processing of “group by” or “order by” clause often requires creation of Temporary tables to process the results of the query. Which depending of the result set can be very expensive.

What is a self join? Explain it with an example. Self join is just like any other join, except that two instances of the same table will be joined in the query. It can be used with inner / outer joins. Example:

Employees table which contains records of all the employees in the organisation including managers. The query below fetches the details of all the employees and their manager details. SELECT EMP.empname [Employee], isnull(MGR.empname, „No manager‟) [Manager] FROM Employee Emp LEFT OUTER JOIN Employee MGR ON Emp.mgrid = MGR.empid You might have noticed that we used two instances of the same table “Employee” to fetch the final results.

what are the differences between cross join and full outer join?

Cross Join : No join conditions are specified. Results in pairs of rows. Results in Cartesian product of two tables. Full Outer Join: A combination of both left and right outer joins. Results in every row from both of the tables , at least once. Assigns NULL for unmatched fields. What is “index covering” of a query? Index covering is a term used when data can be fetched only by using indexes without touching the underlying tables. What is SQL Profiler? SQL Profiler is a graphical tool that allows system administrators to monitor events in an instance of Microsoft SQL Server. You can capture and save data about each event to a file or SQL Server table to analyze later. How do you implement one-to-one, one-to-many and many-to-many relationships while designing tables? One-to-One relationship can be implemented as a single table and rarely as two tables with primary and foreign key relationships. One-to-Many relationships are implemented by splitting the data into two tables with primary key and foreign key relationships. Many-toMany relationships are implemented using a junction table with the keys from both the tables forming the composite primary key of the junction table. What are user defined datatypes? User defined datatypes let you extend the base SQL Server datatypes by providing a descriptive name, and format to the database. Example, if in your database, there is a column

called EmployeeName which appears in many tables. In all these tables it should be varchar(50). In this case you could create a user defined datatype called UDD_EmployeeName of varchar(50) and use it across all your tables.

What is difference between DELETE & TRUNCATE commands? DELETE
       

DELETE removes rows one at a time and records an entry in the transaction log for each deleted row. Delete command removes the rows from a table based on the condition that we provide with a WHERE clause. If you want to retain the identity counter, use DELETE instead. If you want to remove table definition and its data, use the DROP TABLE statement. DELETE Can be used with or without a WHERE clause DELETE Activates Triggers. DELETE can be rolled back. DELETE is DML Command. DELETE does not reset identity of the table.

TRUNCATE


Truncate will actually remove all the rows from a table and there will be no data in the table after we run the truncate command. TRUNCATE is faster and uses fewer system and transaction log resources than DELETE. TRUNCATE removes the data by deallocating the data pages used to store the table’s data, and only the page deallocations are recorded in the transaction log. TRUNCATE removes all rows from a table, but the table structure, its columns, constraints, indexes and so on, remains. The counter used by an identity for new rows is reset to the seed for the column. You cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint. Because TRUNCATE TABLE is not logged, it cannot activate a trigger. TRUNCATE cannot be rolled back. TRUNCATE is DDL Command. TRUNCATE Resets identity of the table

  

   

What are the advantages of using Stored Procedures?
   

Stored procedure can reduced network traffic and latency. Stored procedures promote code reuse. Stored procedures provide better security to your data, as the code used in the SP can be hidden from end users. Stored procedure execution plans are cached, reducing server overhead during each execution.



We can change stored procedure code without affecting clients.

What is a transaction? A transaction is a logical unit of work in which, all the steps must be performed or none. What are defaults? A default is a value that will be used by a column, if no value is supplied to that column while inserting data. IDENTITY columns and timestamp columns can‟t have defaults bound to them.

What are cursors? different types of cursors ? Cursors are objects that allow row-by-row prcessing of the resultsets. Types of cursors: Static, Dynamic, Forward-only, Keyset-driven.

What are the disadvantages of cursors? Disadvantages of cursors: 1. Each time you can perform a set of task only on a single row/record from the cursor 2. it results in a network roundtrip, where as a normal SELECT query makes only one rowundtrip, however large the resultset is. 3. Cursors are also memory intensive because they require more resources and temporary storage 4. Cursors are slower as it results in more IO operations What is the system function to get the current user’s user id? USER_ID().

What is Collation? Collation refers to a set of rules that determine how data is sorted and compared. Character data is sorted using rules that define the correct character sequence, with options for specifying case sensitivity, accent marks, kana character types and character width.

What is OLTP ? In OLTP stands for online transaction processing systems relational database design use the discipline of data modeling and generally follow the Codd rules of data normalization in order to ensure absolute data integrity. Using these rules complex information is broken down into its most simple structures where all of the individual atomic level elements relate to each other and satisfy the normalization rules. What is the difference between Global and Local temp tables? A global temporary table remains in the database permanently, but the rows exist only within a given connection. When connection is closed, the data in the global temporary table disappears. However, the table definition remains with the database for access when database is opened next time. A local temporary table exists only for the duration of a connection or, if defined inside a compound statement, for the duration of the compound statement. This is a commaon question that comes to each developers mind. Most of them considers IN and EXISTS as same but with different syntax. This aint true . We can use both operators to fetch the same results. Let me take few examples before we go to the actuals. SELECT * FROM TABLE_1 returns records as shown below Field1 1 2 3 4 SELECT * FROM TABLE_2 returns Field2 Field3 1 2 3 4 4 6 7 8

if we want to get the data in TABLE_1 which are present in “Field3″ of TABLE_2 then we can use the query with IN operator as SELECT * FROM TABLE_1 WHERE FIELD1 IN ( SELECT FIELD3 FROM TABLE_2) We can also use the query with EXISTS as

SELECT * FROM TABLE_1 WHERE EXISTS( SELECT „X‟ FROM TABLE_2 WHERE TABLE_1.FIELD1 = TABLE_2.FIELD3 ) when using EXISTS always use the where clause in the subquery to join the tables. Not doing so will result in fetching all the records from the main table. for eample if we consider the query below SELECT * FROM TABLE_1 WHERE EXISTS( SELECT Field3 FROM TABLE_2 ) will fetch all the records from TABLE_1 and is same as the query SELECT * FROM TABLE_1 The other difference is in performance( depending on which table is selected in outer/ inner query). EXISTS works faster than IN. you can check the performance plans of the above query for more info.

I had been seeing lot of SQL best practices posts on the web. I found some points missing in many of these post. I have consolidated few of my learning and posted it below. Hope it will be useful to you. Storing objects in Database files You should store the database catalog in the primary file store and all data and objects in secondary files . Disk access contention can be reduced by this configuration. Designing Filegroups Create one user-defined filegroup to hold secondary data files and database objects. Configure this filegroup as the default, this will automatically let SQL Server will store all objects you create in this filegroup. For good performance of data and log files Do not place data files and the operating system files on the same drive .doing so will result in disk contention. Place the tempdb database on a separate drive if possible. In environments in which there is intensive use of tempdb databases, you can get better performance by putting tempdb on a separate drive. It lets SQL Server perform tempdb operations in parallel with database operations. Place data files and transaction log files on a separate drives . This will give you the best performance by reducing disk contention between data and transaction log files. Password use the options to check the Windows expiration policy for SQL Server logins and apply the local Windows password policy . Cleaning up temp objects If you create a temporary table, you should drop it after its use. This ensures that structures are not left hanging around and allows resources to be reused/ reclaimed . Do not wait for the connections to be closed to clean up any temporary tables, because many applications use connection pools in which the connections may never get closed. Explicitly dropping a temporary objects ensures that you never receive errors on attempting to create the temp objects again. Security – assigning permissions


 

Security best practices mentions that you never grant permissions directly to a user. You should add a Windows login to a Windows group and the Windows group as a login to SQL Server. You then add this group as a user in a database. Create roles in a database corresponding to various job functions, and assign database users to the appropriate role. Assign security permissions on objects in the database to the database role.

Queries If possible, avoid SELECT * queries, which return all columns in a table/ s. Always specify a column list, which will ensure that you don‟t select columns that are not needed.

Use different column names Make sure that every output column of a query has a distinct column name. Applications should always be able to rely on column names for retrieving data and should not be allowed to use column ordinal position. Avoid cursors This might be the millionth time you hearing it, but thought of adding it. Avoid cursors . Ideally, cursors should be used only when a set-based solution is impossible to implement. Test your code by Using transactions Begin a transaction before running your code, and then roll back the transaction when you‟re done testing. Your data will be in the same state it was in when you started. use schema binding This will avoid dropping objects accidentaly. Create some views even if it is not used on a table and then make it bonded to schema. Using Stored Procedures to modify data Stored procedures are always a better option because you can more easily validate changes via stored procedures. Stored procedures are also more flexible. Try to avoid recompilation of Stored Procs Stored procedures are compiled into the query cache when executed. Compilation creates a query plan as well as an execution plan. SQL Server can reuse the query plan for subsequent executions, which conserves resources. But the RECOMPILE option forces SQL Server to discard the query plan each time the procedure is executed and create a new query plan. There are only a few extremely rare cases when recompiling at each execution is beneficial, such as if you add a new index from which the stored procedure might benefit. You typically should not add the RECOMPILE option to a procedure when you create it. Code efficiency Use built in procedures and function instead of custom ones ,as these are optimized for performance. Referential integrity and triggers You can use triggers to enforce referential integrity. However, you should not use triggers in place of declarative referential integrity (DRI) via a FOREIGN KEY constraint. DRI is enforced when the modification is made, before the change is part of the table, and is much more efficient than executing trigger code. However, you cannot define FOREIGN KEY constraints across databases. To enforce referential integrity across databases, you must use triggers. Using filegroup backups You should select a filegroup backup method when the size of a database makes it impractical to either back up or restore an entire database while still meeting your recovery requirements. moving databases Creating the files from scratch can consume a significant amount of time, you should not drop a database before a restore if you are going to overwrite it. If you are using backup and

restore to move a database to a different server with a different directory structure or the directory structure has changed, you can use the WITH MOVE option to cause the restore operation to create the underlying files in a path different from the original backup. Recovering to a point in time after a disaster During most disaster scenario, you always have transactions in the log that have not yet been backed up. For this reason, your first step in any recovery operation is to issue one final BACKUP LOG command. This process captures all remaining committed transactions that have not been backed up. Because you can issue a BACKUP LOG command against a database even if every data file, including the primary data file, is no longer available. The backup of the tail of the log then becomes the final transaction log that you apply in a restore process, enabling the database to be recovered without any loss of data. Shrinking databases As with the automatic shrink setting, the manual shrink process takes place in the background and does not affect users in the database, but the process of shrinking a database can consume system resources and degrade server performance. Also, as with auto shrinks, continually shrinking and regrowing a database can lead to fragmentation at the file level, which can be difficult to fix in busy database environments. DBAs should perform database shrink operations or transaction log shrink operations (covered in a moment) only when they are certain that the unused space being reclaimed will not be needed in the future. Authentication When all instances reside within a single domain or across trusted domains, you should use Windows authentication. When instances span nontrusted domains, you should use certificate-based authentication. use sys.dm_db_index_usage_stats The sys.dm_db_index_usage_stats DMV can be used to find any indexes that the query optimizer is not using. If the system has been running for awhile, and an index does not have any seeks, scans, or lookups registered for it, it is a strong possibility that the index is not being used to satisfy any queries. Or an index might show activity but is no longer being used. Encryption Use RC4 for minimal encryption strength and best performance and AES if you require strong encryption, but this algorithm will affect performance. Availability When using log shipping to increase availability reasons only, use No Recovery mode.

Sponsor Documents

Or use your account on DocShare.tips

Hide

Forgot your password?

Or register your new account on DocShare.tips

Hide

Lost your password? Please enter your email address. You will receive a link to create a new password.

Back to log-in

Close