Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
8 views

SQL Server Q - A

This document discusses various SQL concepts including stored procedures, functions, views, joins, errors, identities, row counts, aggregations, and more. Stored procedures allow reusable SQL code to reduce network traffic and improve performance. Functions return single or table values from expressions in SELECT statements. Views store queries to simplify accessing subsets of data. Joins combine rows from two or more tables based on related column values.

Uploaded by

kadiyamramana
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

SQL Server Q - A

This document discusses various SQL concepts including stored procedures, functions, views, joins, errors, identities, row counts, aggregations, and more. Stored procedures allow reusable SQL code to reduce network traffic and improve performance. Functions return single or table values from expressions in SELECT statements. Views store queries to simplify accessing subsets of data. Joins combine rows from two or more tables based on related column values.

Uploaded by

kadiyamramana
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 53

Contents

1) What is store procedure? How do they work? When do you use?.......................................2


2) SQL Server Functions,Types and Examples...............................................................................3
3) What is SQL view? Why use View instead of a Table? Advantages and Drawbacks........4
4) What is Index? How do database indexes work? How do indexes help, Types?...............5
5) SQL Server Cursor [Why Peoples Hate Cursor?]......................................................................7
6) What is a trigger in SQL Server? Why use triggers?................................................................9
7) What is a SQL Join? When would you use SQL Joins?.........................................................10
8) What is @@ERROR in SQL? When we should use @@ERROR?........................................12
9) How to Handle Error or Exception in SQL? When you use @@Error and TRY-CATCH?
..................................................................................................................................................................14
10) What is @@IDENTITY in SQL? When we should use and scope of @@IDENTITY?.....16
11) What is @@RowCount in SQL? What does this statement do @@RowCount?............17
12) 3 Best Ways for 2nd 3rd 4th ...nth Highest Salary - [SQL Server]......................................18
13) Search Text in Stored Procedure in SQL Server....................................................................19
14) How to select true false based on column value in SQL Server?......................................21
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....................................................................................................................22
16) What's new in SQL Server 2016?...............................................................................................23
17) Change Server Name in SQL Server.........................................................................................32
18) MongoDB vs. SQL Server............................................................................................................33
19) SQL temp table vs table variable...............................................................................................34
20) SQL Server copy table from one database to another..........................................................35
21) What is SQL?..................................................................................................................................35
22) What are tables in SQL?...............................................................................................................35
23) What are different types of statements supported by SQL?...............................................35
24) How do we use DISTINCT statement? What is its use?.......................................................36
25) What are different Clauses used in SQL?................................................................................36
26) Why do we use SQL constraints? Which constraints we can use while creating
database in SQL?.................................................................................................................................38
27) What are different JOINS used in SQL?...................................................................................38
28) What are transaction and its controls?....................................................................................43
29) What are properties of the transaction?..................................................................................43

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.

When do you use store procedure?


I used store procedures in 1 of 3 scenarios,
 Security,
 Speed and
 Transactions

Types of SQL Procedures,


1. System Stored Procedures
2. User Defined Stored Procedures
3. Extended Stored Procedures

The SQL Stored Procedure Summary:-


1. Stored Procedure may or not return values.
2. Stored Procedure can have both input and output parameters.
3. Stored Procedures can call functions.
4. We can use exception handling in the Stored Procedure using try catch blocks.
5. We can use transactions within Stored Procedures but not in function.
6. We can use both table variables as well as temporary table in it.
7. We can’t use Stored Procedures in the SELECT, WHERE and HAVING statements.

2) SQL Server Functions,Types and Examples


What is a function in SQL Server?
A SQL function is a set of statements that you can pass input values, perform an action and
return the result and the result can be single value or a table value.
When do you use SQL function?
When I am writing an expression and I want to return some value in the SELECT statement
from this expression that time I can use a function.
Types of SQL functions,
1) System defined functions
· Scalar Functions: - abs, round, upper, lower, trim and convert etc.
· Aggregate Functions: - min, max, avg and count etc.
2) User defined functions

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

Example for Create View:-

-- CREATE ACTIVE CUSTOMERS VIEWS


CREATE VIEW vw_Active_Customers
AS
SELECT Id, Name, CreatedOn, UpdatedBy
FROM [dbo].[Customer]
WHERE IsCurrent = 1

