SQL Interview Questions
SQL Interview Questions
SQL Interview Questions
Ans.
MySQl Server Vs SQL Server
Cloud-based No No
Supported It supports C#, PHP, Python, It supports c++, C#, Java, PHP,
Programming Lang Ruby, R, Visual Basic, Java Perl, Python, Ruby, Tcl, Delphi, D
etc etc
3. 1NF – Removes duplicated attributes, Attribute data should be atomic, and attribute should be same kind.
4. 2NF – Should be in 1NF and each non-key is fully dependent on the primary key.
5. 3NF – Should be in 2NF and all the non-key attributes which are not dependent on the primary key should be
removed. All the attributes which are dependent on the other non-key attributes should also be removed.
Normalization is done in OLTP.
2. One to Many –For each instance in the first entity there can be one or more in the second entity. For each
instance in the second entity there can be one and only one instance in the first entity.
3. Many to Many –For each instance in the first entity there can be one or more instance in the second entity and
moreover, for each instance in the second entity there can be one or more instance in the first entity.
Unique Key
1.Enforces uniqueness of the column in a table.
2.Alternate key –If the table has more than one candidate keys and when one becomes a primary key the rest
becomes alternate keys.
3.Composite key –More than one key uniquely identify a row in a table.
Q7) What are defaults? Is there a column to which a default can’t be bound?
Ans. 1.It is a value that will be used by a column if no value is supplied to that column
while inserting data.
2.I can’t be assigned for identity and timestamp values.
Q8) What are user defined data types and when you should go for them?
Ans. Lets you extend the base SQL server data types by providing a descriptive name
and format to the database.
E.g. Flight_num appears in many tables and all these tables have varchar(8)
Create a user defined data-type
Q9) What is a transaction and what are ACID properties?
Ans. A transaction is a logical unit of work in which, all the steps must be performed or
none. ACID stands for Atomicity, Consistency, Isolation, and Durability. These are the
properties of a transaction.
Q10) What part does database design have to play in the performance of a SQL Server-
based application?
Ans. It plays a very major part. When building a new system, or adding to an existing
system, it is crucial that the design is correct. Ensuring that the correct data is captured
and is placed in the appropriate tables, that the right relationships exist between the
tables and that data redundancy is eliminated is an ultimate goal when considering
performance. Planning a design should be an iterative process, and constantly reviewed
as an application is developed. It is rare, although it should be the point that everyone
tries to achieve, when the initial design and system goals are not altered, no matter how
slightly. Therefore, a designer has to be on top of this and ensure that the design of the
database remains efficient..
Q11) What can a developer do during the logical and physical design of a database in
order to help ensure that their database and SQL Server-based application will perform
well?
Ans. A developer must investigate volumes of data (capacity planning), what types of
information will be stored, and how that data will be accessed. If you are dealing with an
upgrade to an existing system, analyzing the present data and where existing data
volumes occur, how that data is accessed and where the current response bottlenecks
are occurring, can help you search for problem areas in the design.
A new system would require a thorough investigation of what data will be captured, and
looking at volumes of data held in other formats also will aid design. Knowing your data
is just as important as knowing the constituents of your data. Also, constantly revisit
your design. As your system is built, check relationships, volumes of data, and indexes
to ensure that the physical design is still at its optimum. Always be ready to check your
system by using tools like the SQL Server Profiler.
Q12) What are the main steps in Data Modeling?
Ans.
1.Logical – Planning, Analysis and Design
Q17) What is an extended stored procedure? Can you instantiate a COM object by using
T-SQL?
Q18) What is the system function to get the current user’s userid?
Ans. USER_ID(). Also check out other system functions like USER_NAME(),
SYSTEM_USER, SESSION_USER, CURRENT_USER, USER, SUSER_SID(),
HOST_NAME().
Q19) What are triggers? How many triggers you can have on a table? How to invoke a
trigger on demand?
Ans. Triggers are special kind of stored procedures that get executed automatically
when an INSERT, UPDATE or DELETE operation takes place on a table. In SQL
Server 6.5 you could define only 3 triggers per table, one for INSERT, one for UPDATE
and one for DELETE. From SQL Server 7.0 onwards, this restriction is gone, and you
could create multiple triggers per each action. But in 7.0 there’s no way to control the
order in which the triggers fire. In SQL Server 2000 you could specify which trigger fires
first or fires last using sp_settriggerorder.
Triggers can’t be invoked on demand. They get triggered only when an associated
action (INSERT, UPDATE, DELETE) happens on the table on which they are defined.
Triggers are generally used to implement business rules, auditing. Triggers can also be
used to extend the referential integrity checks, but wherever possible, use constraints
for this purpose, instead of triggers, as constraints are much faster.
Till SQL Server 7.0, triggers fire only after the data modification operation happens. So
in a way, they are called post triggers. But in SQL Server 2000 you could create pre
triggers also – INSTEAD OF triggers.
Virtual tables – Inserted and Deleted form the basis of trigger architecture.
Ans. Self join is just like any other join, except that two instances of the same table will
be joined in the query. Here is an example: Employees table which contains rows for
normal employees as well as managers. So, to find out the managers of all the
employees, you need a self join.
1
2 CREATE TABLE emp
3 (
4 empid int,
mgrid int,
5 empname char(10)
6 )
7 INSERT emp SELECT 1,2,’Vyas’
8 INSERT emp SELECT 2,3,’Mohan’
9 INSERT emp SELECT 3,NULL,’Shobha’
INSERT emp SELECT 4,2,’Shridhar’
10 INSERT emp SELECT 5,2,’Sourabh’
11 SELECT t1.empname [HDEV:Employee], t2.empname [HDEV:Manager]
12 FROM emp t1, emp t2
13 WHERE t1.mgrid = t2.empid
14
Here’s an advanced query using a LEFT OUTER JOIN that even returns the employees
without managers (super bosses)
1 SELECT t1.empname [HDEV:Employee], COALESCE(t2.empname, ‘No manager’)
2 [HDEV:Manager]
3 FROM emp t1
LEFT OUTER JOIN
4 emp t2
5 ON
6 t1.mgrid = t2.empid
Explore SQL Server Sample Resumes! Download & Edit, Get Noticed by Top Employers!Download Now!
You can use index hint (index=index_name) after the table name. SELECT au_lname
FROM authors (index=aunmind)
The ORDER BY clause sorts query results by one or more columns up to 8,060 bytes.
This will happen by the time when we retrieve data from database. Clustered indexes
will physically sort data, while inserting/updating the table.
Referential integrity refers to the consistency that must be maintained between primary
and foreign keys, i.e. every foreign key value must have a corresponding primary key
value
Q27) What is the purpose of UPDATE STATISTICS?
It updates information about the distribution of key values for one or more statistics
groups (collections) in the specified table or indexed view.
It returns the most recently created identity value for the tables in the current execution
scope.
Q29) What do you consider are the best reasons to use stored procedures in your
application instead of passing Transact-SQL code directly to SQL Server?
First and foremost, a stored procedure is a compiled set of code, where passing T-SQL
through languages such as VB, Visual FoxPro, etc., means that the set of code needs
to be compiled first. Although T-SQL within VB, etc., can be prepared before running,
this is still slower than using a stored procedure. Then, of course, there is the security
aspect, where, by building a stored procedure, you can place a great deal of security
around it. When dealing with sensitive data, you can use an encrypted stored procedure
to hide sensitive columns, calculations, and so on. Finally, by using a stored procedure,
I feel that transactional processing becomes a great deal easier and, in fact, using
nested transactions become more insular and secure. Having to deal with transactions
within code that may have front end code, will slow up a transaction and therefore a lock
will be held for longer than necessary.
Q30) What are some techniques for writing fast performing stored procedures?
Fast performing stored procedures are like several other areas within T-SQL. Revisiting
stored procedures every six months or so, to ensure that they are still running at their
optimum performance is essential. However, actual techniques themselves include
working with as short a transaction area as possible, as lock contention will certainly
impact performance. Recompiling your stored procedures after index additions if you
are unable or not wishing to restart SQL Server, will also ensure that a procedure is
using the correct index, if that stored procedure is accessing the table which has
received the new index. If you have a T-SQL command that joins several tables, and it
takes a long time to return a value, first of all check out the indexes. But what you may
find tends to help, is to break down the code and try to determine which join it is that is
causing the performance problem. Then analyze this specific join and see why it is a
problem.
Always check out a stored procedure’s performance as you build it up by using the
SHOWPLAN commands.
Also, try to use EXISTS, rather than a JOIN statement. An EXISTS statement will only
join on a table until one record is found, rather than joining all the records . Also, try to
look at using sub queries when you are trying to find a handful of values in the sub
query statement, and there is no key on the column you are looking up on.
Q31) When should SQL Server-based cursors be used, and not be used?
SQL Server cursors are perfect when you want to work one record at a time, rather than
taking all the data from a table as a single bulk. However, they should be used with care
as they can affect performance, especially when the volume of data increases. From a
beginner’s viewpoint, I really do feel that cursors should be avoided every time because
if they are badly written, or deal with too much data, they really will impact a system’s
performance. There will be times when it is not possible to avoid cursors, and I doubt if
many systems exist without them. If you do find you need to use them, try to reduce the
number of records to process by using a temporary table first, and then building the
cursor from this. The lower the number of records to process, the faster the cursor will
finish. Always try to think “out of the envelope”.
Q32) What alternatives do developers have over using SQL Server-based cursors? In
other words, how can developers perform the same function as a cursor without using a
cursor?
Perhaps one of the performance gains least utilized by developers starting out in SQL
Server are temporary tables. For example, using one or more temporary tables to break
down a problem in to several areas could allow blocks of data to be processed in their
own individual way, and then at the end of the process, the information within the
temporary tables merged and applied to the underlying data. The main area of your
focus should be, is there an alternative way of doing things? Even if I have to break this
down into several chunks of work, can I do this work without using cursors, and so
result in faster performance. Another area that you can look at is the use of CASE
statements within your query. By using a CASE statement, you can check the value
within a column and make decisions and operations based on what you have found.
Although you will still be working on a whole set of data, rather than a subset found in a
cursor, you can use CASE to leave values, or records as they are, if they do not meet
the right criteria. Care should be taken here though, to make sure that by looking at all
the data, you will not be creating a large performance impact. Again, look at using a
subset of the data by building a temporary table first, and then merging the results in
afterwards. However, don’t get caught out with these recommendations and do any of
them in every case. Cursors can be faster if you are dealing with small amounts of data.
However, what I have found, to be rule number one, is get as little data in to your cursor
as is needed.
Q33) If you have no choice but to use a SQL Server-based cursor, what tips do you have
in order to optimize them?
Perhaps the best performance gain is when you can create a cursor asynchronously
rather than needing the whole population operation to be completed before further
processing can continue. Then, by checking specific global variables settings, you can
tell when there is no further processing to take place. However, even here, care has to
be taken. Asynchronous population should only occur on large record sets rather than
those that only deal with a small number of rows. Use the smallest set of data possible.
Break out of the cursor loop as soon as you can. If you find that a problem has
occurred, or processing has ended before the full cursor has been processed, then exit.
If you are using the same cursor more than once in a batch of work, and this could
mean within more than one stored procedure, then define the cursor as a global cursor
by using the GLOBAL keyword, and not closing or deallocating the cursor until the
whole process is finished. A fair amount of time will be saved, as the cursor and the
data contained will already be defined, ready for you to use.
DATABASE PERFORMANCE OPTIMIZATION / TUNING
Q34) 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 lot of reasons behind the poor
performance of a query. But some general issues that you could talk about would be:
1. No indexes
2. No Table scans
4. Blocking
This means the transaction finish completely, or it will not occur at all.
Consistency means that the transaction will repeat in a predictable way each time it is
performed.
The data the transactions are independent of each other. The success of one
transaction doesn’t depend on the success of another.
Guarantees that the database will keep track of pending changes so that the server will
be able to recover if an error occurs.
A DBMS is a set of software programs used to manage and interact with databases.
It is a set of software programs used to interact with and manage relational databases.
Relational databases are databases that contain tables.
Q45) What is business intelligence?
Database normalization is the process of organizing the fields and tables of a relational
database to minimize redundancy and dependency.
The way in which two or more concepts/entities are connected, or the state of being
connected.
An OLTP is the process of gathering the data from the users, and a database is the
initial information.
Q55) What is the difference between a derived attribute, derivedpersistent attribute, and
computed column?
A derived attribute is a attribute that is obtained from the values of other existing
columns and does not exist on it’s own. A derived persistent attribute is a derived
attribute that is stored. A computed attribute is a attribute that is computed from internal
system values.
Q57) Is the relationship between a strong and weak entity always identifying?
No.
Q60) Describe what you know about PK, FK, and UK.
Primary keys – Unique clustered index by default, doesn’t accept null values, only one
primary key per table.
Foreign Key – References a primary key column. Can have null values. Enforces
referential integrity.
Unique key – Can have more than one per table. Can have null values. Cannot have
repeating values. Maximum of 999 clustered indexes per table.
Q61) What do you mean by CTEs? How will you use it?
CTEs also known as common table expressions are used to create a temporary table
that will only exist for the duration of a query. They are used to create a temporary table
whose content you can reference in order to simplify a queries structure.
Q63) What would the command: DENY CREATE TABLE TO Peter do?
It wouldn’t allow the user Peter to perform the operation CREATE TABLE regardless of
his role.
Q64) What does the command: GRANT SELECT ON project TO Peter do?
Q65) What does the command: REVOKE GRANT SELECT ON project TO Peter do?
Database encryption, CDCs tables – For on the fly auditing of tables, Merge operation,
INSERT INTO – To bulk insert into a table from another table, Hierarchy attributes,
Filter indexes, C like operations for numbers, resource management, Intellisense – For
making programming easier in SSMS, Execution Plan Freezing – To freeze in place
how a query is executed.
What is new in SQL 2008 R2?
PowerPivot, maps, sparklines, data bars, and indicators to depict data.
A table variable is faster in most cases since it is held in memory while a temporary
table is stored on disk. However, when the table variable’s size exceeds memory size
the two table types tend to perform similarly.
Q68) How big is a tinyint, smallint, int, and bigint?
It will give you the number of active transactions for the current user.
Q70) What are the drawbacks of CTEs?
It is query bound.
Thursday
6:30 AM IST
13
JUL
Saturday
6:30 AM IST
14
JUL
Sunday
7:00 AM IST
16
JUL
Tuesday
6:30 AM IST
More Batches
It keeps a record of all activities that occur during a transaction and is used to roll back
changes.
Q72) What are before images, after images, undo activities and redo activities in relation
to transactions?
Before images refers to the changes that are rolled back on if a transaction is rolled
back. After images are used to roll forward and enforce a transaction. Using the before
images is called the undo activity. Using after images is called the redo activity.
A shared lock, locks a row so that it can only be read. An exclusive lock locks a row so
that only one operation can be performed on it at a time. An update lock basically has
the ability to convert a shared lock into an exclusive lock.
If you use TOP 3 WITH TIES *, it will return the rows, that have a similarity in each of
their columns with any of the column values from the returned result set.
By concurrently running the same resources that access the same information in a
transaction.
It is used for determining the amount of time that the system will wait for a lock to be
released.
It is used to determine whether a query returns one or more rows. If it does, the EXIST
function returns TRUE, otherwise, it will return FALSE.
SQL Query Interview Questions with Answers
Inner Join: It is used to retrieve matching records from both the tables
Department:
Department_No Department_Name
10 ECE
20 ECE
30 CSE
40 IT
Employee Details:
Employee_No Emp_Name Address Age Department_No Salary
Q1) Write a Query to display employee details who are working in ECE department?
Q4) Write a Query to display employee details whose sal>20000 and who is working in
ECE department?
1 SELECT employee.employee_no, employee.employee_name, employee.address,
2 employee.salary, employee.age
FROM department D
3 INNER JOIN employee E
4 ON dept.D_no=emp.D_no
5 WHERE dept.D_name=’ECE’ and E.salary>20000
5) Write a Query to display employee details along with department_name and who is
working in ECE department, whose name starts with a?
Q6) Write a Query to display employee details along with department_name and whose
age between 20 and 24?
Q7) Write a Query to display employee details along with department_name and who are
staying in hyderabad?
Q8) Write a Query to display employee details whose salary>20000 and whose age>20 &
who is working in ECE department?
S2 AP
S3 Tamil Nadu
S4 Karnataka
S5 Kerala
City
City ID City Name State ID
1 Hyderabad S1
2 Vizag S2
3 Vijayawada S2
4 Chennai S3
5 Madhurai S3
6 Bangalore S4
Blood Group Details
Blood Group ID Blood Group
B1 A+ve
B2 B+ve
B3 AB +ve
B4 A -ve
B5 O +ve
Donor Details
Donor ID Donor Name Phone Number City ID Blood Group ID
D1 Anil 9999 1 B1
D2 Sunil 8888 1 B1
D3 Ajay 7777 2 B1
D4 John 6666 4 B3
D5 James 5555 4 B5
1 SELECT C.City_Name
2 FROM State S
3 INNER JOIN City C
4 ON S.State_ID
WHERE S.State_Name ‘AP’
5
Q11) Write a Query to display Donor_ID, Donor_Name, Phone No, Blood Group?
Q12) Write a Query to display Donor_ID, Donor_Name, Phone No and who are staying in
hyderabad?
Q13) Write a Query to display donor details whose blood group is A +ve?
Q14) Write a Query to display Donor_ID, Donor_Name, Phone No, City, Blood Group?
SELECT D.Donor_ID, D_Name, D_Phone No, C.City_Name B.Blood_Group
1 FROM Blood B
2 INNER JOIN Donor D
3 ON D.Blood_ID=B.Donor_Name
4 INNER JOIN City C
ON D.City_ID=C.City_ID
5
6
Q15) Write a Query to display Donor_Name, Phone No, Blood Group of the donors who is
staying in hyderabad and whose blood group is A+ve?
1
SELECT D.Donor_Name, D. Phone_Number, B.Blood_Group
2 FROM Donor D
3 INNER JOIN Blood B
4 ON D.Blood_ID=B.Blood_ID
5 INNER JOIN City C
6 ON D.City_ID=C.City_ID
WHERE C.City_Name=’hyderabad’ and B.Blood_Group=’A+ve’
7
Outer Join A join that includes rows even if they do not have related rows in the joined table is an Outer
Join.. You can create three different outer join to specify the unmatched rows to be included:
101 Anil 10
102 Sunil 20
103 Ajay 30
104 Vijay 40
10 EEE
20 EEE
30 CSE
Null Null
50 IT
1 SELECT e.*
2 FROM Employee E
3 LEFT OUTER JOIN Department D
4 ON E.D_no
WHERE D.D_No IS NULL
5
1 SELECT *
2 FROM Employee E
3 WHERE E_No=101
Q18) Write a Query to display employee details where employee number is null?
1 SELECT *
2 FROM Employee E
3 WHERE E_No IS NULL
1 SELECT D.*
2 FROM Employee E
3 RIGHT OUTER JOIN Department D
4 ON E.D.No=D.D_No
WHERE E.D_No IS NULL
5
Q20) Write a Query to display all the records from the table except matching records?
1 ECE
2 CSE
3 EEE
Course Details Table
Course_ID Course_Name Cr
1 EDC 4
2 PDC 4
3 SS 4
4 DAA 4
5 OS 4
Student Details Table
Student_No Student_Name
101 Anil
102 Sunil
103 Ajay
104 Vijay
105 John
Enroll Details Table
Enroll_Date Student_No Dpet_No S_ID
1/2/2014 101 10 S1
3/2/2016 102 10 S1
3/2/2016 104 20 S2
3/2/2016 105 20 S2
Address Table
Emp_No Address
E1 Hyderabad
E2 Vizag
E3 Hyderabad
E4 Bangalore
E5 Hyderabad
Employee Details Table
Emp_No Emp_Name
E1 Arun
E2 Kiran
E3 Kumar
E4 Anus
E5 James
Semester Details Table
Semester Sn
S1 1
S2 2-1
S3 2-2
S4 3-1
S5 3-2
S6 4-1
S7 4-2
Course Department Details
Dept_No Course_ID
10 1
10 2
10 3
20 4
20 5
Syllabus Table
Dept_No Course_ID S_ID
10 1 S1
10 2 S1
10 3 S1
20 4 S2
20 5 S2
Instructor Details Table
Emp_No Dept_No
E1 10
E2 10
E3 10
E4 20
E5 30
Course Instructor Table
Course_ID Emp_No S_ID Dept_No
1 E1 S1 10
1 E1 S1 20
1 E2 S1 30
2 E3 S1 10
4 E4 S2 20
5 E4 S2 20
5 E5 S1 10
Q) Write a query to display Student No, Student Name, Enroll Date, Department Name?
Q) Write a query to display Employee Number, Employee Name and address, department
name?
1
SELECT E.Emp_No, E.Emp_Name, A.Address, D.Dept_Name
2 FROM Employee E
3 INNER JOIN Address A
4 ON E.Emp_No=A.Emp_No
5 INNER JOIN Instructor I
6 ON A.Emp_No=I.Emp_No
INNER JOIN Department D
7 ON I.Dept_No=D.Dept_No
8
1
SELECT C.Course_Name
2 FROM Department D
3 INNER JOIN Course Department CD
4 ON D.Dept_NO=CD.Dept_NO
5 INNER JOIN Course C
ON CD.CourseDept_ID=C.Course_ID
6 WHERE D.Dept_Name=’ECE’
7
Q) ) Write a query to display student number, student name, enroll date, dept name,
semester name?
1 SELECT C.Course_Name
2 FROM Department D
3 INNER JOIN Syllabus Sy
ON D.Dept_No=Sy.Dept_No
4 INNER JOIN Course C
5 ON Sy.Course_ID=C.Course_ID
6 INNER JOIN Semester Se
7 ON Syllabus_Sy_ID=Se_Sy_ID
8 WHERE D.Dept_Name=’ECE’ and Se.Semester=’1’
9
Q) Write a query to display the employee names and faculty names of ECE dept 1st
year?
1
2 SELECT E.Emp_Name
FROM Employee E
3 INNER JOIN Course Instructor Ci
4 ON E.Emp_No=Ci.Emp_No
5 INNER JOIN Semester Se
6 ON Se.Student_ID=Ci.Student_ID
INNER JOIN Dept D
7 ON Ci.Dept_No=D.Dept_No
8 WHERE D.Dept_Name=’ECE’ and Se.Student_Name=’1’
9
Q) ) Write a query to display student details who enrolled for ECE department?
1
SELECT S.Student_NO, S.Student_Name, S.Enroll_Date
2 FROM Student S
3 INNER JOIN Enroll E
4 ON S.Student_No=E.Student_No
5 INNER JOIN Department D
ON E.Dept_No=D.Dept_No
6 WHERE D.Dept_Name=’ECE’
7
Q) ) Write a query to display student details along with dept name who are enrolled in
ECE department first year?
1
SELECT S.Student_No, S.Student_Name, S.Enroll_Date, D.Dept_Name
2
FROM Student S
3 INNER JOIN Enrollment E
4 ON S.Student_No=E.Student_No
5 INNER JOIN Department D
6 ON D.Dept_No=E.Dept_No
INNER JOIN Semester Se
7 ON E.Student_ID=Se.Student_ID
8 WHERE D.Dept_Name=’ECE’ and Se.Student_Name=’1’
9
1 SELECT E.Emp_Name
2 FROM Employee E
INNER JOIN Course Instructor Ci
3 ON E.Emp_No=Ci.Emp_No
4 INNER JOIN Course C
5 ON Ci.Course_ID=C.Course_ID
6 WHERE C.Course_Name=’EDC’
7
Q) ) Write a query to display employee details along with dept name who are staying in
Hyderabad?
1
2 SELECT E.Emp_No, Emp_Name, D.Dept_Name
FROM Employee E
3 INNER JOIN Address A
4 ON E.Emp_No=A.Emp_No
5 INNER JOIN Instructor I
6 ON A.Emp_No=I.Emp_No
INNER JOIN Department D
7 ON I.Dept_No=D.Dept_No
8 WHERE A.Address=’hyderabad’
9
Q) Write a Query to display employee details whose salary > 20000 and whose age >23?
Q) Write a Query to display employee details whose salary >20000 and who is working in
ECE department?
Q) Write a Query to display employee details whose age is BETWEEN 18 and 22?
Q) Write a Query to display employee details whose salary range BETWEEN 20000 and
23000?
1 SELECT * FROM Employee
2 WHERE Salary BETWEEN 20000 AND 23000;
Q) Write a Query to display employee details whose age is NOT BETWEEN 18 & 22?
Q) Write a Query to display employee details and whose age>20 & whose name starts
with a?
Q) Write a Query to display employee details whose name not starts with a?
SSIS Power BI
SSRS SharePoint
Modes can be changed by selecting the tools menu of SQL Server configuration
properties and choose security page.
SQL Profiler is a tool which allows system administrator to monitor events in the
SQL server. This is mainly used to capture and save data about each event of a file
or a table for analysis.
SQL Server supports recursive stored procedure which calls by itself. Recursive
stored procedure can be defined as a method of problem solving wherein the
solution is arrived repetitively. It can nest up to 32 levels.
4. What are the differences between local and global temporary tables?
Local temporary tables are visible when there is a connection, and are
deleted when the connection is closed.
A CHECK constraint can be applied to a column in a table to limit the values that
can be placed in a column. Check constraint is to enforce integrity.
SQL server can be connected to any database which has OLE-DB provider to give a
link. Example: Oracle has OLE-DB provider which has link to connect with the SQL
server group.
A sub-query is a query which can be nested inside a main query like Select, Update,
Insert or Delete statements. This can be used when expression is allowed.
Properties of sub query can be defined as
The SQL Server agent plays a vital role in day to day tasks of SQL server
administrator(DBA). Server agent's purpose is to implement the tasks easily with the
scheduler engine which allows our jobs to run at scheduled date and time.
10. What are scheduled tasks in SQL Server?
Scheduled tasks or jobs are used to automate processes that can be run on a
scheduled time at a regular interval. This scheduling of tasks helps to reduce human
intervention during night time and feed can be done at a particular time. User can
also order the tasks in which it has to be generated.
COALESCE is used to return first non-null expression within the arguments. This
function is used to return a non-null from more than one column in the arguments.
Example –
FLOOR(6.7)
Returns 6.
14. Can we check locks in database? If so, how can we do this lock check?
Yes, we can check locks in the database. It can be achieved by using in-built stored
procedure called sp_lock.
Example –
SIGN(-35) returns -1
Insert
Delete
Update
Instead of
IDENTITY column is used in table columns to make that column as Auto incremental
number or a surrogate key.
Bulkcopy is a tool used to copy large amount of data from Tables. This tool is used
to load large amount of data in SQL Server.
20. What will be query used to get the list of triggers in a database?
22. How Global temporary tables are represented and its scope?
Global temporary tables are represented with ## before the table name. Scope will
be the outside the session whereas local temporary tables are inside the session.
Session ID can be found using @@SPID.
23. What are the differences between Stored Procedure and the dynamic SQL?
Stored Procedure is a set of statements which is stored in a compiled form. Dynamic
SQL is a set of statements that dynamically constructed at runtime and it will not be
stored in a Database and it simply execute during run time.
Collation is defined to specify the sort order in a table. There are three types of sort
order –
1. Case sensitive
2. Case Insensitive
3. Binary
Following are the queries can be used to get the count of records in a table -
Select * from <tablename> Select count(*) from <tablename> Select rows from sysindexes where
id=OBJECT_ID(tablename) and indid<2
26. What is the command used to get the version of SQL Server?
Select SERVERPROPERTY('productversion')
By default, NOCOUNT is set to OFF and it returns number of records got affected
whenever the command is getting executed. If the user doesn't want to display the
number of records affected, it can be explicitly set to ON- (SET NOCOUNT ON).
29. Which SQL server table is used to hold the stored procedure scripts?
31. What is the difference between SUBSTR and CHARINDEX in the SQL
Server?
The SUBSTR function is used to return specific portion of string in a given string.
But, INSTR function gives character position in a given specified string.
SUBSTR("Smiley",3)
CHARINDEX("Smiley",'i',1)
ISNULL function is used to check whether value given is NULL or not NULL in sql
server. This function also provides to replace a value with the NULL.
FOR clause is mainly used for XML and browser options. This clause is mainly used
to display the query results in XML format or in browser.
For SQL Server 2008 100 Index can be used as maximum number per table. 1
Clustered Index and 999 Non-clustered indexes per table can be used in SQL
Server.
1000 Index can be used as maximum number per table. 1 Clustered Index and 999
Non-clustered indexes per table can be used in SQL Server.
1 Clustered Index and 999 Non-clustered indexes per table can be used in SQL
Server.
36. What is the difference between COMMIT and ROLLBACK?
Varchar and nvarchar are same but the only difference is that nvarhcar can be used
to store Unicode characters for multiple languages and it also takes more space
when compared with varchar.
39. What is the command used to Recompile the stored procedure at run
time?
Stored Procedure can be executed with the help of keyword called RECOMPILE.
Example
Duplicate rows can be deleted using CTE and ROW NUMER feature of SQL Server.
41. Where are SQL Server user names and passwords stored in SQL Server?
Both are same but GETDATE can give time till milliseconds and SYSDATETIME
can give precision till nanoseconds. SYSDATE TIME is more accurate than
GETDATE.
43. How data can be copied from one table to another table?
SELECT INTO
This command is used to create a new table and its structure and data can be
copied from existing table.
TABLESAMPLE is used to extract sample of rows randomly that are all necessary
for the application. The sample rows taken are based on the percentage of rows.
RAISEERROR is the command used to generate and initiates error processing for a
given session. Those user defined messages are stored in sys.messages table.
XML data type is used to store XML documents in the SQL Server database.
Columns and variables are created and store XML instances in the database.
CDC is abbreviated as Change Data Capture which is used to capture the data that
has been changed recently. This feature is present in SQL Server 2008.
49. What are the methods used to protect against SQL injection attack?
Following are the methods used to protect against SQL injection attack:
Filtered Index is used to filter some portion of rows in a table to improve query
performance, index maintenance and reduces index storage costs. When the index
is created with WHERE clause, then it is called Filtered Index
Full
Simple
Bulk-Logged
Q#5. What are different backups available in SQL Server?
Ans. Different possible backups are:
Full backup
Differential Backup
Transactional Log Backup
Copy Only Backup
File and Filegroup backup
Q#6. What is a FULL Backup?
Ans. A full backup is the most common type of backup in SQL Server. This is the complete
backup of the database. It also contains part of transaction log so it can be recovered.
Q#7. What is OLTP?
Ans. OLTP means Online transaction processing which follows rules of data normalization to
ensure data integrity. Using these rules complex information is broken down into a most simple
structure.
Q#8. What is RDBMS?
Ans. RDBMS or Relational Data Base Management Systems are database management systems
that maintain data in the form of tables. We can create relationships between the tables. An
RDBMS has the capability to recombine the data items from different files, providing powerful
tools for data usage.
Q#9. What are the properties of the Relational tables?
Ans. Relational tables have six properties:
Values are atomic.
Column values are of the same kind.
Each row is unique.
The sequence of columns is insignificant.
The sequence of rows is insignificant.
Each column must have a unique name.
Q#10. What's the difference between a primary key and a unique key?
Ans. The differences between the primary key and a unique key are:
The primary key is a column whose values uniquely identify every row in a table.
Primary key values can never be reused. They create a clustered index on the column and
cannot be null.
A Unique key is a column whose values also uniquely identify every row in a table but
they create a non-clustered index by default and it allows one NULL only.
Q#11. When is UPDATE_STATISTICS command used?
Ans. As the name implies UPDATE_STATISTICS command updated the statistics used by the
index to make the search easier.
Q#12. What is the difference between a HAVING CLAUSE and a WHERE CLAUSE?
Ans. The differences between HAVING CLAUSE and WHERE CLAUSE are:
Both specify a search condition but Having clause is used only with the SELECT
statement and typically used with GROUP BY clause.
If GROUP BY clause is not used then Having behaved like WHERE clause only.
Q#13. What is Mirroring?
Ans. Mirroring is a high availability solution. It is designed to maintain a hot standby server
which is consistent with the primary server in terms of a transaction. Transaction Log records are
sent directly from principal server to a secondary server which keeps a secondary server up to
date with the principal server.
Q#14. What are the advantages of the Mirroring?
Ans. Advantages of Mirroring are:
It is more robust and efficient that Log shipping.
It has an automatic failover mechanism.
The secondary server is synced with the primary in near real time.
Q#15. What is Log Shipping?
Ans. Log shipping is nothing but the automation of backup and restores of a database from one
server to another standalone standby server. This is one of the disaster recovery solutions. If one
server fails for some reason we will have the same data available on the standby server.
Q#16. What are the advantages of Log shipping?
Blocking
Missing and unused indexes.
I/O bottlenecks
Poor Query plans
Fragmentation
Q#23. List the various tools available for performance tuning?
Ans. There are various tools available for performance tuning:
Dynamic Management Views
SQL Server Profiler
Server Side Traces
Windows Performance monitor.
Query Plans
Tuning advisor
Q#24. What is a performance monitor?
Ans. Windows performance monitor is a tool to capture metrics for the entire server. We can use
this tool for capturing events of SQL server also.
Some useful counters are – Disks, Memory, Processors, Network etc.
Q#25. What are 3 ways to get a count of the number of records in a table?
Ans. SELECT * FROM table_Name
SELECT COUNT(*) FROM table_Name
SELECT rows FROM indexes WHERE id = OBJECT_ID(tableName) AND indid< 2
Q#26. Can we rename a column in the output of SQL query?
Ans. Yes by using the following syntax we can do this.
SELECT column_name AS new_name FROM table_name;
Q#27. What is the difference between a Local and a Global temporary table?
Ans. If defined in inside a compound statement a local temporary table exists only for the
duration of that statement but a global temporary table exists permanently in the database but its
rows disappear when the connection is closed.
Q#28. What is the SQL Profiler?
Ans. SQL Profiler provides a graphical representation of events in an instance of SQL Server for
the monitoring and investment purpose. We can capture and save the data for further
analysis. We can put filters as well to captures the specific data we want.
Q#29. What do you mean by authentication modes in SQL Server?
Ans. There are two authentication modes in SQL Server.
Windows mode
Mixed Mode – SQL and Windows.
Q#30. How can we check the SQL Server version?
Ans. By running the following command:
SELECT @@Version
Q#48. Where SQL server usernames and passwords are stored in a SQL server?
Ans. They get stored in System Catalog Views sys.server_principals and sys.sql_logins.
Q#49. What are the properties of a transaction?
Ans. Generally, these properties are referred to as ACID properties. They are:
Atomicity
Consistency
Isolation
Durability
Q#50. Define UNION, UNION ALL, MINUS, INTERSECT?
Ans. UNION – returns all distinct rows selected by either query.
UNION ALL – returns all rows selected by either query, including all duplicates.
MINUS – returns all distinct rows selected by the first query but not by the second.
INTERSECT – returns all distinct rows selected by both queries.
Q#51. What is SQL Server used for?
Ans. SQL Server is one of the very popular Relational Database Management Systems. This is a
product from Microsoft to store and manage the information in the database.
Q#52. Which language is supported by SQL Server?
Ans. SQL Server is based upon the implementation of the SQL also known as Structured Query
Language to work with the data inside the database.
Q#53. Which is the latest version of SQL Server and when it is released?
Ans. SQL Server 2017 is the latest version of SQL Server that is available in the market and
Microsoft launched this on 2 October 2017 with the support of the Linux O/S.
Q#54. What are the various editions of SQL Server 2017 that are available in the market?
Ans. SQL Server 2017 is available in 4 editions. These are as follows:
Enterprise: This supports in leading the high performance for the Tier 1 database along
with the capability of supporting business intelligence and workloads of advanced
analytics.
Standard: This supports mid-tier applications to achieve fast performance. This can be
easily upgraded to an enterprise edition also without having any changes in the coding
part.
Express: This is available for free and supports the building
of web and mobile applications up to 10 GB in the size.
Developer: This supports building, testing and demonstrating applications in a non-
production.
Q#55. What are functions in the SQL Server?
Ans. Functions are the sequence of the statements which accepts inputs, process the inputs to
perform some specific task and then provides the outputs. Functions should have some
meaningful name but these should not start with a special character such as %,#,@, etc.
Q#56. What is a User-Defined function in the SQL Server and what is its advantage?
Ans. User-Defined Function is a function which can be written as per the needs of the user by
implementing your own logic. The biggest advantage of this function is that the user is not
limited to pre-defined functions and can simplify the complex code of pre-defined function by
writing a simple code as per the needs.
This returns Scalar value or a table.
Q#57. Explain the creation and execution of a user-defined function in the SQL Server?
Ans. A User-Defined function can be created in the following way:
DELETE TRUNCATE
Delete command is used to delete a row in a Truncate is used to delete all the rows
table. from a table.
You can rollback data after using delete
You cannot rollback data.
statement.
It is a DML command. It is a DDL command.
It is slower than truncate statement. It is faster.
Q2. What are the different subsets of SQL?
Q3. What do you mean by DBMS? What are its different types?
A DBMS allows a user to interact with the database. The data stored in the database
can be modified, retrieved and deleted and can be of any type like strings, numbers,
images etc.
Table: StudentInformation
Field: Stu Id, Stu Name, Stu Marks
A JOIN clause is used to combine rows from two or more tables, based on a related
column between them. It is used to merge two tables or retrieve data from there. There
are 4 joins in SQL namely:
Inner Join
Right Join
Left Join
Full Join
Q6. What is the difference between CHAR and VARCHAR2 datatype in SQL?
Both Char and Varchar2 are used for characters datatype but varchar2 is used for
character strings of variable length whereas Char is used for strings of fixed length. For
example, char(10) can only store 10 characters and will not be able to store a string of
any other length whereas varchar2(10) can store any length i.e 6,8,2 in this variable.
Constraints are used to specify the limit on the data type of the table. It can be specified
while creating or altering the table statement. The sample of constraints are:
NOT NULL
CHECK
DEFAULT
UNIQUE
PRIMARY KEY
FOREIGN KEY
SQL is a standard language which stands for Structured Query Language based on the
English language whereas MySQL is a database management system. SQL is the core
of relational database which is used for accessing and managing database, MySQL is
an RDMS (Relational Database Management System) such as SQL Server, Informix
etc.
Q10. What is a Unique key?
Apart from this SQL Interview Questions blog, if you want to get trained from
professionals on this technology, you can opt for a structured training from edureka!
Click below to know more.
Foreign key maintains referential integrity by enforcing a link between the data in
two tables.
The foreign key in the child table references the primary key in the parent table.
The foreign key constraint prevents actions that would destroy links between the
child and parent tables.
Data Integrity defines the accuracy as well as the consistency of the data stored in a
database. It also defines integrity constraints to enforce business rules on the data
when it is entered into an application or a database.
Q13. What is the difference between clustered and non clustered index in SQL?
The differences between the clustered and non clustered index in SQL are :
1. Clustered index is used for easy retrieval of data from the database and its faster
whereas reading from non clustered index is relatively slower.
2. Clustered index alters the way records are stored in a database as it sorts out
rows by the column which is set to be clustered index whereas in a non clustered
index, it does not alter the way it was stored but it creates a separate object
within a table which points back to the original table rows after searching.
3. One table can only have one clustered index whereas it can have many non
clustered index.
In SQL, there is a built-in function called GetDate() which helps to return the current
timestamp/date.
There are various types of joins which are used to retrieve data between the tables.
There are four types of joins, namely:
Inner join: Inner Join in MySQL is the most common type of join. It is used to return all
the rows from multiple tables where the join condition is satisfied.
Left Join: Left Join in MySQL is used to return all the rows from the left table but only
the matching rows from the right table where the join condition is fulfilled.
Right Join: Right Join in MySQL is used to return all the rows from the right table but
only the matching rows from the left table where the join condition is fulfilled.
Full Join: Full join returns all the records when there is a match in any of the tables.
Therefore, it returns all the rows from the left-hand side table and all the rows from the
right-hand side table.
Denormalization refers to a technique which is used to access data from higher to lower
forms of a database. It helps the database managers to increase the performance of the
entire infrastructure as it introduces redundancy into a table. It adds the redundant data
into a table by incorporating database queries that combine data from various tables
into a single table.
Entities: A person, place, or thing in the real world about which data can be stored in a
database. Tables store data that represents one type of entity. For example – A bank
database has a customer table to store customer information. Customer table stores
this information as a set of attributes (columns within the table) for each customer.
Relationships: Relation or links between entities that have something to do with each
other. For example – The customer name is related to the customer account number
and contact information, which might be in the same table. There can also be
relationships between separate tables (for example, customer to accounts).
This index does not allow the field to have duplicate values if the column is unique
indexed. If a primary key is defined, a unique index can be applied automatically.
Clustered Index:
This index reorders the physical order of the table and searches based on the basis of
key values. Each table can only have one clustered index.
Non-Clustered Index:
Non-Clustered Index does not alter the physical order of the table and maintains a
logical order of the data. Each table can have many nonclustered indexes.
Apart from this SQL Interview Questions Blog, if you want to get trained from
professionals on this technology, you can opt for a structured training from
edureka! Click below to know more.
Atomicity: Atomicity refers to the transactions that are completely done or failed
where transaction refers to a single logical operation of a data. It means if one part
of any transaction fails, the entire transaction fails and the database state is left
unchanged.
Consistency: Consistency ensures that the data must meet all the validation rules.
In simple words, you can say that your transaction never leaves the database
without completing its state.
Durability: Durability means that if a transaction has been committed, it will occur
whatever may come in between such as power loss, crash or any sort of error.
1. Arithmetic Operators
2. Logical Operators
3. Comparison Operators
Apart from this SQL Interview Questions blog, if you want to get trained from
professionals on this technology, you can opt for a structured training from
edureka! Click below to know more.
Correlated subquery: These are queries which select the data from a table
referenced in the outer query. It is not considered as an independent query as it
refers to another table and refers the column in a table.
Apart from this SQL Interview Questions Blog, if you want to get trained from
professionals on this technology, you can opt for a structured training from
edureka! Click below to know more.
Group functions work on the set of rows and returns one result per group. Some of
the commonly used group functions are: AVG, COUNT, MAX, MIN, SUM, VARIANCE.
Example of BETWEEN:
SELECT * FROM Students where ROLL_NO BETWEEN 10 AND 50;
Example of IN:
SELECT * FROM students where ROLL_NO IN (8,15,25);
Q37. Why are SQL functions used?
SQL functions are used for the following purposes:
Apart from this SQL Interview Questions Blog, if you want to get trained from
professionals on this technology, you can opt for a structured training from
edureka! Click below to know more.
Using EXEC.
Using sp_executesql.
LOWER(‘string’)
UPPER(‘string’)
INITCAP: This function returns the string with the first letter in uppercase
and rest of the letters in lowercase. Syntax:
INITCAP(‘string’)
Apart from this SQL Interview Questions blog, if you want to get trained from
professionals on this technology, you can opt for a structured training from
edureka! Click below to know more.
Scalar functions return a single value based on the input value. For example –
UCASE(), NOW() are calculated with respect to string.
Q50. Name the operator which is used in the query for pattern matching?
Disadvantage:
The only disadvantage of Stored Procedure is that it can be executed only in the
database and utilizes more memory in the database server.
Scalar Functions
Inline Table-valued functions
Multi-statement valued functions
Scalar returns the unit, variant defined the return clause. Other two types of
defined functions return table.
Apart from this SQL Interview Questions Blog, if you want to get trained from
professionals on this technology, you can opt for a structured training from
edureka! Click below to know more.
These variables can be used or exist only inside the function. These variables are
not used or referred by any other function.
Global variables:
These variables are the variables which can be accessed throughout the program.
Global variables cannot be created whenever that function is called.
AUTO INCREMENT keyword can be used in Oracle and IDENTITY keyword can be
used in SQL SERVER.
Select SQL Server Configuration Properties, and choose the Security page.
REPLACE function: This function is used to replace the existing characters of all
the occurrences. Syntax:
REPLACE (string_expression, search_string, replacement_string)
Here every search_string in the string_expression will be replaced with the
replacement_string.
Deleting is one the most expensive operation, it's logged. Every row deleted is logged to the
transaction log.
Delete from ... allows to you delete specific rows.
Delete from ... marks the row as a ghost row.
Delete from ... does not release the space of the deleted rows, you will need to run DBCC
SHRINKFILE to recover the space [single user mode].
Truncate in MSSQL
Often people want to empty a temporary table to repopulate it with current data, then it's much
faster to use the truncate statement instead of the delete statement.
truncate table is the most efficient way of emptying a table.
It's not possible to use the truncate table when you only want to delete some rows based on a
condition.
Truncate table does not delete rows, it deallocates the data pages and release the space.
Truncate table cannot be used when the table is referenced by a foreign key or involved in data
replication.
Truncate table is recommended for temporary tables that need to be cleared for the next process.
A subquery in the main query that has to be placed on the right-hand side of the comparison
operator
A subquery has to be placed parenthesis, in order to get executed first before the main query.
It cannot have any order by clause.
More than one subquery can be included in the main query.
Insert
Update
Delete
Instead of
Binary
Case sensitive
Case insensitive.
Recursive stored procedure – It is defined as a process of resolving a problem where the solution occurs
repetitively.This can be nested up to 32 levels.
16. State the difference between Local and Global temporary tables?
Local temporary table – These tables are invisible when there is a connection and are deleted when it is
closed.
Global temporary table – These tables are visible to all users and are deleted when the connection is
closed.
18. What methods do you follow to protect from SQL injection attack?
Following methods are used to protect from SQL injection attack:
Select
Insert
Update
Delete
Create
Alter
Drop
Truncate
Grant
Revoke
28. What is SQL server agent and what are the two modes of authentication in SQL
Server?
SQL Server agent
The SQL Server agent plays an important part in the day to day tasks of the SQL Server Database
Administrator (DBA).
Its purpose is to implement the tasks easily with the Scheduler engine that allows our tasks to run at a
scheduled time and date.
Modes of Authentication in SQL Server
The two authentication modes in SQL Server are:
Windows Mode
Mixed Mode
From the tools menu of SQL Server configuration properties in the security page, the modes can be
changed.