You are on page 1of 28

Basic SQL Training

Agenda
Select Statement
Sql Where Clause
Insert Into Statement
Update Statement
Sql Join
Analyzing Sql Profiler Output
Missing Index Analysis
Worst Query Analysis
Execution Plan Analysis

Select Query

The SELECT statement is used to select data from a database.

The result is stored in a result table, called the result-set.

SQL SELECT Syntax:

Sql Where Clause

The WHERE clause is used to extract only those records that fulfill a
specified criterion.

SQL WHERE Syntax:

Example:
SELECT * FROM Customers
WHERE Country='Mexico';

The SQL INSERT INTO Statement

The INSERT INTO statement is used to insert new records in a table.

SQL INSERT INTO Syntax:


It is possible to write the INSERT INTO statement in two forms.

The first form does not specify the column names where the data will be inserted,
only their values:

The second form specifies both the column names and the values to be inserted:

Example:
INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode,
Country) VALUES ('Cardinal','Tom B. Erichsen','Skagen 21','Stavanger','4006','Norway');

SQL UPDATE Statement

The UPDATE statement is used to update existing records in a table.

SQL UPDATE Syntax:

Example:
UPDATE Customers SET ContactName='Alfred Schmidt', City='Hamburg'
WHERE CustomerName='Alfreds Futterkiste';

SQL JOIN

An SQL JOIN clause is used to combine rows from two or more tables,
based on a common field between them.

The most common type of join is: SQL INNER JOIN (simple join). An SQL
INNER JOIN return all rows from multiple tables where the join condition
is met.

Different SQL JOINs:


Before we continue with examples, we will list the types the different SQL
JOINs you can use:
1.INNER JOIN: Returns all rows when there is at least one match in BOTH
tables
2.LEFT JOIN: Return all rows from the left table, and the matched rows from
the right table
3.RIGHT JOIN: Return all rows from the right table, and the matched rows
from the left table
4.FULL JOIN: Return all rows when there is a match in ONE of the tables

SQL INNER JOIN

The INNER JOIN keyword selects all rows from both tables as long as there is a match
between the columns in both tables.
INNER JOIN is the same as JOIN.

Syntax:

SQL LEFT JOIN

The LEFT JOIN keyword returns all rows from the left table (table1), with the
matching rows in the right table (table2). The result is NULL in the right side
when there is no match.
SQL LEFT JOIN Syntax:

SQL RIGHT JOIN Keyword

The RIGHT JOIN keyword returns all rows from the right table (table2),
with the matching rows in the left table (table1). The result is NULL in the
left side when there is no match.

SQL FULL OUTER JOIN

The FULL OUTER JOIN keyword returns all rows from the left table (table1)
and from the right table (table2).

The FULL OUTER JOIN keyword combines the result of both LEFT and RIGHT
joins.

SQL FULL OUTER JOIN Syntax:

Analyzing SQL Profiler output

Microsoft SQL Server Profiler is a graphical user interface to SQL Trace for
monitoring T-SQL Statements of Database Engine. We can save and reuse
the state at a later point of time.

We can do the following using SQL Server Profiler:


Create a trace
Watch the trace results as the trace runs
Store the trace results in a table
Start, stop, pause, and modify the trace results as necessary
Replay the trace results

Menu Path:Start | All Programs | Microsoft SQL Server 2008 |


Performance Tools | SQL Server Profiler.

Cont...

Step 1
The following screen will come:
This is basically a login screen of sql server profiler where we have to
enter credentials to login

Step 2:

After Login this window will apper,this is basically trace properties window.
Here we will select various event aacording to our need by simply checking the
checkboxes.
Generally we check only following events:
RPC Completed
Sql Batch Completed
Sql Batch Starting

Step 3
After clicking on column filter new window will apperThis Section is something like
customization. Just click on the "Column Filter Button". In this section, you can
specify some condition (like or Not like).Here genrally we enter database id for
better tracking ,which is taken from sys.databases table .

Step 4:

Now Click on the "Run" Button, then Trace window will come:

Using these windows, you will get the detailed time duration of a query and all other
events information that you have selected.

You can save this result and use it in future. Or you can extract a particular query
from the trace, just right click and click on "Extract Event Data". And save this as a
SQL Script.

Important Points:
Profiler is basically used to analysis performance
issue or production issue.
In case of performance issue we can identify query
by identify query having higher duration & by start
time or end time of individual query.
In case of production issue where there is improper
function,we can identify query by searching query by
particular column name or its value.
After this we have to paste query in query editor &
check its execution plan & analyze query & try to find
out ,is there any scope of improvement.

Missing Index Query Analysis


Performance Tuning is quite interesting and Index plays a
vital role in it. A proper index can improve the performance
and a bad index can hamper the performance.
Please note, if you should not create all the missing indexes
this script suggest. This is just for guidance. You should not
create more than 5-10 indexes per table. Additionally, this
script sometime does not give accurate information so use
your common sense.
You should pay attention to Avg_Estimated_Impact when you
are going to create index. The index creation script is also
provided in the last column.
While selecting index from missindex query output we
consider various factor like Avg percentage benifit,No of
seeks needed,cost that could be reduced etc.

Query to find Missing index in SQL Server:


SELECT mig.index_group_handle,mid.index_handle, migs.avg_total_user_cost
as AvgTotalUserCostThatCouldbeReduced, migs.avg_user_impact as
AvgPercentageBenefit,
migs.user_seeks as NumberOfSeekQueriesNeedIt, migs.user_scans as
NumberOfScanQueriesNeedIt,
'CREATE INDEX missing_index_' + CONVERT (varchar,
mig.index_group_handle) + '_' + CONVERT (varchar, mid.index_handle)
+ ' ON ' + mid.statement
+ ' (' + ISNULL (mid.equality_columns,'')
+ CASE WHEN mid.equality_columns IS NOT NULL AND
mid.inequality_columns IS NOT NULL THEN ',' ELSE '' END
+ ISNULL (mid.inequality_columns, '')
+ ')'
+ ISNULL (' INCLUDE (' + mid.included_columns + ')', '') AS
create_index_statement
FROM sys.dm_db_missing_index_groups mig
INNER JOIN sys.dm_db_missing_index_group_stats migs ON migs.group_handle
= mig.index_group_handle
INNER JOIN sys.dm_db_missing_index_details mid ON mig.index_handle =
mid.index_handle
--order by migs.avg_total_user_cost*user_seeks desc
order by migs.user_seeks desc

Index Syntax
SQL CREATE INDEX Syntax:
CREATE INDEX index_name ON table_name (column_name)

DROP INDEX Syntax :


DROP INDEX index_name ON table_name

DISABLE INDEX Syntax:


ALTER INDEX index_name on table_name DISABLE;

REBUILD INDEX Syntax:


ALTER INDEX index_name on table_name REBUILD;

Worst Query Analysis


Worst query will return TOP 20 worst performing SQL Statement
with the name of object that contain those statements e.g. Stored
Procedure, Trigger and Function. query. The result will be sorted by
CPU time in descending order.
Elapsed time should be less corresponding to execution count for
better performance.Look the query and replace unnecessarily type
casting and extra line of codes which can be handle.
We consider various factor while selecting worst query like total
worker time,logical reads,execution count,execution plan etc.
There is a link in output of worst query.Clicking this will showcase
complete graphical execution plan. which will provide complete
information like total subtree cost,various phyiscal operator,index
recommnedation ,if any.

Query to find Top 20 Worst Query


SELECT TOP 20 SUBSTRING(qt.text, (qs.statement_start_offset/2)+1,
((CASE qs.statement_end_offset
WHEN -1 THEN DATALENGTH(qt.text)
ELSE qs.statement_end_offset
END - qs.statement_start_offset)/2)+1),
qs.execution_count,
qs.total_worker_time, qs.last_worker_time,
qs.min_worker_time, qs.max_worker_time,
qs.total_logical_reads, qs.last_logical_reads,
qs.min_logical_reads, qs.max_logical_reads,
qs.total_elapsed_time, qs.last_elapsed_time,
qs.min_elapsed_time, qs.max_elapsed_time,
qs.last_execution_time,
qp.query_plan
FROM sys.dm_exec_query_stats qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) qt
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) qp
WHERE qt.encrypted=0
ORDER BY qs.total_worker_time DESC

Best Practices:
1.This query will provide top 20 worst queries along with their execution,max
worker time,total worker time an execution plan.
2.While selecting victim query we have to consider various factor like
execution,max worker time,total worker time.
3.After analyzing the query we have to copy the query in query editor,format
it,execute it and check its execution plan.
4.Check weather is there any missing index,any implicit casting and take action
accordingly.
5.If not then we verify is there is any scope of query re-factoring.

Execution plan Analysis:


Problem:

First, you click the 'New Query' button on the top left ofSQL Server
Management Studioto have a new query window to execute a query.
Second, you click the 'Execute' icon on the toolbar or press the F5 key to
process a query.
Third, SQL Server does some processing behind the scenes.
Fourth, results are returned. These are the four steps to retrieving
information from Microsoft SQL Server.
Three of which are pretty straightforward and happen in the light of day.
You see the commands, parameters, object names, keywords and the like
being laid down on the display in front of you when entering T-SQL
commands. You are the one clicking the Execute or F5 key.
You see the results as they are returned. Is there not a way to see how SQL
Server goes about taking the gibberish of T-SQL and converting it to
understandable rows of data? Of course there is. It's the graphical
execution plan!

Solution:

The graphical execution plan is just that. It is a tool that presents in


images and text, the process by which SQL Server steps through the query,
parsing, hashing, and building the results set using the information it has
available (statistics, indexes, and the raw data).

There are actually two other flavors of execution plans that we will not be
discussing at this time: text execution plan and an xml execution plan.

There are two types of graphical execution plans: the estimated execution
plan and the actual execution plan. They are precisely what the names
imply (yes, a rarity in technology).

The estimated execution plan is an estimate based upon the query


optimizer on what it expects to occur when executing the query whereas
the actual execution plan show what did actually occur when generating
the results.

Reading the Graphical Execution Plan:


Plan
Graphical execution plan read from top to buttom & right to left.Some time there is
index recommnedation with impact as showcased below.
And there is warning whose detail can be analyzed by simply drag on warning.
Graphical execution plan not only showcased flow of data through arrows but also
show amount of data flow

Summarize Graphical Execution Plans:


There are a variety of methods for displaying or triggering
graphical execution plans
You read them right-to-left and top-to-bottom.
The arrows denote not just the direction of data travel, but also
(comparatively) amount of data rows being transferred from
step-to-step in the execution process
Costs are displayed for each step, relative to the total cost of the
query plan.
The cost for the statement can be compared to other statements
run in the same batch