-- SELECT ACTIVE CUSTOMERS VIEWS


SELECT * FROM [dbo].[vw_Active_Customers]

-- DROP VIEW
DROP VIEW [dbo].[vw_Active_Customers]

4) What is Index? How do database indexes work? How do indexes help,


Types?
What is an index in SQL?
An index is created in a table to increase the performance of queries and the data pages are
stored contiguously when the index is created and when the index is new-built.
Index allows us to retrieve very fast data from the database and allow us to searching millions of
records quickly.
How do database indexes work?
There are some strategies that make indexes work,
1. Optimize your code.
2. Restructure your data.
3. Compress your data.

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.

The examples are,


-- CREATE INDEX
CREATE INDEX INDEX_NAME ON TABLE_NAME;
-- CREATE SINGLE COLUMN INDEXE
CREATE INDEX INDEX_NAME ON TABLE_NAME (COLUMN_NAME);
-- CREATE UNIQUE INDEXE
CREATE UNIQUE INDEX INDEX_NAME ON TABLE_NAME (COLUMN_NAME);
-- CREATE COMPOSITE INDEXE

6|Page
CREATE INDEX INDEX_NAME ON TABLE_NAME (COLUMN_NAME_1, COLUMN_NAME_2);
--DROP INDEX
DROP INDEX INDEX_NAME;

5) SQL Server Cursor [Why Peoples Hate Cursor?]


“What is a Cursor in SQL Server”? “What is the exact use of Cursor”? “Why
do people hate SQL Cursor”?
A Cursor is a database object. Cursor is used, when you need to enumerate table records in
row by row basic that means singleton fashion.
Its work likes a RecordSet in the ASP.Net.
We can say that a Cursor is a set of rows with a pointer that identify a current row.
Why is it considered to use cursors in SQL Server?
Why do people hate SQL cursors so much?
Actually, the main reason of avoid cursor is “cursors take up memory and create locks” and
also create performance issues.
What are the Alternatives of cursor?
As per my thought, I am trying to use a “while loop” at the place of CURSOR to resolve this
locking issues.
The “while loops” are easy to use as a cursor but it’s sometime created more difficulty to
understand.
The main advantage of “while loop” is that no objects must be created in memory to facilitate the
looping.

How to Create Cursor in Sql Server?


--How to Create Cursor in Sql Server?
--STEP1: DECLARE A CURSOR
DECLARE @EmpName VARCHAR(50)
DECLARE @EmpDepartment VARCHAR(50)

--STEP2: DEFINE A CURSOR


DECLARE Cursor_Emply CURSOR FOR
SELECT EmpName, EmpDepartment FROM Emply

--STEP3: OPEN A CURSOR


OPEN Cursor_Emply

--STEP4: FETCH A CURSOR


FETCH Cursor_Emply INTO @EmpName, @EmpDepartment
WHILE(@@fetch_status=0)

7|Page
BEGIN
PRINT '* EmpName= '+@EmpName
PRINT ' EmpDepartment= '+@EmpDepartment

--FETCH CURSOR FOR NEXT ROWS


FETCH Cursor_Emply INTO @EmpName, @EmpDepartment
END

--STEP5: CLOSE A CURSOR


CLOSE Cursor_Emply

--STEP6: DEALLOCATE A CURSOR


DEALLOCATE Cursor_Emply

How to Call a Cursor in Store procedure?

--How to Call a Cursor in Store procedure?


--CREATE PROCEDURE
CREATE PROCEDURE SPCursor_Emply
AS BEGIN
DECLARE @EmpName VARCHAR(50)
DECLARE @EmpDepartment VARCHAR(50)

DECLARE Cursor_Emply CURSOR FOR


SELECT EmpName, EmpDepartment FROM Emply

-- OPEN CURSOR
OPEN Cursor_Emply

-- FETCH CURSOR
FETCH Cursor_Emply INTO @EmpName,@EmpDepartment
WHILE(@@fetch_status=0)
BEGIN
PRINT '* EmpName= '+@EmpName
PRINT ' EmpDepartment= '+@EmpDepartment

--FETCH CURSOR FOR NEXT ROWS


