SQL Server Q - A
SQL Server Q - A
1|Page
30) How many Aggregate Functions are available there in SQL?............................................43
31) What are Scalar Functions in SQL?..........................................................................................44
32) What are triggers?.........................................................................................................................44
33) What is View in SQL?....................................................................................................................44
34) How we can update the view?....................................................................................................44
35) Explain the working of SQL Privileges?...................................................................................45
36) How many types of Privileges are available in SQL?...........................................................45
37) What is SQL Injection?.................................................................................................................45
38) What is SQL Sandbox in SQL Server?......................................................................................45
39) What is the difference between SQL and PL/SQL?...............................................................46
40) What is the difference between SQL and MySQL?................................................................46
41) What is the use of NVL function?..............................................................................................46
42) What is the Cartesian product of table?...................................................................................46
43) What do you mean by Subquery?..............................................................................................46
44) How many row comparison operators are used while working with a subquery?........46
45) What is the difference between clustered and non-clustered indexes?..........................46
46) What is the difference between DELETE and TRUNCATE?.................................................47
47) What is the difference between DROP and TRUNCATE?.....................................................47
48) How to write a query to show the details of a student from Students table whose
name starts with K?.............................................................................................................................47
49) What is the difference between Nested Subquery and Correlated Subquery?..............47
50) What is Normalization? How many Normalization forms are there?................................47
51) What is Relationship? How many types of Relationship are there?.................................47
52) What do you mean by Stored Procedures? How do we use it?.........................................48
53) State some properties of Relational databases?...................................................................48
54) What are Nested Triggers?..........................................................................................................48
55) What is Cursor?.............................................................................................................................48
56) What is Collation?.........................................................................................................................48
57) What do we need to check in Database Testing?..................................................................48
58) What is Database White Box Testing?......................................................................................49
59) What is Database Black Box Testing?......................................................................................49
60) What are Indexes in SQL?...........................................................................................................49
2|Page
1) What is store procedure? How do they work? When do you use?
A stored procedure is a collection of SQL statements that has been created and stored in the
database.
It is a set of recompiled SQL statements that are used to perform a special task.
Stored procedures create once a time and calls it n number of times and also reduces the
network traffic and increase the performance.
3|Page
The user defined functions are created in the user defined database. This user defined function
can be “inline table valued function”, “scalar value function” or “multi statement table valued
function”.
The SQL function Summary:-
1. SQL function must be be return a value or a table value.
2. SQL function accepts only input parameters.
3. SQL functions can’t use in insert, update and delete in the database tables.
4. SQL functions can be nested up to 32 levels.
5. The user defined SQL function can have up to 1023 input parameters.
6. The user defined SQL function can't return XML data type and it is not support to
exception handling.
7. It is only call in the stored procedures and it is not support to the set options like
ROWCOUNT etc.
3) What is SQL view? Why use View instead of a Table? Advantages and
Drawbacks
What is SQL view?
The View is a virtual table, which not create physically, it create logically only. We insert, update
& delete the records from a view.
In view there are no any physical relations in the database and the view is a virtual table based
on the result set of an SQL statement.
Why use View instead of a Table?
A table contains data but the View dose not stored set of data values in a database and the
view is only a SELECT statement.
A view can combine columns/rows from multiple tables.
Views are work like a security layers and we can handle security issues.
Views can be used as security mechanisms and its display only those data that you granting the
permissions in this view.
Advantages of View:-
We can hide so of table columns.
Views can model complex joins easily.
Views are work like a security layers and we can handle security issues.
Drawbacks of View: -
When table is dropped or modified, view becomes inactive; it depends on the table objects.
4|Page
If we querying from views, it will takes more time than directly querying from the tables.
We can lose information about relations (primary, foreign keys).
How to create View “Virtual Table”?
Syntax:-
-- CREATE VIEWS
CREATE VIEW View_Name
AS
SELECT Column_Name
FROM Table_Name
WHERE your_Conditions
-- DROP VIEW
DROP VIEW [dbo].[vw_Active_Customers]
5|Page
4. Materialize them.
5. Redundancy
How do indexes help?
For Example, suppose is a student and studying a book and this book contains 10,000 pages.
In the first day I read some topic “abc” and next day I want to read some another topic “pqr”. I
will never manually go through page by page. It is very difficult to go there. In this situation, I
am using book index to find specific topic and go directly to this page because IDEX allow us to
search millions of record quickly!
What types of indexes?
1. Clustered
2. Non-clustered
3. Unique
4. Index with included columns
How does an index improve performance?
An index is a way to physically re-organise the records and used to run faster queries.
The index can be used as a pointer to the large table. It helps to find row quickly and then return
back to the user.
What are some best practices for creating indexes?
Some of the rules are to creating index as,
1. Index ALL primary keys columns (It is default).
2. Index ALL foreign keys columns
3. You create more indexes only when the queries are too slow otherwise ignoring it.
6|Page
CREATE INDEX INDEX_NAME ON TABLE_NAME (COLUMN_NAME_1, COLUMN_NAME_2);
--DROP INDEX
DROP INDEX INDEX_NAME;
7|Page
BEGIN
PRINT '* EmpName= '+@EmpName
PRINT ' EmpDepartment= '+@EmpDepartment
-- OPEN CURSOR
OPEN Cursor_Emply
-- FETCH CURSOR
FETCH Cursor_Emply INTO @EmpName,@EmpDepartment
WHILE(@@fetch_status=0)
BEGIN
PRINT '* EmpName= '+@EmpName
PRINT ' EmpDepartment= '+@EmpDepartment
-- CLOSE CURSOR
CLOSE Cursor_Emply
-- DEALLOCATE CURSOR
DEALLOCATE Cursor_Emply
END
8|Page
--WHILE LOOP WITH SELECT STATEMENT
DECLARE @Age INT
SET @Age = 30
WHILE (@Age >=18)
BEGIN
PRINT @Age
SET @Age = @Age + 1
END
GO
9|Page
DDL Triggers
There are three query actions that are used in SQL INSERT, UPDATE OR DELETE.
Syntax:-
--CREATE DATABASE TRIGGER TEMPLATE
CREATE TRIGGER <trigger_name, sysname, table_alter_drop_safety> ON DATABASE
FOR <data_definition_statements, , DROP_TABLE, ALTER_TABLE>
AS
IF IS_MEMBER ('db_owner') = 0
BEGIN
PRINT 'You must ask your DBA to drop or alter tables!'
ROLLBACK TRANSACTION
END
GO
-- BEFORE DELETE
SELECT 'Before DELETE'
DELETE FROM Employee
WHERE ID = 1
10 | P a g e
a. Right Outer Join
b. Left Outer Join
c. Full Outer Join
3. SELF JOIN
4. CROSS JOIN
5. MULTIPLE JOIN
All the Joins are work between the table’s key relations.
What is Left Outer Join in SQL? when would you use it?
In the LEFT OUTER JOIN, returns all the matched rows from the left table and matched rows
from right table. If the right table is not matched then will return NULL values.
What is Right Outer Join in SQL? when would you use it?
11 | P a g e
In the RIGHT OUTER JOIN, returns all the matched rows from the right table and matched rows
from left table. If the left table rows are not matched then return NULL values.
What is Full Outer Join in SQL? when would you use it?
FULL OUTER JOIN work between with both the LEFT OUTER and RIGHT OUTER JOINS. If
the condition is matched then returns matched rows otherwise returns NULL values.
There is no SELF JOIN keyword and it is used to compare values in a column with other values
in the same column in the same table.
For example,
In the above query, WHERE clause could be any given expression as per you!
12 | P a g e
8) What is @@ERROR in SQL? When we should use @@ERROR?
What is @@ERROR in SQL?
@@ERROR returns only current error information (error number and error) after T-SQL
statements executed.
@@ERROR returns 0, if the previous SQL statement has no errors otherwise return 1.
@@ERROR is used in basic error handling in SQL Server and @@ERROR is a global variable
of SQL and this @@ERROR variable automatically handle by SQL. If error is occurred set error
number otherwise reset 0.
It is work only within the current scope and also contains the result for the last operation only.
Syntax: - @@ERROR
Return Type: - INT
When we should use @@ERROR?
1. While executing any stored procedures
2. In the SQL statements like Select, Insert, Delete and Update etc.
3. In the Open, Fetch Cursor.
When we should use Try Catch Block?
The Try Catch Block is generally used where want to catch errors for multiple SQL statements.
The example as,
-- DECLARE RETURN TABLE
DECLARE @Return_Table TABLE (Code varchar(10)
,Message varchar(100), ID varchar(100))
--USE OF @@ERROR
IF (@@ERROR <> 0)
BEGIN
INSERT INTO @Return_Table (Code, Message, ID)
SELECT 'ERROR', 'An error occurred in updating the customer.', SCOPE_IDENTITY()
SELECT Code, Message, ID FROM @Return_Table
END
ELSE IF (@@ERROR = 1087)
BEGIN
INSERT INTO @Return_Table (Code, Message, ID)
SELECT 'ERROR', 'Must declare the table variable @Return_Table.', SCOPE_IDENTITY()
13 | P a g e
SELECT Code, Message, ID FROM @Return_Table
END
ELSE IF (@@ERROR = 547)
BEGIN
INSERT INTO @Return_Table (Code, Message, ID)
SELECT 'ERROR', 'A check constraint violation occurred.', SCOPE_IDENTITY()
SELECT Code, Message, ID FROM @Return_Table
END
ELSE
BEGIN
INSERT INTO @Return_Table (Code, Message, ID)
SELECT 'OK', 'SUCCESS', SCOPE_IDENTITY()
SELECT Code, Message, ID FROM @Return_Table
END
GO
14 | P a g e
ERROR_LINE():Will return error line number.
ERROR_PROCEDURE():Will return stored procedure name that occurred the error.
ERROR_MESSAGE():Will return full message text of the error.
Syntax:-
BEGIN TRY
---YOUR CODE LOGIC
END TRY
BEGIN CATCH
---YOUR ERRORS HANDLER
END CATCH
-- ============================================================
-- ABOUT : TRY CATCH IN SQL SERVER STORED PROCEDURE
-- CREATE DATE: 22/04/2015
-- DESCRIPTION: RETURNS [LISTEVENT]
-- PARAMETERS: FROMDATE, TODATE
-- =============================================================
CREATE PROCEDURE [SPX].[LISTEVENT]
(
@FROMDATE DATETIME,
@TODATE DATETIME
)
AS BEGIN
BEGIN TRY
SELECT EVENTDESC,
EVENTNAME,
STARTDATE,
ENDDATE
FROM SPX.SPORTPIXPROMOEVENTS
WHERE STARTDATE=@FROMDATE AND ENDDATE=@TODATE
END TRY
BEGIN CATCH
DECLARE @ERRORS VARCHAR(8000)
SET @ERRORS= CONVERT(VARCHAR,ERROR_NUMBER()) + '*****' +
CONVERT(VARCHAR(4000),ERROR_MESSAGE()) + '*****' +
ISNULL(CONVERT(VARCHAR,ERROR_PROCEDURE()),'GETPROMOTIONLIST') +
'*****' +
CONVERT(VARCHAR,ERROR_LINE()) + '*****' +
CONVERT(VARCHAR,ERROR_SEVERITY()) + '*****' +
CONVERT(VARCHAR,ERROR_STATE())
15 | P a g e
);
END CATCH
END
The @@IDENTITY and SCOPE_IDENTITY return the current session last identity value but the
SCOPE_IDENTITY returns the current scope value.
What is the scope of @@IDENTITY?
In the @@IDENTITY, there are no any limitations for a specific scope.
Syntax: - @@IDENTITY
Return Type: - numeric (38, 0)
For example as,
-- USE OF @@IDENTITY
INSERT INTO ContactType(Code, Description, IsCurrent, CreatedBy, CreatedOn)
VALUES ('IT-PROGRAMING', 'This is a Prrogrammer!', 1, 'Anil Singh', GETDATE());
GO
SELECT @@IDENTITY AS 'COL_IDENTITY';
GO
--USE SCOPE_IDENTITY
IF (@@ERROR <> 0)
BEGIN
INSERT INTO @Return_Table (Code, Message, ID)
SELECT 'ERROR', 'An error occurred in updating the customer.', SCOPE_IDENTITY()
16 | P a g e
SELECT Code, Message, ID FROM @Return_Table
END
ELSE
BEGIN
INSERT INTO @Return_Table (Code, Message, ID)
SELECT 'OK', 'SUCCESS', SCOPE_IDENTITY()
SELECT Code, Message, ID FROM @Return_Table
END
GO
Syntax: - @@ROWCOUNT
Return Types: - INT
--USE OF @@ROWCOUNT
IF (@@ROWCOUNT > 0)
BEGIN
INSERT INTO @Return_Table (Code, Message, ID)
SELECT 'OK', 'SUCCESS', SCOPE_IDENTITY()
SELECT Code, Message, ID FROM @Return_Table
END
ELSE
BEGIN
INSERT INTO @Return_Table (Code, Message, ID)
SELECT 'ERROR', 'Warning - No rows updated.', SCOPE_IDENTITY()
SELECT Code, Message, ID FROM @Return_Table
END
GO
17 | P a g e
Keep in Mind an Interesting point:-
@@ROWCOUNT is returns only integer value. Suppose that, you are working on bulk insert
operations and you are updating millions of records in the database table that
time @@ROWCOUNT is fail to returns the count values because it is an integer return types
and your effected millions of rows in the table.
In that case, we are using ROWCOUNT_BIG() method to achieve this because it is bigint
returns types.
Syntax: - ROWCOUNT_BIG()
Return Types: - BIGINT
12) 3 Best Ways for 2nd 3rd 4th ...nth Highest Salary - [SQL Server]
Method 1 :-
SQL Server 2nd, 3rd, 4th... Highest salary using SUB QUERY!
We can find the 2nd, 3rd, 4th ... nth highest salary using SQL Server the below query, In the below
query use top 1 for the 2nd highest salary, top 2 for the 3rd highest salary, top 3 for the 4th highest
salary,.... nth for the (n+1) highest salary.
Method 2:-
You can use LIMIT to get 2nd, 3rd, 4th ... nth highest salary!
The examples using SUB QUERY,
18 | P a g e
--QUERY FOR THE 2ND HIGHEST SALARY
SELECT MAX(salary) AS [2ndHighestSalary]
FROM Employee WHERE salary not in (SELECT TOP 1 salary FROM Employee
GROUP BY salary ORDER BY salary DESC)
19 | P a g e
SELECT DISTINCT
OBJ.NAME AS OBJECT_NAME,
OBJ.TYPE_DESC
FROM SYS.SQL_MODULES MOD
INNER JOIN SYS.OBJECTS OBJ ON MOD.OBJECT_ID = OBJ.OBJECT_ID
WHERE MOD.DEFINITION LIKE '%'+@SEARCH_TEXT+'%'
ORDER BY TYPE_DESC
#OR
#Query for Search Text in Stored Procedure with system Procedure.
SELECT DISTINCT
OBJ.NAME AS OBJECT_NAME,
OBJ.TYPE_DESC
FROM SYS.SQL_MODULES MOD
INNER JOIN SYS.OBJECTS OBJ ON MOD.OBJECT_ID = OBJ.OBJECT_ID
WHERE MOD.DEFINITION LIKE '%['+@SEARCH_TEXT+']%'
ORDER BY TYPE_DESC
20 | P a g e
14) How to select true false based on column value in SQL Server?
Hello everyone, today's I am going to share the query for select true and false based on column
value using the SQL CASE as given below.
CASE WHEN ColumnName IS NULL THEN 'False' ELSE 'True' END
In the below example, UNIT is a table name and UNITID, UNIT and UPDATEDATE is the
columns name. Here I using the case on UPDATEDATE column.
For the detail you can see the example.
SELECT E.UNITID,
E.UNIT,
CASE
WHEN E.UPDATEDDATE IS NULL THEN 'NOT UPDATED'
ELSE 'UPDATED'
END AS RTURNING
FROM UNIT E
--OR
SELECT MP.MASTERPLANID,
MP.DISPLAYNAME,
CASE
21 | P a g e
WHEN MP.MOBILENO IS NULL THEN 'False'
ELSE 'True'
END AS ADDONS
FROM MASTERPLAN MP WHERE MP.EQUIPMENTID=8
Please see the live output as given in below screen.
15) Find First and Last Day of Current Month in SQL Server
Hello everyone, I am going to share the code sample to get the first and last day of current
month using SQL Server. The code detail as given below.
DECLARE @GETDATE DATETIME
SELECT @GETDATE = GETDATE()
--QUERY FOR GET LAST DAY OF PREVIOUS MONTH
SELECT CONVERT(VARCHAR(25),DATEADD(DD,-(DAY(@GETDATE)),@GETDATE),105) A
S MY_DATE ,'LAST DAY OF PREVIOUS MONTH' AS MY_DATE_TYPE
UNION ALL
--QUERY FOR GET FIRST DAY OF CURRENT MONTH
SELECT CONVERT(VARCHAR(25),DATEADD(DD,-(DAY(@GETDATE)-1),@GETDATE),105)
AS DATE_VALUE,'FIRST DAY OF CURRENT MONTH'
UNION ALL
--QUERY FOR GET TODAY
SELECT CONVERT(VARCHAR(25),@GETDATE,105) AS DATE_VALUE, 'TODAY'
UNION ALL
22 | P a g e
SELECT CONVERT(VARCHAR(25),DATEADD(DD,-
(DAY(DATEADD(MM,1,@GETDATE))),DATEADD(MM,1,@GETDATE)),105),'LAST DAY OF
CURRENT MONTH'
UNION ALL
--QUERY FOR GET FIRST DAY OF NEXT MONTH
SELECT CONVERT(VARCHAR(25),DATEADD(DD,-(DAY(DATEADD(MM,1,@GETDATE))-
1),DATEADD(MM,1,@GETDATE)),105),'FIRST DAY OF NEXT MONTH'
The output : go to below image
6. In SQL server 2012, available new conversion functions are PARSE, TRY_CONVERT,
and TRY_PARSE.
What is difference between SQL 2012 and 2016?
Top 7 Features Coming to SQL Server 2016, lets see in the detail with examples.
1. Query Store
2. Polybase
3. Stretch Database
4. JSON Support
23 | P a g e
5. Row Level Security
6. Always Encrypted
7. In-Memory Enhancements
Query Store
Microsoft is maintain query store upgrading most of all versions but What happen in this
version?
Actually In this version Microsoft trying to maintains a history of query execution plans with
query performance and quickly queries etc.
PolyBase
Microsoft is introduced Polybase, This is data processing technique that is called SQL Server
connector.
24 | P a g e
This SQL connector provide the connectivity to Azure Blob Storage and Hadoop using database
tables query and Its dealing to a lot of large text files.
Stretch Database
In this section, Microsoft is trying to reduce your storage cast by a hybrid feature that is called
Stretch Database.
JSON Support
JSON Support Is very awesome features, Using this features you can direct querying to
Hadoop, SQL Server 2016 and also support to Lingua Franca.
Row Level Security
The SQL Server 2016 provide row-level security. It's very useful for multi tenant environments
and Its provide the limit to access the data based on role etc.
Always Encrypted
25 | P a g e
The SQL Server 2016 has feature to supported both column level encryption and encryption in
transit as well.
The Always Encrypted mechanism provided a easy way to encryption to data and makes much
better security.
In-Memory Enhancements
This feature already introduce in SQL Server 2014 but it has some limitation over data and
issues like no-locking-issues and high-volume-session state issues.
Now in SQL Server 2016, Fixed the issues and trying to improved memory mgmt and Its also
supporting foreign keys, check and unique constraints and parallelism also.
1. The OPENJSON () table value function transforms JSON object to one or many rows. It will
not execute any command. It just returns a table row if JSON text is properly formatted.
26 | P a g e
OPENJSON function will also work with JSON arrays and this function can also open
nested/hierarchical JSON objects. OPENJSON will just return set of rows instead of single row.
2. The JSON_Value () is a scalar function and used to returns a value from JSON on the
specified path.
There are some specific examples for OPENJSON read nested JSON –
Example 1 – OPENJSON AND JSON INPUT
DECLARE @json NVARCHAR(MAX)
SET @json=N'{
"Name":"Anil",
"Surname":"Singh",
"Age":32,
"Skills":["SQL","C#","MVC","Angular 2, 4 and 5"]
}'
SELECT * FROM OPENJSON(@json);
Result –
27 | P a g e
"DOMAIN_ID": "Cable Length",
"UPDATE_BY": null,
"VISIBLE": true,
"SOURCE": "OSB",
"MIN_VALUE": 2,
"UPDATE_DT": null,
"VERSION": 1,
"MAX_VALUE": 10
},
{
"CREATE_DT": 34334343433,
"INCLUDEIND_IND": true,
"CREATE_BY": "admin",
"DOMAIN_ID": "Number",
"UPDATE_BY": null,
"VISIBLE": true,
"SOURCE": "COB",
"MIN_VALUE": 1,
"UPDATE_DT": null,
"VERSION": 1,
"MAX_VALUE": 10
},
{
"CREATE_DT": 3434343,
"INCLUDEIND_IND": true,
"CREATE_BY": "admin",
"DOMAIN_ID": "Number_concurrent_access",
"UPDATE_BY": null,
"VISIBLE": true,
"SOURCE": "OCB",
28 | P a g e
"MIN_VALUE": 1,
"UPDATE_DT": null,
"VERSION": 1,
"MAX_VALUE": 5
}]'
CREATE TABLE TBL_ConvertJSONToTableObject(
CREATE_DT VARCHAR(30),
INCLUDEIND_IND VARCHAR(30),
CREATE_BY VARCHAR(30),
DOMAIN_ID VARCHAR(30) ,
UPDATE_BY VARCHAR(30) ,
VISIBLE VARCHAR(30) ,
SOURCE VARCHAR(30) ,
MIN_VALUE VARCHAR(30) ,
UPDATE_DT VARCHAR(30) ,
VERSION VARCHAR(30) ,
MAX_VALUE VARCHAR(30) ,
)
INSERT INTO TBL_ConvertJSONToTableObject (
CREATE_DT,
INCLUDEIND_IND,
CREATE_BY,
DOMAIN_ID,
UPDATE_BY,
VISIBLE ,
SOURCE ,
MIN_VALUE,
UPDATE_DT,
VERSION ,
MAX_VALUE
29 | P a g e
)
SELECT * FROM OPENJSON (@json)
WITH(
CREATE_DT VARCHAR(30) '$.CREATE_DT',
INCLUDEIND_IND VARCHAR(30) '$.INCLUDEIND_IND',
CREATE_BY VARCHAR(30) '$.CREATE_BY',
DOMAIN_ID VARCHAR(30) '$.DOMAIN_ID',
UPDATE_BY VARCHAR(30) '$.UPDATE_BY',
VISIBLE VARCHAR(30) '$.VISIBLE',
SOURCE VARCHAR(30) '$.SOURCE',
MIN_VALUE VARCHAR(30) '$.MIN_VALUE',
UPDATE_DT VARCHAR(30) '$.UPDATE_DT',
VERSION VARCHAR(30) '$.VERSION',
MAX_VALUE VARCHAR(30) '$.MAX_VALUE'
)
SELECT * FROM TBL_ConvertJSONToTableObject
Result –
30 | P a g e
DECLARE @json NVARCHAR(1000)
SELECT @json = N'{
"Orders": [
{
"OrderID": 10100,
"CustomerID": 202000,
"OrderDetail": [{
"ProductID": 302000,
"UnitPrice": 4350
},
{
"ProductID": 203000,
"UnitPrice": 4450
},
{
"ProductID": 43000,
"UnitPrice": 5560
}]
}]
}'
SELECT JSON_Value (c.value, '$.OrderID') as OrderID,
JSON_Value (c.value, '$.CustomerID') as CustomerID,
JSON_Value (p.value, '$.ProductID') as ProductID,
JSON_Value (p.value, '$.UnitPrice') as UnitPrice
FROM OPENJSON (@json, '$.Orders') as c
CROSS APPLY OPENJSON (c.value, '$.OrderDetail') as p
Result –
31 | P a g e
Now you can download SQL Server 2016 from given below link
http://www.microsoft.com/en-in/server-cloud/products/sql-server-2016/
1. If SQL Server is clustered then you should not rename the server name otherwise you
rename it.
2. If you are using replication in SQL Server then can't change server name.
3. If you are installed the Reporting Service that time you not rename or change the server
name.
First you run below query and find the detail about you SQL like Host Name, Server Name,
Machine Name, Net BOIS name and last one SQL Server is clustered or not.
32 | P a g e
The Steps of fallowing process as given below
STEP 2: EXECUTE BELOW TO ADD NEW SERVER NAME. MAKE SURE LOCAL IS
SPECIFIED
STEP 4: VERIFY THE NEW SERVER NAME WHICH YOU CHANGED USING THE BELOW
QUERY
33 | P a g e
The MongoDB provides high performance, high availability, easy scalability etc. rather than
SQL Server.
MongoDB mentioned to document-based NoSQL databases but SQL Server mentioned to
relational database.
MongoDB is a NoSQL database so there's nothing like a stored procedure. You can create a
set of common functionality in a class library.
The "fire-and-forget" is a default option to check query operations but we can use to
"getLastError" method to check query operations succeeded or not.
In the MongoDB, we can change the structure simply by adding, removing column from the
existing documents.
34 | P a g e
Point 6:
In the Temp table (#tmp), function not allows us to use the Temp table.
In the Table variable (@tmp), function allows us to use the table variable.
35 | P a g e
There are 3 types of SQL statements
1) DDL (Data Definition Language): It is used to define the database structure such as tables.
It includes three statements such as Create, Alter, and Drop.
Some of the DDL Commands are listed below
CREATE: It is used for creating the table.
CREATE TABLE&amp;amp;nbsp;table_name
column_name1 data_type(size),
column_name2 data_type(size),
column_name3 data_type(size),
ALTER: The ALTER table is used for modifying the existing table object in the database.
ALTER TABLE table_name
ADD column_name datatype
OR
3) DCL (Data Control Language): These statements are used to set privileges such as Grant
and Revoke database access permission to the specific user.
24) How do we use DISTINCT statement? What is its use?
DISTINCT statement is used with the SELECT statement. If the records contain duplicate
values then DISTINCT is used to select different values among duplicate records.
36 | P a g e
WHERE Clause: This clause is used to define the condition, extract and display only
those records which fulfill the given condition
Syntax: SELECT column_name(s)
FROM table_name
WHERE condition;
GROUP BY Clause: It is used with SELECT statement to group the result of the
executed query using the value specified in it. It matches the value with the column
name in tables and groups the end result accordingly.
Syntax: SELECT column_name(s)
FROM table_name
GROUP BY column_name;
HAVING clause: This clause is used in association with GROUP BY clause. It is applied
to the each group of result or the entire result as single group and much similar as
WHERE clause, the only difference is you cannot use it without GROUP BY clause
Syntax: SELECT column_name(s)
FROM table_name
GROUP BY column_name
HAVING condition;
ORDER BY clause: This clause is to define the order of the query output either in
ascending (ASC) or in descending (DESC) order. Ascending (ASC) is the default one
but descending (DESC) is set explicitly.
Syntax: SELECT column_name(s)
FROM table_name
WHERE condition
ORDER BY column_name ASC|DESC;
USING clause: USING clause comes in use while working with SQL Joins. It is used to
check equality based on columns when tables are joined. It can be used instead ON
clause in Joins.
Syntax: SELECT column_name(s)
FROM table_name
JOIN table_name
USING (column_name);
37 | P a g e
26) Why do we use SQL constraints? Which constraints we can use
while creating database in SQL?
Constraints are used to set the rules for all records in the table. If any constraints get violated
then it can abort the action that caused it.
Constraints are defined while creating the database itself with CREATE TABLE statement or
even after the table is created once with ALTER TABLE statement.
There are 4 major types of joins made to use while working on multiple tables in SQL databases
INNER JOIN: It is also known as SIMPLE JOIN which returns all rows from BOTH tables
when it has at least one column matched
Syntax: SELECT column_name(s)
FROM table_name1
INNER JOIN table_name2
ON column_name1=column_name2;
Example
In this example, we have a table Employee with the following data
38 | P a g e
The second Table is joining
FROM Employee
ON Employee.Emp_id = Joining.Emp_id
ORDER BY Employee.Emp_id;
There will be 4 records selected. These are the results that you should see
Employee and orders tables where there is a matching customer_id value in both
the Employee and orders tables
LEFT JOIN (LEFT OUTER JOIN): This join returns all rows from a LEFT table and its
matched
rows from a RIGHT table.
Syntax: SELECT column_name(s)
FROM table_name1
LEFT JOIN table_name2
ON column_name1=column_name2;
39 | P a g e
Example
In this example, we have a table Employee with the following data:
FROM Employee
ON Employee.Emp_id = Joining.Emp_id
ORDER BY Employee.Emp_id;
There will be 4 records selected. These are the results that you should see:
RIGHT JOIN (RIGHT OUTER JOIN): This joins returns all rows from the RIGHT table
and its matched rows from a LEFT table.
Syntax: SELECT column_name(s)
FROM table_name1
40 | P a g e
RIGHT JOIN table_name2
ON column_name1=column_name2;
Example
In this example, we have a table Employee with the following data
FROM Employee
ON Employee.Emp_id = Joining.Emp_id
ORDER BY Employee.Emp_id;
There will be 4 records selected. These are the results that you should see
FULL JOIN (FULL OUTER JOIN): This joins returns all when there is a match either in
the RIGHT table or in the LEFT table.
41 | P a g e
Syntax: SELECT column_name(s)
FROM table_name1
FULL OUTER JOIN table_name2
ON column_name1=column_name2;
Example
In this example, we have a table Employee with the following data:
FROM Employee
ON Employee.Emp_id = Joining.Emp_id
ORDER BY Employee.Emp_id;
There will be 8 records selected. These are the results that you should see
42 | P a g e
28) What are transaction and its controls?
A transaction can be defined as the sequence task that is performed on databases in a logical
manner to gain certain results. Operations performed like Creating, updating, deleting records in
the database comes from transactions.
In simple word, we can say that a transaction means a group of SQL queries executed on
database records.
43 | P a g e
SQL Aggregate Functions calculates values from multiple columns in a table and returns a
single value.
Action and Event are two main components of SQL triggers when certain actions are performed
the event occurs in response to that action.
44 | P a g e
Following query syntax is to be executed to update the created view
GRANT Command: This command is used provide database access to user apart from an
administrator.
Syntax: GRANT privilege_name
ON object_name
TO {user_name|PUBLIC|role_name}
[WITH GRANT OPTION];
In above syntax WITH GRANT OPTIONS indicates that the user can grant the access to
another user too.
REVOKE Command: This command is used provide database deny or remove access to
database objects.
Syntax: REVOKE privilege_name
ON object_name
FROM {user_name|PUBLIC|role_name};
36) How many types of Privileges are available in SQL?
There are two types of privileges used in SQL, such as
System Privilege: System privileges deal with an object of a particular type and
specifies the right to perform one or more actions on it which include Admin allows a
user to perform administrative tasks, ALTER ANY INDEX, ALTER ANY CACHE GROUP
CREATE/ALTER/DELETE TABLE, CREATE/ALTER/DELETE VIEW etc.
Object Privilege: This allows to perform actions on an object or object of another
user(s) viz. table, view, indexes etc. Some of the object privileges are EXECUTE,
INSERT, UPDATE, DELETE, SELECT, FLUSH, LOAD, INDEX, REFERENCES etc.
37) What is SQL Injection?
SQL Injection is a type of database attack technique where malicious SQL statements are
inserted into an entry field of database such that once it is executed the database is opened for
an attacker. This technique is usually used for attacking Data-Driven Applications to have an
access to sensitive data and perform administrative tasks on databases.
45 | P a g e
SQL Sandbox is the safe place in SQL Server Environment where untrusted scripts are
executed. There are 3 types of SQL sandbox, such as
Safe Access Sandbox: Here a user can perform SQL operations such as creating
stored procedures, triggers etc. but cannot have access to the memory and cannot
create files.
External Access Sandbox: User can have access to files without having a right to
manipulate the memory allocation.
Unsafe Access Sandbox: This contains untrusted codes where a user can have
access to memory.
39) What is the difference between SQL and PL/SQL?
SQL is a structured query language to create and access databases whereas PL/SQL comes
with procedural concepts of programming languages.
44) How many row comparison operators are used while working with a
subquery?
There are 3-row comparison operators which are used in subqueries such as IN, ANY and ALL.
46 | P a g e
46) What is the difference between DELETE and TRUNCATE?
The basic difference in both is DELETE is DML command and TRUNCATE is DDL
DELETE is used to delete a specific row from the table whereas TRUNCATE is used to
remove all rows from the table
We can use DELETE with WHERE clause but cannot use TRUNCATE with it
47) What is the difference between DROP and TRUNCATE?
TRUNCATE removes all rows from the table which cannot be retrieved back, DROP removes
the entire table from the database and it cannot be retrieved back.
48) How to write a query to show the details of a student from Students
table whose
name starts with K?
SELECT * FROM Student WHERE Student_Name like ‘%K’;
Here ‘like’ operator is used for pattern matching.
47 | P a g e
There are 4 types of relationships
One to One Relationship
Many to One Relationship
Many to Many Relationship
One to Many Relationship
52) What do you mean by Stored Procedures? How do we use it?
A stored procedure is a collection of SQL statements which can be used as a function to access
the database. We can create these stored procedures previously before using it and can
execute these them wherever we require and also apply some conditional logic to it. Stored
procedures are also used to reduce network traffic and improve the performance.
Declare Cursor
Open Cursor
Retrieve row from the Cursor
Process the row
Close Cursor
Deallocate Cursor
56) What is Collation?
Collation is set of rules that check how the data is sorted by comparing it. Such as Character
data is stored using correct character sequence along with case sensitivity, type, and accent.
48 | P a g e
Generally, in Database Testing following thing is need to be tested
Database Connectivity
Constraint Check
Required Application Field and its size
Data Retrieval and Processing With DML operations
Stored Procedures
Functional flow
58) What is Database White Box Testing?
Database White Box Testing involves
Database Consistency and ACID properties
Database triggers and logical views
Decision Coverage, Condition Coverage, and Statement Coverage
Database Tables, Data Model, and Database Schema
Referential integrity rules
59) What is Database Black Box Testing?
Database Black Box Testing involves
Data Mapping
Data stored and retrieved
Use of Black Box techniques such as Equivalence Partitioning and Boundary Value
Analysis (BVA)
60) What are Indexes in SQL?
The index can be defined as the way to retrieve the data more quickly. We can define indexes
using CREATE statements.
49 | P a g e
1. Right Join
2. Outer Join
3. Full Join
4. Cross Join
5. Self Join.
64. What is the syntax to add a record to a table?
Ans. To add a record in a table INSERT syntax is used.
Ex: INSERT into table_name VALUES (value1, value2..);
WHERE <Condition>
50 | P a g e
76. What is Trigger?
Ans. Trigger allows us to execute a batch of SQL code when a table event occurs (Insert,
update or delete command executed against a specific table)
77. How to select random rows from a table?
Ans. Using SAMPLE clause we can select random rows.
Example:
SELECT * FROM table_name SAMPLE(10);
78. Which TCP/IP port does SQL Server run?
Ans. By default SQL Server runs on port 1433.
79. Write a SQL SELECT query that only returns each name only once
from a table?
Ans. To get the each name only once, we need to use the DISTINCT keyword.
SELECT DISTINCT name FROM table_name;
51 | P a g e
3. Isolation
4. Durability.
87. What do you mean by ROWID?
Ans. It’s an 18 character long pseudo column attached with each row of a table.
88. Define UNION, MINUS, UNION ALL, INTERSECT ?
Ans. MINUS – returns all distinct rows selected by the first query but not by the second.
UNION – returns all distinct rows selected by either query
UNION ALL – returns all rows selected by either query, including all duplicates.
52 | P a g e
100. Explain the difference between Rename and Alias?
Ans. Rename is a permanent name given to a table or column whereas Alias is a temporary
name given to a table or column.
101. What is a View?
Ans. A view is a virtual table which contains data from one or more tables. Views restrict data
access of table by selecting only required values and make complex queries easy.
102. What are the advantages of Views?
Ans. Advantages of Views:
1. Views restrict access to the data because the view can display selective columns from
the table.
2. Views can be used to make simple queries to retrieve the results of complicated queries.
For example, views can be used to query information from multiple tables without the
user knowing.
103. List the various privileges that a user can grant to another user?
Ans. SELECT, CONNECT, RESOURCES.
104. What is schema?
Ans. A schema is a collection of database objects of a User.
105. What is Table?
Ans. A table is the basic unit of data storage in the database management system. Table data
is stored in rows and columns.
106. Do View contain Data?
Ans. No, Views are virtual structure.
107. Can a View based on another View?
Ans. Yes, A View is based on another View.
108. What is the difference between Having clause and Where clause?
Ans. 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 behaves like WHERE clause only.
109. What is the difference between Local and 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 DB but its rows
disappear when the connection is closed.
110. What is CTE?
Ans. A CTE or common table expression is an expression which contains temporary result set
which is defined in a SQL statement.
53 | P a g e