This action might not be possible to undo. Are you sure you want to continue?
1. Write a query for merging two columns into one column on conditional bases(i.e. I want to select Employee Name from any of the column FullName or FirstName whichever is not null). Ans. To query from two columns conditionally we need to use CASE operator that is provided by SQL Server. Following is the query which depicts how to retrieve conditional value into one column.
SELECT Name= CASE WHEN EMPLOYEE.FullName IS NOT NULL THEN EMPLOYEE.FullName WHEN EMPLOYEE.FirstName IS NOT NULL THEN EMPLOYEE.FirstName END FROM EMPLOYEE
2. How to create Identity Column using Query? Ans.
SELECT row_number() OVER(ORDER by TESTTABLE.p1) as SRNO, result=CASE WHEN TESTTABLE.p1 IS NOT NULL THEN TESTTABLE.p1 WHEN TESTTABLE.p2 IS NOT NULL THEN TESTTABLE.p2 END FROM TESTTABLE
3. Which date function is used to find the difference between two dates? Ans.
OUTPUT: 5 more=>http://msdn.microsoft.com/en-us/library/ms189794.aspx 4. How can I find total number of employees with more than 40 years? Ans.
SELECT COUNT(EMPLOYEES.*) FROM EMPLOYEES WHERE EMPLOYEES.Age>40
5. How do I select 2nd highest salaried employee from my EMPLOYEE table? Ans.
SELECT EMPLOYEE.*, MAX(EMPLOYEE.Salary) AS SalarySecondHighest FROM EMPLOYEE WHERE EMPLOYEE.Salary< (SELECT MAX(EMPLOYEE.Salary) AS SalaryFirstHighest FROM EMPLOYEE)
6.Write a query to select all the employees from EMPLOYEE table whole first name starts with ‘j’ and who resides in city ‘Ahmedabad’ without using JOIN operator? Ans.
SELECT EMPLOYEE.* FROM EMPLOYEE WHERE CHARINDEX('j',EMPLOYEE.EmployeeName)=1 AND CHARINDEX('Ahmedabad',EMPLOYEE.CompanyName)>0
7. How to delete duplicate employee entry from EMPLOYEE table? Ans. There are two ways to do so. First is using temporary table and second is without using temporary table. Let’s see both with example one by one. First: Using Temporary Table –First select duplicate employee records and copy it into –holding table.
SELECT EMPLOYEE.EmployeeID, COUNT(EMPLOYEE.EmployeeID), * INTO HoldTable FROM EMPLOYEE
EmployeeID=HoldTable. .EmployeeID=HoldTable. Salary. Write a query for merging two columns into one column on conditional bases(i. COUNT(EMPLOYEE.other list of columns) FROM HoldDistinct Second: Without Using Temporary Table .'YYYY') HAVING COUNT(EMPLOYEE. I want to select Employee Name from any of the column FullName or FirstName whichever is not null).'YYYY') AS Year.EmployeeID –Third delete duplicate rows from EMPLOYEE tabled DELETE EMPLOYEE FROM EMPLOYEE. HoldTable WHERE EMPLOYEE.GROUP BY EMPLOYEE. SELECT TO_CHAR(EMPLOYEE. . row_number() OVER(PARTITION BY EMPLOYEE. Ans.e.FirstName END FROM EMPLOYEE 9.HireDate.EmployeeID –Fourth insert distinct entries.EmployeeID) = (SELECT MAX(COUNT(EMPLOYEE.EmployeeID HAVING COUNT(EMPLOYEE..EmployeeID)>1 –Second select duplicate rows into another holding table.FullName IS NOT NULL THEN EMPLOYEE. SELECT DISTINCT EMPLOYEE.* INTO HoldDistinct FROM EMPLOYEE.EmployeeID) AS TotalEmployees FROM EMPLOYEE GROUP BY TO_CHAR(EMPLOYEE. HoldTable WHERE EMPLOYEE.WITH HoldValues AS ( SELECT * . FirstName. SELECT Name= CASE WHEN EMPLOYEE.EmployeeID) AS Rank FROM EMPLOYEE ) –Delete duplicate entry DELETE FROM HoldValues WHERE Rank > 1 8.EmployeeID ORDER BY EMPLOYEE.other list of columns) SELECT EmployeeID.FullName WHEN EMPLOYEE. Salary. LastName. INSERT INTO EMPLOYEE(EmployeeID... FirstName. Among the employees in the EMPLOYEE table I want to find the year in which maximum employee join the company and also how many employees join the company during that year? Ans.EmployeeID)) FROM EMPLOYEE .HireDate.FirstName IS NOT NULL THEN EMPLOYEE. LastName..
How to find all the employees from EMPLOYEE table who earns more than the average salary of their department? Ans. SELECT EMPLOYEE.Salary) FROM EMPLOYEE INNEREMPLOYEE WHERE OUTEREMPLOYEE. SELECT EMPLOYEE.'YYYY')).HireDate.Salary ASC) AS Rank from EMPLOYEE ) EMPLOYEE where Rank<3 -.mod(rownum.12))) AS Months FROM EMPLOYEE 12.*.*. 10.* FROM (SELECT EMPLOYEE.2) FROM EMPLOYEE) 14.Gender= CASE EMPLOYEE.GROUP BY TO_CHAR(EMPLOYEE.*.Gender WHEN ‘Male’ THEN ‘Female’ WHEN ‘female’ THEN ‘Male’ END 13.Salary 11. TO_CHAR(TRUNC( MONTHS_BETWEEN(SYSDATE.* . How to list employees with period of service in terms of years and months? Ans. TO_CHAR(TRUNC( MOD(MONTHS_BETWEEN(SYSDATE. How to select top 3 employees from EMPLOYEE table which is grouped in the salary groups? Ans.Salary ORDER BY EMPLOYEE.HireDate).DepartmentID = INNEREMPLOYEE.0) in (SELECT rowid. SELECT OUTEREMPLOYEE. How you update Gender of EMPLOYEE table from ‘Male’ to ‘Female’ and from ‘Female’ to ‘Male’ in single query? Ans.DepartmentID) 12. EMPLOYEE. UPDATE EMPLOYEE SET EMPLOYEE. EMPLOYEE.Salary > (SELECT AVG(INNEREMPLOYEE.Salary FROM EMPLOYEE OUTEREMPLOYEE WHERE OUTEREMPLOYEE.* FROM EMPLOYEE WHERE (rowid.replace 3 in the query with (n+1) ORDER BY EMPLOYEE. SELECT EMPLOYEE.HireDate)/12)) AS Years. SELECT EMPLOYEE. How to display only Even Records from EMPLOYEE table? Ans. rank() OVER(PARTITION BY EMPLOYEE. How to display only Odd Records from EMPLOYEE table? Ans. OUTEREMPLOYEE.if you want to top n employees for each grouped salary -.
FROM EMPLOYEE WHERE (rowid.) Collapse | Copy Code --nth Highest Salary select min(Emp_Sal) from Employee_Test where Emp_Sal in (select distinct top n Emp_Sal from Employee_Test order by Emp_Sal desc) (ii) Finding TOP X records from each group Create a table named photo_test and insert some test data as :Collapse | Copy Code . I will be covering some of the common but tricky queries like:- (i) Finding the nth highest salary of an employee.1200 To find the nth highest salary. Emp_name Varchar(100). ('Maria'.1000). ('Rick'. Create a table named Employee_Test and insert some test data as:Collapse | Copy Code CREATE TABLE Employee_Test ( Emp_ID INT Identity. (i) Finding the nth highest salary of an employee. (iii) Deleting duplicate rows from a table. BACKGROUND This article demonstrates some commonly asked SQL queries in a job interview.1300).NET/SQL Server job interviews.1400).1100).2) FROM EMPLOYEE) INTRODUCTION SQL queries most asked in .mod(rownum. It is very easy to find the highest salary as:Collapse | Copy Code --Highest Salary select max(Emp_Sal) from Employee_Test Now.1200).3 etc. NOTE : All the SQL mentioned in this article has been tested under SQL Server 2005. replace the top 3 with top n (n being an integer 1. then the query is as:Collapse | Copy Code --3rd Highest Salary select min(Emp_Sal) from Employee_Test where Emp_Sal in (select distinct top 3 Emp_Sal from Employee_Test order by Emp_Sal desc) The result is as :. These tricky queries may be required in your day to day database usage.2) ) INSERT INSERT INSERT INSERT INSERT INTO INTO INTO INTO INTO Employee_Test Employee_Test Employee_Test Employee_Test Employee_Test VALUES VALUES VALUES VALUES VALUES ('Anees'. ('Stephen'. ('John'. (ii) Finding TOP X records from each group.2. Emp_Sal Decimal (10. if you are asked to find the 3rd highest salary.1) in (SELECT rowid.
Emp_name Varchar(100). file_path varchar(MAX) ) insert into photo_test values (17. rank() over (partition by pgm_main_category_id order by pgm_sub_category_id asc) as rankid from photo_test ) photo_test where rankid < 3 -.'photo/base1. it is often needed to get rid of such duplicates.jpg').jpg photo/forest1.replace 3 by any number 2. But if due to some reason.24.15.jpg photocamer1. This can be achieved in tow ways :(a) Using a temporary table. values(18.'photo/cybermbl1.'photo/tree1.'photo/cricket1. values(19.'photo/bb1.jpg').2) ) INSERT INTO Employee_Test1 VALUES (1. Now.1200). There are three groups of pgm_main_category_id each with a value of 17 (group 17 has four records).jpg').'photo/forest1.'photo/camer1. duplicates come up in the table data. the query is as follows:Collapse | Copy Code select pgm_main_category_id.'Rick'.jpg').jpg').20.18.pgm_sub_category_id. values(18.16.'photo/flower1.17.19.jpg').file_path from ( select pgm_main_category_id. .18 (group 18 has three records) and 19 (group 19 has three records).file_path. values(17.jpg').22. (a) Using a temporary or staging table Let the table employee_test1 contain some duplicate data like:Collapse | Copy Code CREATE TABLE Employee_Test1 ( Emp_ID INT. insert into photo_test values (17.pgm_sub_category_id The result is as:Collapse | Copy Code pgm_main_category_id 17 17 18 18 19 19 pgm_sub_category_id 15 16 18 19 21 22 file_path photo/bb1.jpg photo/cricket1.pgm_sub_category_id. values(19.1000). insert into photo_test values(19.jpg (iii) Deleting duplicate rows from a table A table with a primary key doesn’t contain duplicates .'photo/laptop1.jpg').jpg photo/tree1. order by pgm_main_category_id.jpg'). pgm_sub_category_id int. (b) Without using a temporary table. the keys have to be disabled or when importing data from other sources. Emp_Sal Decimal (10. insert insert insert insert insert insert insert into into into into into into into photo_test photo_test photo_test photo_test photo_test photo_test photo_test values(17. values(18.jpg photo/laptop1.21.'Anees'. INSERT INTO Employee_Test1 VALUES (2.jpg').create table photo_test ( pgm_main_Category_id int.3 etc for top2 or top3. if you want to select top 2 records from each group.23.'photo/F1.
(5.'Tim'.Emp_name. Collapse | Copy Code select * from employee_test1 gives the result as:Collapse | Copy Code Emp_ID 1 2 3 4 5 6 Emp_name Anees Rick John Stephen Maria Tim Emp_Sal 1000 1200 1100 1300 1400 1150 (b) Without using a temporary table Collapse | Copy Code .'Stephen'.Emp_Sal from employee_test1 group by Emp_ID.with T as ( select * .Emp_Sal Step3: Truncate the original table as:Collapse | Copy Code truncate table employee_test1 Step4: Fill the original table with the rows of the temporary table as:Collapse | Copy Code insert into employee_test1 select * from employee_test1_temp Now. (6. Step 1: Create a temporary table from the main table as:Collapse | Copy Code select top 0* into employee_test1_temp from employee_test1 Step2 : Insert the result of the GROUP BY query into the temporary table as:Collapse | Copy Code insert into employee_test1_temp select Emp_ID.1100). the duplicate rows from the main table have been removed.1300). (6.1400).1150).1150).Emp_name.'John'.'Maria'. row_number() over (partition by Emp_ID order by Emp_ID) as rank from employee_test1 ) delete from T where rank > 1 The result is as:Collapse | Copy Code Emp_ID 1 2 3 4 5 6 Emp_name Anees Rick John Stephen Maria Tim Emp_Sal 1000 1200 1100 1300 1400 1150 . (4.INSERT INSERT INSERT INSERT INSERT INTO INTO INTO INTO INTO Employee_Test1 Employee_Test1 Employee_Test1 Employee_Test1 Employee_Test1 VALUES VALUES VALUES VALUES VALUES (3.'Tim'.
title_id GROUP BY authors. SELECT empid. a3.tempe AS Difference FROM day_temp a INNER JOIN day_temp b ON a. DATEADD(dd.id+1 There is a table which contains the names like this. a1. .au_id = titleauthor. How do I write a query to get the difference of temperature among each other for seven days of a week? SELECT a. primary key doesn‘t allow NULLs. a. and the rest are called alternate . where are unique creates a nonclustered index by default. a1.Salary > E1. and total salaries of individual employees in one query. alternate key.au_lname ORDER BY BooksCount DESC Write a SQL Query to find first day of month? SELECT DATENAME(dw.tempe. one of them will become the primary key. a.Salary))From Employee Query to Find the 2nd Maximum Salary SELECT SALARY FROM RY <> (SELECT MAX (SALARY) FROM EMPLOYEE)) select max(salary) as Salary from Emplo where salary!=(select max(salary) fromEmplo) SELECT MAX(E1. a.dayid. SELECT authors. COUNT(*) AS BooksCount FROM authors INNER JOIN titleauthor ON authors. GETDATE()) + 1. a1. composite key.dayid + 1 or this query Select a.degree-b. Define candidate key.degree from temperature a. A candidate key is one that can identify each row of a table uniquely. a3.title_id = titleauthor. but unique key allows one NULL only.Few Interesting Questions and concepts There are 3 tables Titles.dday. a2 and their salaries.b. Query to find the maximum salary of an employee Select * from Employee where salary = (Select max(Salary) from Employee) Query to Find the Nth Maximum Salary Select * From Employee E1 Where E2 Where E2. the result should start from the author who has written the maximum number of books and end with the author who has written the minimum number of books. Authors and Title-Authors (check PUBS db). Write a query to get grand total salary.salary Creating a foreign-key constraint between columns of two tables defined with two different datatypes will produce an error Ans : Yes Important concepts 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. UPDATE Emp1 SET Gender=CASE Gender WHEN ‘Male’ THEN ‘Female’WHEN ‘female’ THEN‘Male’END.dayid = b. temperature b where a. If the table has more than one candidate key. au_id INNERJOIN titles ON titles.DATEPART(dd. a2.au_lname. But by default primary key creates a clustered index on the column. SUM(salary) AS salaryFROM employeeGROUP BY empid WITH ROLLUP ORDER BY empid Update With Case EmpID 1 2 EmpName Raja Rani Gender Male Female In the above table using one query u need to change Gender male to female and who is female need to change male.Salary) EMPLOYEEWHERE SALARY=(SELECT MAX(SALARY) FROM EMPLOYEE WHERE SALA (3-1) = (Select Count(Distinct(E2.salary) FROM emplo E1 . a. Generally a candidate key becomes the primary key of the table. GETDATE())) AS FirstDay There is a table day_temp which has three columns dayid. Another major difference is that.day. day and temperature. Write the query to get the author name and the number of books written by that author.tempe .id=b.salary< E2. emplo E2WHERE E1. a4.
and only the page deallocations are recorded in th e transaction log. attempt to acquire a lock on the other‘s piece. dirty reads are not possible but nonrepeatable reads and phantoms are possible. Check out SET DEADLOCK_PRIORITY and ―Minimizing Deadlocks‖ in SQL Server books online . TRUNCATE TABLE can be rolled back. You cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint. ACID stands for Atomicity. Windows NT /2000 Performance monitor. Be sure to read about SET TRANSACTION ISOLATION LEVEL. SQL Server detects deadlocks and terminates one user‘s process. What’s the difference between DELETE TABLE and TRUNCATE TABLE commands? DELETE TABLE is a logged operation. The counter used by an identity for new rows is reset to the seed for the column. Repeatable Read. and phantoms are not possible. but it won‘t log the deletion of each row. excess recompilations of stored procedures. For more information and explanation of these properties. table scans. instead. Durability. which makes it faster. But some general issues that you could talk about would be: No indexes. TRUNCATE TABLE may not be used on tables participating in an indexed view What are the steps you will take to improve performance of a poor performing query? This is a very open ended question and there could be a lot of reasons behind the poor performance of a query. TRUNCATE TABLE removes the data by deallocating the data pages used to store the table‘s data. Graphical execution plan in Query Analyzer What is a deadlock and what is a live lock? How will you go about resolving deadlocks? Deadlock is a situation when two processes. Repeatable Read – A transaction operating at the Repeatable Read level is guaranteed not to see any changes made by other transactions in values it has already read. SQL Server Profiler. Read Committed. Read Committed – A transaction operating at the Read Committed level cannot see changes made by other transactions until those transactions are committed. A livelock also occurs when read transactions monopolize a table or page. but the table structure and its columns. SET STATISTICS IO ON. See SQL Server books online for an explanation of the isolation levels. Isolation. These are the properties of a transaction. forcing a write transaction to wait indefinitely. blocking. and phantoms are all possible. Here are the other isolation levels (in the ascending order of isolation): Read Uncommitted.keys. At this level of isolation. dirty reads. each having a lock on one piece of data. TRUNCATE TABLE removes all rows from a table. too much normalization. use DELETE statement without a WHERE clause. Some of the tools/ways that help you troubleshooting performance problems are: SET SHOWPLAN_ALL ON. At this level of isolation. constraints. nonrepeatable reads. Consistency. nonrepeatable reads. Read Uncommitted – A transaction operating at the Read Uncommitted level can see uncommitted changes made by other transactions. Of course. At this isolation level. Serializable – A transaction operating at the Serializable level guarantees that all concurrent transactions interact only in ways that produce the same effect as if each transaction were entirely executed one after the other. SET SHOWPLAN_TEXT ON. What is a transaction and what are ACID properties? A transaction is a logical unit of work in which. Serializable. dirty reads and nonrepeatable reads are not possible but phantoms are possible. A key formed by combining at least two or more columns is called composite key. indexes and so on remain. all the steps must be performed or none. which lets you customize the isolation level at the connection level. A livelock is one. use the DROP TABLE statement. excess usage of cursors and temporary tables. Each process would wait indefinitely for the other to release the lock. Because TRUNCATE TABLE is not logged. which makes it slow. The DELETE statement removes rows one at a time and records an entry in the transaction log for each deleted row. missing or out of date statistics. TRUNCATE TABLE also deletes all the rows in a table. If you want to remove table definition and its data. SQL Server detects the situation after four denials and refuses further shared locks. TRUNCATE TABLE is functionally identical to DELETE statement with no WHERE clause: both remove all rows in the table. poorly written query with unnecessarily complicated joins. procedures and triggers without SET NOCOUNT ON. see SQL Server books online or any RDBMS fundamentals text book. so the deletion of each row gets logged in the transaction log. unless one of the user processes is terminated. The default SQL Server isolation level is Read Committed. At this level of isolation. instead it logs the deallocat ion of the data pages of the table. But TRUNCATE TABLE is faster and uses fewer system and transaction log resources than DELETE. dirty reads. use DELETE instead. If you want to retain the identity counter. where a request for an exclusive lock is repea tedly denied because a series of overlapping shared locks keeps interfering. Explain different isolation levels An isolation level determines the degree of isolation of data between concurrent transactions. it cannot activate a trigger.
sp_updatestats Index Optimization tips • Every index increases the time in takes to perform INSERTS. o Queries that return large result sets. or removed (that is. under what circumstances they go out of date. as opposed to an index with non-unique values. if the distribution of key values has changed). how do you update them? Statistics determine the selectivity of the indexes. • If you want to join several tables. try to create surrogate integer keys for this purpose and create indexes on their columns. Try to schedule it to execute during CPU idle time and slow production periods. This reduces the size of the index and reduces the number of reads required to read the index. Try to order the columns in the key as to enhance selectivity. Therefore table can have only one clustered index. • You can use sp_MSforeachtable undocumented stored procedure to rebuild all indexes in your database. If you have read-only table. Each index row contains the non-clustered key value and one or more row locators that point to the data row (or rows if the index is not . and <=.What are statistics. sp_autostats. Look up SQL Server books online for the following commands: UPDATE STATISTICS. >. the leaf nodes contain index rows. A clustered index is a special type of index that reorders the way records in the table are physically stored. UPDATES and DELETES. • If your application will be performing the same query over and over on the same table. the leaf nodes contain index rows. • Create surrogate integer primary key (identity for example) if your table will not have many insert operations. This trace will show which tables are being scanned by queries instead of using an index. • Clustered indexes are more preferable than nonclustered. o The leaf layer of a non-clustered index does not consist of the data pages. DROP STATISTICS. The leaf nodes of a nonclustered index does not consist of the data pages. A nonclustered index is a special type of index in which the logical order of the index does not match the physical stored order of the rows on disk. if you need to select by a range of values or you need to sort results set with GROUP BY or ORDER BY. >=. CREATE STATISTICS. Consider using a clustered index for: o Columns that contain a large number of distinct values. If an indexed column has unique values then the selectivity of that index is more. STATS_DATE. changed. with two significant differences: o The data rows are not sorted and stored in order based on their non-clustered keys. • Try to create indexes on columns that have integer values rather than character values. Instead. with the most selective columns to the leftmost of the key. • If you create a composite (multi-column) index. then the number of indexes may be increased. so the number of indexes should not be very much. • You can use the SQL Server Profiler Create Trace Wizard with ―Identify Scans of Large Tables‖ trace to determine which tables in your database may need indexes. not more. • Keep your indexes as narrow as possible. Some situations under which you should update statistics: 1) If there is significant change in the key values in the index 2) If a large amount of data in an indexed column has been added. o Queries that return a range of values using operators such as BETWEEN. the order of the columns in the key are very important. Try to use maximum 4-5 indexes on one table. Non-clustered indexes have the same B-tree structure as clustered indexes. DBCC SHOW_STATISTICS. The leaf nodes of a clustered index contain the data pages. sp_createstats. or the table has been truncated using the TRUNCATE TABLE statement and then repopulated 3) Database is upgraded from a previous version. o Columns that are accessed sequentially. Instead. sp_MSforeachtable @command1=‖print ‗?‘ DBCC DBREINDEX (‗?‘)‖ Explain about Clustered and non clustered index? How to choose between a Clustered Index and a Non-Clustered Index? There are clustered and nonclustered indexes. <. consider creating a covering index on the table. Query optimizer uses these indexes in determining whether to choose an index or not while executing a query.
retrieving all rows where the student identification number is the same in both the students and courses tables. o Per table only 249 non clustered indexes How many types of Joins? Joins can be categorized as: • Inner joins (the typical join operation. getsal function get‘s executed and the return Type is returned as the result set. You can also get one by joining every row of a table to every row of itself. • model – The model database is used as the template for all databases created on a system. tempdb is re-created every time SQL Server is started so the system starts with a clean copy of the database. part of your system processing load may be taken up with autogrowing tempdb to the size needed to support your workload each time to restart SQL Server. the select list columns from the other table contain null values. You can avoid this overhead by using ALTER DATABASE to increase the size of tempdb. All rows from the right table are returned. the first part of the database is created by copying in the contents of the model database. which uses some comparison operator like = or <>). If the size defined for tempdb is small. What is the basic functions for master. msdb. then the remainder of the new database is filled with empty pages. when table is created no storage is allotted for salary type. Outer joins are specified with one of the following sets of keywords when they are specified in the FROM clause: • LEFT JOIN or LEFT OUTER JOIN -The result set of a left outer join includes all the rows from the left table specified in the LEFT OUTER clause. • tempdb – tempdb holds all temporary tables and temporary stored procedures. each row from the left table is combined with all rows from the right table. • Cross joins – Cross joins return all rows from the left table. Outer joins can be a left. the entire result set row contains data values from the base tables. What are the difference between a function and a stored procedure? Functions can be used in a select statement where as procedures cannot Procedure takes both input and output parameters but Functions takes only input parameters Functions cannot return values of type text. But when we are fetching some values from this table. the model database . • RIGHT JOIN or RIGHT OUTER JOIN – A right outer join is the reverse of a left outer join. • FULL JOIN or FULL OUTER JOIN – A full outer join returns all rows in both the left and right tables. A Cartesian join is when you join every row of one table to every row of another table. Cross joins are also called Cartesian products. For example. and getsal function is also not executed. When a CREATE DATABASE statement is issued. the associated result set row contains null values for all select list columns coming from the right table. tempdb autogrows as needed while SQL Server is running. Because tempdb is created every time SQL Server is started. These include equi-joins and natural joins. not just the ones in which the joined columns match.unique) having the key value. or full outer join. Null values are returned for the left table any time a right table row has no matching row in the left table. Any time a row has no match in the other table. Inner joins use a comparison operator to match rows from two tables based on the values in common columns from each table.salary getsal(name)) Here getsal is a user defined function which returns a salary type. • Outer joins. tempdb databases? Microsoft® SQL Server 2000 systems have four system databases: • master – The master database records all of the system level information for a SQL Server system. ntext. master is the database that records the existence of all other databases. including the location of the database files. When there is a match between the tables. By default. image & timestamps where as procedures can Functions can be used as user defined datatypes in create table but procedures cannot ***Eg:-create table <tablename>(name varchar(10). When a row in the left table has no matching rows in the right table. It also fills any other temporary storage needs such as work tables generated by SQL Server. a right. It records all login accounts and all system configuration settings. (A Cartesian join will get you a Cartesian product.
the definition of 2NF is sometimes phrased as. Rule 5: Isolate Semantically Related Multiple Relationships. Boyce-Codd Normal Form (BCNF) Definition: A table is in BCNF if it is in 3NF and if every determinant is a candidate key. 1st Normal Form (1NF) Definition: A table (relation) is in 1NF if 1. remove it to a separate table. Instead. 3.‖ Rule 2: Eliminate Redundant Data. • msdb – The msdb database is used by SQL Server Agent for scheduling alerts and jobs. the order of the columns is immaterial. Note: The requirement that there be no duplicated rows in the table means that the table has a key (although the key might be made up of more than one column—even. The leaf nodes of a clustered index contain the data pages. possibly. of all the columns). if it is in 4NF and if every join dependency in the table is a consequence of the candidate keys of the table. 5th Normal Form (5NF) Definition: A table is in 5NF. The leaf node of a non clustered index does not consist of the data pages. Each cell is single-valued (i. Therefore table can have only one clustered index.e. remove them to a separate table. A clustered index is a special type of index that reorders the way records in the table are physically stored. 2. and recording operators. 3. No table may contain two or more l:n or n:m relationships that are not directly related. A non clustered index is a special type of index in which the logical order of the index does not match the physical stored order of the rows on disk.must always exist on a SQL Server system. What are the difference between clustered and a non-clustered index? 1. Rule 4: Isolate Independent Multiple Relationships. there are no repeating groups or arrays). There are no duplicated rows in the table. field) are of the same kind. There may be practical constraints on information that justify separating logically related many-to-many relationships. If an attribute depends on only part of a multi-valued key.. 2nd Normal Form (2NF) Definition: A table is in 2NF if it is in 1NF and if all non-key attributes are dependent on all of the key. ―A table is in 2NF if it is in 1NF and if it has no partial dependencies. Note: The order of the rows is immaterial. It can be changed from the Network Utility TCP/IP properties. Which TCP/IP port does SQL Server run on? How can it be changed? SQL Server runs on port 1433. 2. What are the different index configurations a table can have? . Rule 1: Eliminate Repeating Groups. Domain-Key Normal Form (DKNF) Definition: A table is in DKNF if every constraint on the table is a logical consequence of the definition of keys and domains. Entries in a column (attribute. the leaf nodes contain index rows. Rule 3: Eliminate Columns Not Dependent on Key. also called ―Projection-Join Normal Form‖ (PJNF). and give each table a primary key. Make a separate table for each set of related attributes. If attributes do not contribute to a description of the key. Note: Since a partial dependency occurs when a non-key attribute is dependent on only a part of the (composite) key. 4th Normal Form (4NF) Definition: A table is in 4NF if it is in BCNF and if it has no multi-valued dependencies. 3rd Normal Form (3NF) Definition: A table is in 3NF if it is in 2NF and if it has no transitive dependencies. 2.
TRUNCATE Resets identity of the table 2. DELETE Can be used with or without a WHERE clause 4. it is called Kana sensitive. No indexes A clustered index A clustered index and many nonclustered indexes A nonclustered index Many nonclustered indexes 4.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. 1. 4. TRUNCATE: 1. Because TRUNCATE TABLE is not logged. and only the page deallocations are recorded in the transaction log. 3. DELETE removes rows one at a time and records an entry in the transaction log for each deleted row. 5. 2. its columns. Kana Sensitivity . TRUNCATE is faster and uses fewer system and transaction log resources than DELETE. 3. 4. 6. TRUNCATE cannot be rolled back. 7. use the DROP TABLE statement. 7. etc. You cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint. What's the difference between a primary key and a unique key? Both primary key and unique key enforces uniqueness of the column on which they are defined. it cannot activate a trigger. Using these rules complex information is broken down into its most simple structures (a table) where all of the individual atomic level elements relate to each other and satisfy the normalization rules. What are different types of Collation Sensitivity? 1. What is difference between DELETE and TRUNCATE commands? Delete command removes the rows from a table based on the condition that we provide with a WHERE clause. DELETE can be rolled back. 6. Another major difference is that. Width sensitivity . indexes and so on. The counter used by an identity for new rows is reset to the seed for the column. but unique key allows one NULL only. 2. 7. TRUNCATE is DDL Command. 5. TRUNCATE removes all rows from a table. remains. If you want to retain the identity counter. DELETE: 1. 2. 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. constraints. 5. B and b. TRUNCATE removes the data by deallocating the data pages used to store the table's data. DELETE is DML Command. What is OLTP (Online Transaction Processing)? In OLTP . where are unique creates a nonclustered index by default. but the table structure. If you want to remove table definition and its data. use DELETE instead. 4.When Japanese kana characters Hiragana and Katakana are treated differently. 5.A single-byte character (half-width) and the same character represented as a doublebyte character (full-width) are treated differently than it is width sensitive. primary key doesn't allow NULLs. 3. Case sensitivity . DELETE Activates Triggers. 6.A and a.A table can have one of the following index configurations: 1. . Accent sensitivity 3. But by default primary key creates a clustered index on the column. 2. DELETE does not reset identity of the table.
Microsoft SQL Server and click SQL Enterprise Manager to run SQL Enterprise Manager from the Microsoft SQL Server program group. you can filter them based on the information you want. HAVING behaves like a WHERE clause. and 3. 10. especially when the monitoring process takes place over a long period of time. Select the server then from the Tools menu select SQL Server Configuration Properties. 9.. If a large amount of deletions any modification or Bulk Copy into the tables has occurred. To change authentication mode in SQL Server click Start. 2. 2. Programs. you can monitor a production environment to see which stored procedures are hampering performances by executing too slowly. Single-row sub-query. where the sub-query returns multiple columns 11. and 3. If TRUNCATE is written in Query Editor surrounded by TRANSACTION and if session is closed. A query can contain more than one sub-query. HAVING is typically used in a GROUP BY clause. When GROUP BY is not used. where the sub-query returns multiple rows. where the sub-query returns only one row. A sub-query cannot contain an ORDER-BY clause. so that only a subset of the event data is collected. A sub-query must be put in the right hand of the comparison operator. What is the difference between a HAVING CLAUSE and a WHERE CLAUSE? They specify a search condition for a group or an aggregate. A sub-query must be enclosed in the parenthesis. 8. Types of Sub-Query 1. SERVERPROPERTY ('edition'). When is the use of UPDATE_STATISTICS command? This command is basically used when a large processing of data has occurred. and choose the Security page. Multiple column sub-query. But the difference is that HAVING can be used only with the SELECT statement. What are the properties and different Types of Sub-Queries? 1. 13. 14. it has to update the indexes to take these changes into account. What is SQL Server Agent? SQL Server agent plays an important role in the day-to-day tasks of a database administrator (DBA).Note: DELETE and TRUNCATE both can be rolled back when surrounded by TRANSACTION if the current session is not closed.SQL and Windows. Monitoring too many events adds overhead to the server and the monitoring process and can cause the trace file or trace table to grow very large. It is often overlooked as one of the main tools for SQL Server management. 2. For example. 4. What are the authentication modes in SQL Server? How can it be changed? Windows mode and Mixed Mode . Multiple-row sub-query. You can capture and save data about each event to a file or SQL Server table to analyze later. Use SQL Profiler to monitor only the events in which you are interested. Having Clause is basically used only with the GROUP BY function in a query whereas WHERE Clause is applied to each row before they are part of the GROUP BY function in a query. SERVERPROPERTY ('productlevel'). it can not be rolled back but DELETE can be rolled back. Which command using Query Analyzer will give you the version of SQL server and operating system? SELECT SERVERPROPERTY ('productversion'). What is SQL Profiler? SQL Profiler is a graphical tool that allows system administrators to monitor events in an instance of Microsoft SQL Server. Properties of Sub-Query 1. 12. If traces are becoming too large. Its purpose is to ease the implementation of . UPDATE_STATISTICS updates the indexes on these tables accordingly.
17. identifiers can be delimited by double quotation marks. type. length. 15. 19. The primary key constraints are used to enforce entity integrity. Recursion can be defined as a method of problem solving wherein the solution is arrived at by repetitively applying it to subsets of the problem. the data in the global temporary table disappears.function scheduling engine. 20. In log shipping the transactional log file from one server is automatically updated into the backup database on the other server. the other server will have the same db and can be used this as the Disaster Recovery plan. What is PRIMARY KEY? A PRIMARY KEY constraint is a unique identifier for a row within a database table. A global temporary table remains in the database permanently. string_expression is the string that will have characters substituted. Enterprise Editions only supports log shipping. Using this syntax. However. A common application of recursive logic is to perform numeric computations that lend themselves to repetitive evaluation by the same processing steps. 21. start. replacement_characters). but the rows exist only within a given connection. If one server fails. What is UNIQUE KEY constraint? . you can write stored procedures that call themselves. What does it mean to have QUOTED_IDENTIFIER ON? What are the implications of having it OFF? When SET QUOTED_IDENTIFIER is ON. What is Log Shipping? Log shipping is the process of automating the backup of database and transaction log files on a production SQL server. Using the syntax REPLACE (string_expression.tasks for the DBA. A local temporary table exists only for the duration of a connection or. where every incidence of search_string found in the string_expression will be replaced with replacement_string. replacement_string). search_string. You can nest stored procedures and managed code references up to 32 levels. Every table should have a primary key constraint to uniquely identify each row and only one primary key constraint can be created for each table. which allows you to schedule your own jobs and scripts. and then restoring them onto a standby server. with its full. if defined inside a compound statement. The key feature of log shipping is that it will automatically backup transaction logs throughout the day and automatically restore them on the standby server at defined interval. Stored procedures are nested when one stored procedure calls another or executes managed code by referencing a CLR routine. Because Transact-SQL supports recursion. STUFF (string_expression. What is the STUFF function and how does it differ from the REPLACE function? STUFF function is used to overwrite existing characters. and literals must be delimited by single quotation marks. identifiers cannot be quoted and must follow all Transact-SQL rules for identifiers. 2. or aggregate. 16. for the duration of the compound statement. and replacement_characters are the new characters interjected into the string. REPLACE function to replace existing characters of all occurrences. the table definition remains with the database for access when database is opened next time. Name 3 ways to get an accurate count of the number of records in a table? SELECT * FROM table1 SELECT COUNT(*) FROM table1 SELECT rows FROM sysindexes WHERE id = OBJECT_ID(table1) AND indid < 2 18. When SET QUOTED_IDENTIFIER is OFF. Can a stored procedure call itself or recursive stored procedure? How much level SP nesting is possible? Yes. start is the starting position. 22. When connection is closed. What is the difference between a Local and a Global temporary table? 1. length is the number of characters in the string that are substituted.
Stored procedure can reduced network traffic and latency. staying cached in SQL Server's memory. Can SQL Servers linked to other servers like Oracle? SQL Server can be linked to any server provided it has OLE-DB provider from Microsoft to allow a link. The not null constraints are used to enforce domain integrity. Oracle has an OLE-DB provider for oracle that Microsoft provides to add it as linked server to SQL Server group. The check constraints are used to enforce domain integrity. Microsoft Press Books and Book on Line (BOL) refers it as Heap. SELECT @RC = @@ROWCOUNT. 5. Stored procedures provide better security to your data. Many times it is better to drop all indexes from table and then do bulk of inserts and to restore those indexes after that. User can schedule administrative tasks. 4. Foreign keys prevent actions that would leave rows with foreign key values when there are no primary keys with that value. such as cube processing. 24. so no duplicate values are entered. The unique key constraints are used to enforce entity integrity as the primary key constraints. What is FOREIGN KEY? A FOREIGN KEY constraint prevents any actions that would destroy links between tables with the corresponding data values.A UNIQUE constraint enforces the uniqueness of the values in a set of columns. What are the advantages of using Stored Procedures? 1. Stored procedures can encapsulate logic. therefore. user can configure SQL Server Agent to continue to run the remaining tasks or to stop execution. You can change stored procedure code without affecting clients. Stored procedure execution plans can be reused. Stored procedures help promote code reuse. E. 28. What is CHECK Constraint? A CHECK constraint is used to limit the values that can be placed in a column. How to get @@ERROR and @@ROWCOUNT at the same time? If @@Rowcount is checked after Error checking statement then it will have 0 as the value of @@Recordcount as it would have been reset. What is a Scheduled Jobs or What is a Scheduled Tasks? Scheduled tasks let user automate processes that run on regular or predictable cycles. A foreign key in one table points to a primary key in another table. If one job fails. And if @@Recordcount is checked before the error-checking statement then @@Error would get reset. if it has neither Cluster nor Non-cluster Index? What is it used for? Unindexed table or Heap. Update Stats of Tables. What is NOT NULL Constraint? A NOT NULL constraint enforces that the column will not accept null values. The foreign key constraints are used to enforce referential integrity. E. What is a table called. 25. back up database. . 30. reducing server overhead. 29. Unindexed tables are good for fast storing of data. as the check constraints. to run during times of slow business activity. To get @@error and @@rowcount at the same time do both in same statement and store them in local variable. The IAM pages are the only structures that link the pages in a table together. boosting application performance. @ER = @@ERROR 27. 2. 26.g. A heap is a table that does not have a clustered index and. 23. Job steps give user control over flow of execution. User can also determine the order in which tasks run by creating job steps within a SQL Server Agent job.g. the pages are not linked by pointers. 3.
6. Windows services can run on your system even if you have not logged on to your computer. is used to install a Windows service. Can you share a process between Windows services? Yes. you can share a process between Windows services. The primary use of Windows services is to reduce the consumption of memory required for performing backend operations. How to implement one-to-one. also known as the project installer class. BCP does not copy the structures same as source to destination. you can use Windows services to reduce memory consumption. Which property of the ServiceBase class can be used to specify whether a service can be paused and resumed? . One-to-Many relationships are implemented by splitting the data into two tables with primary key and foreign key relationships. Let's take an example to understand this easily. Many-to-Many relationships are implemented using a junction table with the keys from both the tables forming the composite primary key of the junction table. 4.NET.hoc query and is a very useful tool for a developer to understand the performance characteristics of a query or stored procedure since the plan is the one that SQL Server will place in its cache and use to execute the stored procedure or query. these services do not have any user interface. Suppose you want to perform a variety of functions. While installing a Windows service. 32. In addition. and manage various devices. are applications that are installed on the system as system services. it is true. 5. Windows services are applications that run in the background with the Windows operating system. 3. From within Query Analyzer is an option called "Show Execution Plan" (located on the Query drop-down menu). BULK INSERT command helps to import a data file into a database table or view in a user-specified format. In such a case. 2. check the status of an application. If this option is turned on it will display query execution plan in separate window when query is ran again. 33. In other words. In addition. an EventLogInstaller class is automatically created to install the event log related to the particular service.31. In .NET is used to install a Windows service? The ServiceInstaller class. such as printers. previously known as NT services. 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. What is an execution plan? When would you use it? How would you view the execution plan? An execution plan is basically a road map that graphically or textually shows the data retrieval methods chosen by the SQL Server query optimizer for a stored procedure or ad. which is the parent class to create all Windows services? The ServiceBase class is the parent class to create all Windows services. What is BCP? When does it used? BulkCopy is a tool used to copy huge amount of data from tables and views. What are Windows services? Windows services. Is it true? Yes. such as monitor the performance of your computer or application. Which class in .
.The CanPauseAndContinue property provides such type of service.