FETCH Cursor_Emply INTO @EmpName, @EmpDepartment
END

-- CLOSE CURSOR
CLOSE Cursor_Emply

-- DEALLOCATE CURSOR
DEALLOCATE Cursor_Emply

END

How to use a “while loop” with select statement in SQL Server?

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

-- WHILE LOOP WITH CONTINUE AND BREAK KEYWORDS


DECLARE @Age INT
SET @Age = 30
WHILE (@Age >=18)
BEGIN
PRINT @Age
SET @Age = @Age + 1
CONTINUE;

IF @Age = 45 -- WILL NEVER EXECUTED!


BREAK;
END
GO

6) What is a trigger in SQL Server? Why use triggers?


What is a trigger in SQL? Why use triggers?
A trigger is a special kind of operations that execute automatically when an event occurs in the
database (tables and views) when you trying to INSERT, UPDATE OR DELETE operations in
the tables and views.
All the triggers are directly attached with the tables and views. Each of the tables has their own
trigger.
Noted Points:-
1. We can’t create triggers against the system tables and views.
2. The AFTER triggers can’t be defined on the views.
3. You try to avoid using nested triggers.
4. You try to avoid using recursive triggers.

What types of trigger in SQL Server?


There are two types of Triggers available in the SQL that is
DML Triggers: - i) After Trigger ii) Instead of Trigger

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

How to create triggers?


--How to Create trigger?
--CREATE TRIGGER
CREATE TRIGGER myTrigger3 ON employee
FOR UPDATE, INSERT, DELETE
AS
-- BEFORE INSERT
SELECT 'Before INSERT'
INSERT Employee (ID, Name) VALUES (31, 'Rick')
GO
--BEFORE UPDATE
SELECT 'Before UPDATE'
UPDATE Employee
SET Name = 'Test'
WHERE ID = 1
GO

-- BEFORE DELETE
SELECT 'Before DELETE'
DELETE FROM Employee
WHERE ID = 1

7) What is a SQL Join? When would you use SQL Joins?


What is a SQL Join? When would you use Joins?
Join is used to fetch data rows from more than one tables simultaneously based on your join
conditions.
Types of joins in SQL:-
1. INNER JOIN
2. OUTER JOIN

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 inner join in SQL? when would you use it?


Inner Join returns the matched rows from both the tables. If both the keys are matched then
return rows otherwise not!

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.

What is SELF JOIN and when would you use it?


A SELF JOIN is join which is used to join a table to itself.

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,

SELECT * FROM TableA t1, TableA t2


WHERE t1.Id = t2.Id

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))

--UPDATE CUSTOMER QUERY


UPDATE Customer
SET Name = N'Anil Singh'
WHERE Id = 0786

--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

9) How to Handle Error or Exception in SQL? When you use @@Error


and TRY-CATCH?
Today's, I am going to share the code sample for exception handling in SQL Server; The SQL
Server exception handling is very similar to the Microsoft C# and C++ etc.
Error Handling Mechanism:-
The two types of error handling in SQL Server that is
1. @@ERROR
2. TRY CATCH Block

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.
In the SQL Server, The TRY CATCH are catches all errors and store in the @ERRORS variable
and raise the errors using the RAISERROR().
Following functions are used in CATCH block,
ERROR_NUMBER(): Will return error number.
ERROR_SEVERITY():Will return severity level.
ERROR_STATE():Will return state number.

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

The example as,

-- ============================================================
-- 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())

RAISERROR (@ERRORS, -- MESSAGE TEXT.


16, -- SEVERITY.
1 -- STATE.

15 | P a g e
);
END CATCH
END

10) What is @@IDENTITY in SQL? When we should use and scope of


@@IDENTITY?
What is @@IDENTITY in SQL?
The @@IDENTITY is a system function which returns the last inserted identity value.
All the @@IDENTITY, SCOPE_IDENTITY and IDENT_CURRENT are similar functions
because all are return the last inserted value into the table’s IDENTITY columns.

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

The Use of SCOPE_IDENTITY :-


-- DECLARE RETURN TABLE
DECLARE @Return_Table TABLE (Code varchar(10)
,Message varchar(100), ID varchar(100))

--INSERT CONTACT TYPE


INSERT INTO ContactType(Code, Description, IsCurrent, CreatedBy, CreatedOn)
VALUES ('IT-PROGRAMING', 'This is a Prrogrammer!', 1, 'Anil Singh', GETDATE());

--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

11) What is @@RowCount in SQL? What does this statement do


@@RowCount?
The @@ROWCOUNT is a special variable of SQL. It will return the number of rows changed by
the last statement.
The @@RowCount is equal to (=) the number of rows changed by the last statement.

Syntax: - @@ROWCOUNT
Return Types: - INT

What is the scope of @@RowCount?


The @@RowCount is both the scope and connection safe and it is read only!

For example as,


-- DECLARE RETURN TABLE
DECLARE @Return_Table TABLE (Code varchar(10)
,Message varchar(100), ID varchar(100))

--UPDATE CUSTOMER QUERY


UPDATE Customer
SET Name = N'Anil Singh'
WHERE Id = 0786

--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

For example as,


-- DECLARE RETURN TABLE
DECLARE @Return_Table TABLE (Code varchar(10)
,Message varchar(100), ID varchar(100))

--INSERT CUSTOMER ROWS


INSERT INTO ContactType(Code, Description, IsCurrent, CreatedBy, CreatedOn)
VALUES ('IT-PROGRAMING', 'This is a Prrogrammer!', 1, 'Anil Singh', GETDATE());

--USE OF ROWCOUNT_BIG() METHOD


IF (ROWCOUNT_BIG() > 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

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)

--QUERY FOR THE 3RD HIGHEST SALARY


SELECT MAX(salary) AS [3rdHighestSalary]
FROM Employee WHERE salary not in (SELECT TOP 2 salary FROM Employee
GROUP BY salary ORDER BY salary DESC)

--QUERY FOR THE 4TH HIGHEST SALARY


SELECT MAX(salary) AS [4thHighestSalary]
FROM Employee WHERE salary not in (SELECT TOP 3 salary FROM Employee
GROUP BY salary ORDER BY salary DESC)

--QUERY FOR THE 5TH HIGHEST SALARY


SELECT MAX(salary) AS [5thHighestSalary]
FROM Employee WHERE salary not in (SELECT TOP 4 salary FROM Employee
GROUP BY salary ORDER BY salary DESC)

--QUERY FOR THE NTH HIGHEST SALARY


SELECT MAX(salary) AS [nthHighestSalary]
FROM Employee WHERE salary not in (SELECT TOP (n-1) salary FROM Employee
GROUP BY salary ORDER BY salary DESC)

In MySQL simple and sweeter 2nd, 3rd, 4th... Highest salary.


You can use LIMIT to get highest salary!
Examples using MySQL LIMIT,
--QUERY FOR THE 2ND HIGHEST SALARY USINGH LIMIT
SELECT salary FROM Employee ORDER BY salary DESC LIMIT 1, 1;

--QUERY FOR THE 3rd HIGHEST SALARY USINGH LIMIT


SELECT salary FROM Employee ORDER BY salary DESC LIMIT 2, 1;

--QUERY FOR THE 4th HIGHEST SALARY USINGH LIMIT


SELECT salary FROM Employee ORDER BY salary DESC LIMIT 3, 1;

13) Search Text in Stored Procedure in SQL Server


Hello everyone, I am going to share the query for search a text from my all database stored
procedures with and withoutsystem stored procedures.
#Declare a input text as given below.
DECLARE @SEARCH_TEXT VARCHAR(255)
SET @SEARCH_TEXT=anil.singh@gmail.com'
#Query for Search Text in Stored Procedure without system Procedure

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

--QUERY FOR GET LAST DAY OF CURRENT MONTH

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

16) What's new in SQL Server 2016?


Top 6 Features Coming to SQL Server 2012
1. In SQL Server 2012, uses 48 bit precision for spatial.
2. In SQL server 2012, has unlimited concurrent connections are available.
3. In SQL server 2012, by default supports 15,000 partitions in DB.
4. In SQL server 2012, available new string function CONCAT to strings.
5. In SQL server 2012, available new string function FORMAT to strings.

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.

Insert multiple level JSON data into SQL Server 2016 -


Now Native JSON support in SQL Server 2016 and it provides you some functions to read and
parse your JSON object to table format.

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 –

Example 2 – OPENJSON AND JSON INPUT


DECLARE @json NVARCHAR(MAX)
set @json =N'[
{
"CREATE_DT": 3443434343,
"INCLUDEIND_IND": true,
"CREATE_BY": "admin",

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 –

Example 3 – USING JSON_VALUE() WITH OPENJSON() FUNCTION

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/

17) Change Server Name in SQL Server


Some Noted Point Keep in Mind which are given below

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.

SELECT HOST_NAME() AS 'HOSTNAME',


@@SERVERNAME AS 'SERVERNAME',
SERVERPROPERTY('SERVERNAME') AS 'SERVERNAME',
SERVERPROPERTY('MACHINENAME') AS 'MACHINENAME',
SERVERPROPERTY('COMPUTERNAMEPHYSICALNETBIOS') AS 'NETBIOSN
AME',
SERVERPROPERTY('ISCLUSTERED') AS 'ISCLUSTERED'

32 | P a g e
The Steps of fallowing process as given below

STEP 1: EXECUTE BELOW TO DROP THE CURRENT SERVER NAME

EXEC SP_DROPSERVER 'OLD SERVER NAME'

STEP 2: EXECUTE BELOW TO ADD NEW SERVER NAME. MAKE SURE LOCAL IS
SPECIFIED

EXEC SP_ADDSERVER 'NEW SERVER NAME', 'LOCAL SERVER'

STEP 3: RESTART SQL SERVICES FOR REFRESH ALL THE STUFF

STEP 4: VERIFY THE NEW SERVER NAME WHICH YOU CHANGED USING THE BELOW
QUERY

SELECT @@SERVERNAME AS SERVERNAME


SELECT * FROM SYS.SERVERS WHERE SERVER_ID = 0

The output look like below image.

18) MongoDB vs. SQL Server


The MongoDB store the data in documents with JSON format but SQL store the data in Table
format.

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.

19) SQL temp table vs table variable


There are some differences between “Temporary Tables” (#tempTable) and “Table Variables”
(@tempTable).
Point 1:
A Temp table (#tmp) can do all the DDL operations and it allows creating the indexes, altering
and dropping.
A Table variable (@tmp) is not allowed doing the DDL operations but can create the clustered
index only.
Point 2:
A Temp table (#tmp) is easy to create and back up your data.
A Variable table (@tmp) is easy to create but involves the extra effort for create the normal
tables and then back up your data.
Point 3:
A Temp table (#tmp) result can be used by multiple users.
A Variable table (@tmp) result can be used by the current user only.
Point 4:
A Temp table (#tmp) will be stored in the tempdb and create network traffic. If we have large
amount of data in the temp table and it will create performance issue.
A Table variable (@tmp) will be store in the physical memory for some of the data, and then
later when the size increases it will be moved to the tempdb.
Point 5:
A Temp table (#tmp) can be used for the current session or global, so that multiple user session
can utilize the results in the table.
A Table variable (@tmp) can be used inside program, function or procedures.

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.

20) SQL Server copy table from one database to another.


Query for copy table from one database to another database using SQL Server 2012. The query
detail as given below.
Table of Content
1. Syntax for copy table from one database to another.
2. Query for copy table from one database to another.
Syntax
/* COPY TABLE DATA FROM ONE DATABASE TO ANOTHER DATABASE IN SQL SERVER
2012 */
SELECT * INTO DB1.dbo.[Employee] FROM DB2.dbo.[User]
Query for copy table from one database to another
/* COPY TABLE DATA FROM ONE DATABASE TO ANOTHER DATABASE */
SELECT * INTO OBPC.[dbo].[User]
FROM MASTER.[dbo].[User]
You can use the Wizard method to generate SQLServer scripts

21) What is SQL?


Structured Query Language is a database tool which is used to create and access database to
support software application.

22) What are tables in SQL?


The table is a collection of record and its information at a single view.

23) What are different types of statements supported by SQL?

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;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

ALTER TABLE table_name


DROP COLUMN column_name
2) DML (Data Manipulation Language): These statements are used to manipulate the data in
records. Commonly used DML statements are Insert, Update, and Delete.
The Select statement is used as partial DML statement that is used to select all or relevant
records in the table.

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.

Syntax: SELECT DISTINCT column_name(s)


FROM table_name;
25) What are different Clauses used in SQL?

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 5 major constraints are used in SQL, such as


 NOT NULL: That indicates that the column must have some value and cannot be left
null
 UNIQUE: This constraint is used to ensure that each row and column has unique value
and no value is being repeated in any other row or column
 PRIMARY KEY: This constraint is used in association with NOT NULL and UNIQUE
constraints such as on one or the combination of more than one columns to identify the
particular record with a unique identity.
 FOREIGN KEY: It is used to ensure the referential integrity of data in the table and also
matches the value in one table with another using Primary Key
 CHECK: It is used to ensure whether the value in columns fulfills the specified condition
27) What are different JOINS used in SQL?

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

Enter the following SQL statement

SELECT Employee.Emp_id, Joining.Joining_Date

FROM Employee

INNER JOIN Joining

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:

Second Table is joining

Enter the following SQL statement

SELECT Employee.Emp_id, Joining.Joining_Date

FROM Employee

LEFT OUTER JOIN Joining

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

The second Table is joining

Enter the following SQL statement

SELECT Employee.Emp_id, Joining.Joining_Date

FROM Employee

LEFT OUTER JOIN Joining

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:

Second Table is joining

Enter the following SQL statement:

SELECT Employee.Emp_id, Joining.Joining_Date

FROM Employee

FULL OUTER JOIN Joining

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.

There are 4 transaction controls such as

 COMMIT: It is used to save all changes made through the transaction


 ROLLBACK: It is used to roll back the transaction such as all changes made by the
transaction are reverted back and database remains as before
 SET TRANSACTION: Set the name of transaction
 SAVEPOINT: It is used to set the point from where the transaction is to be rolled back
29) What are properties of the transaction?
Properties of transaction are known as ACID properties, such as
 Atomicity: Ensures the completeness of all transactions performed. Checks whether
every transaction is completed successfully if not then transaction is aborted at the
failure point and the previous transaction is rolled back to its initial state as changes
undone
 Consistency: Ensures that all changes made through successful transaction are
reflected properly on database
 Isolation: Ensures that all transactions are performed independently and changes made
by one transaction are not reflected on other
 Durability: Ensures that the changes made in database with committed transactions
persist as it is even after system failure
30) How many Aggregate Functions are available there in SQL?

43 | P a g e
SQL Aggregate Functions calculates values from multiple columns in a table and returns a
single value.

There are 7 aggregate functions we use in SQL

 AVG(): Returns the average value from specified columns


 COUNT(): Returns number of table rows
 MAX(): Returns largest value among the records
 MIN(): Returns smallest value among the records
 SUM(): Returns the sum of specified column values
 FIRST(): Returns the first value
 LAST(): Returns Last value
31) What are Scalar Functions in SQL?
Scalar Functions are used to return a single value based on the input values. Scalar Functions
are as follows

 UCASE(): Converts the specified field in upper case


 LCASE(): Converts the specified field in lower case
 MID(): Extracts and returns character from text field
 FORMAT(): Specifies the display format
 LEN(): Specifies the length of text field
 ROUND(): Rounds up the decimal field value to a number
32) What are triggers?
Triggers in SQL is kind of stored procedures used to create a response to a specific action
performed on the table such as Insert, Update or Delete. You can invoke triggers explicitly on
the table in the database.

Action and Event are two main components of SQL triggers when certain actions are performed
the event occurs in response to that action.

Syntax: CREATE TRIGGER name {BEFORE|AFTER} (event [OR..]}


ON table_name [FOR [EACH] {ROW|STATEMENT}]
EXECUTE PROCEDURE functionname {arguments}
33) What is View in SQL?
A View can be defined as a virtual table that contains rows and columns with fields from one or
more table.

Syntax: CREATE VIEW view_name AS


SELECT column_name(s)
FROM table_name
WHERE condition
34) How we can update the view?
SQL CREATE and REPLACE can be used for updating the view.

44 | P a g e
Following query syntax is to be executed to update the created view

Syntax: CREATE OR REPLACE VIEW view_name AS


SELECT column_name(s)
FROM table_name
WHERE condition
35) Explain the working of SQL Privileges?
SQL GRANT and REVOKE commands are used to implement privileges in SQL multiple user
environments. The administrator of the database can grant or revoke privileges to or from users
of database object like SELECT, INSERT, UPDATE, DELETE, ALL etc.

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.

For Example: SELECT column_name(s) FROM table_name WHERE condition;


38) What is SQL Sandbox in SQL Server?

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.

40) What is the difference between SQL and MySQL?


SQL is a structured query language that is used for manipulating and accessing the relational
database, on the other hand, MySQL itself is a relational database that uses SQL as the
standard database language.

41) What is the use of NVL function?


NVL function is used to convert the null value to its actual value.

42) What is the Cartesian product of table?


The output of Cross Join is called as a Cartesian product. It returns rows combining each row
from the first table with each row of the second table. For Example, if we join two tables having
15 and 20 columns the Cartesian product of two tables will be 15×20=300 Rows.

43) What do you mean by Subquery?


Query within another query is called as Subquery. A subquery is called inner query which
returns output that is to be used by another query.

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.

45) What is the difference between clustered and non-clustered


indexes?
 One table can have only one clustered index but multiple nonclustered indexes.
 Clustered indexes can be read rapidly rather than non-clustered indexes.
 Clustered indexes store data physically in the table or view and non-clustered indexes
do not store data in table as it has separate structure from data row

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.

49) What is the difference between Nested Subquery and Correlated


Subquery?
Subquery within another subquery is called as Nested Subquery. If the output of a subquery is
depending on column values of the parent query table then the query is called Correlated
Subquery.

SELECT adminid(SELEC Firstname+’ ‘+Lastname FROM Employee WHERE


empid=emp. adminid)AS EmpAdminId FROM Employee
This query gets details of an employee from Employee table.

50) What is Normalization? How many Normalization forms are there?


Normalization is used to organize the data in such manner that data redundancy will never
occur in the database and avoid insert, update and delete anomalies.

There are 5 forms of Normalization


 First Normal Form (1NF): It removes all duplicate columns from the table. Creates table
for related data and identifies unique column values
 First Normal Form (2NF): Follows 1NF and creates and places data subsets in an
individual table and defines relationship between tables using primary key
 Third Normal Form (3NF): Follows 2NF and removes those columns which are not
related through primary key
 Fourth Normal Form (4NF): Follows 3NF and do not define multi-valued dependencies.
4NF also known as BCNF
51) What is Relationship? How many types of Relationship are there?
The relationship can be defined as the connection between more than one tables in the
database.

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.

Syntax: CREATE Procedure Procedure_Name


(
//Parameters
)
AS
BEGIN
SQL statements in stored procedures to update/retrieve records
END
53) State some properties of Relational databases?
 In relational databases, each column should have a unique name
 Sequence of rows and columns in relational databases are insignificant
 All values are atomic and each row is unique
54) What are Nested Triggers?
Triggers may implement data modification logic by using INSERT, UPDATE, and DELETE
statement. These triggers that contain data modification logic and find other triggers for data
modification are called Nested Triggers.

55) What is Cursor?


A cursor is a database object which is used to manipulate data in a row-to-row manner.

Cursor follows steps as given below

 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.

57) What do we need to check in Database Testing?

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.

Syntax: CREATE INDEX index_name


ON table_name (column_name)
Further, we can also create Unique Index using following syntax;

Syntax: CREATE UNIQUE INDEX index_name


ON table_name (column_name)
******************

UPDATE: Added more questions for your practice.

61. What does SQL stand for?


Ans. SQL stands for Structured Query Language.
62. How to select all records from the table?
Ans. To select all the records from the table we need to use the following syntax:
Select * from table_name;

63. Define join and name different types of joins?


Ans. Join keyword is used to fetch data from related two or more tables. It returns rows where
there is at least one match in both the tables included in the join. Read more here.
Type of joins are:

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..);

65. How do you add a column to a table?


Ans. To add another column in the table following command has been used.
ALTER TABLE table_name ADD (column_name);

66. Define SQL Delete statement.


Ans. Delete is used to delete a row or rows from a table based on the specified condition.
The basic syntax is as follows:
DELETE FROM table_name

WHERE <Condition>

67. Define COMMIT?


Ans. COMMIT saves all changes made by DML statements.
68. What is a primary key?
Ans. A Primary key is a column whose values uniquely identify every row in a table. Primary
key values can never be reused.
69. What are foreign keys?
Ans. When a one table’s primary key field is added to related tables in order to create the
common field which relates the two tables, it called a foreign key in other tables.
Foreign Key constraints enforce referential integrity.
70. What is CHECK Constraint?
Ans. A CHECK constraint is used to limit the values or type of data that can be stored in a
column. They are used to enforce domain integrity.
71. Is it possible for a table to have more than one foreign key?
Ans. Yes, a table can have many foreign keys and only one primary key.
72. What are the possible values for the BOOLEAN data field?
Ans. For a BOOLEAN data field, two values are possible: -1(true) and 0(false).
73. What is a stored procedure?
Ans. A stored procedure is a set of SQL queries which can take input and send back output.
74. What is identity in SQL?
Ans. An identity column in the SQL automatically generates numeric values. We can define a
start and increment value of identity column.
75. What is Normalization?
Ans. The process of table design to minimize the data redundancy is called normalization. We
need to divide a database into two or more table and define relationships between them.

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;

80. Explain DML and DDL?


Ans. DML stands for Data Manipulation Language. INSERT, UPDATE and DELETE are DML
statements.
DDL stands for Data Definition Language. CREATE , ALTER, DROP, RENAME are DDL
statements.

81. Can we rename a column in the output of SQL query?


Ans. Yes using the following syntax we can do this.
SELECT column_name AS new_name FROM table_name;

82. Give the order of SQL SELECT?


Ans. Order of SQL SELECT clauses is: SELECT, FROM, WHERE, GROUP BY, HAVING,
ORDER BY. Only the SELECT and FROM clause are mandatory.
83. Suppose a Student column has two columns, Name and Marks. How
to get name and marks of top three students.
Ans. SELECT Name, Marks FROM Student s1 where 3 <= (SELECT COUNT(*) FROM
Students s2 WHERE s1.marks = s2.marks)
84. What is SQL comments?
Ans. SQL comments can be put by two consecutive hyphens (–).
85. Difference between TRUNCATE, DELETE and DROP commands?
Ans. DELETE removes some or all rows from a table based on the condition. It can be rolled
back.
TRUNCATE removes ALL rows from a table by de-allocating the memory pages. The operation
cannot be rolled back

DROP command removes a table from the database completely.

86. What are the properties of a transaction?


Ans. Generally, these properties are referred as ACID properties. They are:
1. Atomicity
2. Consistency

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.

INTERSECT – returns all distinct rows selected by both queries.

89. What is a transaction?


Ans. A transaction is a sequence of code that runs against a database. It takes the database
from one consistent state to another.
90. What is the difference between UNIQUE and PRIMARY KEY
constraints?
Ans. A table can have only one PRIMARY KEY whereas there can be any number of UNIQUE
keys.
The primary key cannot contain Null values whereas Unique key can contain Null values.

91. What is a composite primary key?


Ans. Primary key created on more than one column is called composite primary key.
92. What is an Index?
Ans. An Index is a special structure associated with a table speed up the performance of
queries. The index can be created on one or more columns of a table.
93. What is the Subquery?
Ans. A Subquery is a subset of select statements whose return values are used in filtering
conditions of the main query.
94. What do you mean by query optimization?
Ans. Query optimization is a process in which database system compares different query
strategies and select the query with the least cost.
95. What is Collation?
Ans. Set of rules that define how data is stored, how case sensitivity and Kana character can be
treated etc.
96. What is Referential Integrity?
Ans. Set of rules that restrict the values of one or more columns of the tables based on the
values of the primary key or unique key of the referenced table.
97. What is Case Function?
Ans. Case facilitates if-then-else type of logic in SQL. It evaluates a list of conditions and
returns one of multiple possible result expressions.
98. Define a temp table?
Ans. A temp table is a temporary storage structure to store the data temporarily.
99. How can we avoid duplicating records in a query?
Ans. By using DISTINCT keyword duplicating records in a query can be avoided.

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

You might also like