Welcome to Vinayak SQL Tutorial. In this Tutorials explaind completed SQL DBA & development attribute SQL Tutorial for Data Analysis

SQL Injection

 SQL injection is a code injection technique that might destroy your database.

SQL injection is one of the most common web hacking techniques.


explain how to find and exploit various kinds of SQL injection vulnerabilities, and summarize how to prevent SQL injection.


SQL injection (SQLi) is a web security vulnerability that allows an attacker to interfere with the queries that an application makes to its database. It generally allows an attacker to view data that they are not normally able to retrieve. This might include data belonging to other users, orany other data that the application itself is able to access. In many cases, an attacker can modify or delete this data, causing persistent changes to the application's content or behavior.





SQL Server Architecture Explained: Named Pipes, Optimizer, Buffer Manager

SQL Server Architecture Explained: Named Pipes, Optimizer, Buffer Manager 

MS SQL Server is a client-server architecture. MS SQL Server process starts with the client application sending a request. The SQL Server accepts, processes and replies to the request with processed data. Let’s discuss in detail the entire architecture shown below:

As the below Diagram depicts there are three major components in SQL Server Architecture:

   1.  Protocol Layer

   2 .Relational Engine



      Protocol Layer – SNI

·        Shared Memory

·        TCP/IP

·        Named Pipes

·        What is TDS?



Shared Memory
MS SQL SERVER – Here MS SQL server provides SHARED MEMORY PROTOCOL. Here CLIENT and MS SQL server run on the same machine. Both can communicate via Shared Memory protocol

For connection to local - DB in SQL Management Studio, "Server Name" Option could be below

 

TCP/IP
MS SQL SERVER provides the capability to interact via TCP/IP protocol, where CLIENT and MS SQL Server are remote to each other and installed on a separate machine.

Named Pipes
MS SQL Server Provides the capability to interact via the named pipe protocol, here the CLIENT and MS SQL Server are in connection via LAN


What is TDS?
Now that we know that there are three types of Client-Server Architecture, lets us have a glance at TDS:


TDS stands for Tabular Data Stream.

All 3 protocol Relational Engine
The Relational Engine is also known as the Query Processor. It has the SQL Server components that determine what exactly a query needs to do and how it can be done best. It is responsible for the execution of user queries by requesting data from the storage engine and processing the results that are returned.

As depicted in the Architectural Diagram there are 3 major components of the Relational Engine. Let’s study the components in detail:



CMD Parser
Data once received from Protocol Layer is then passed to Relational Engine. “CMD Parser” is the first component of Relational Engine to receive the Query data. The principal job of CMD Parser is to check the query for Syntactic and Semantic error. Finally, it generates a Query Tree. 



Syntactic check:

Like every other Programming language, MS SQL also has the predefined set of Keywords. Also, SQL Server has its own grammar which SQL server understands.
SELECT, INSERT, UPDATE, and many others belong to MS SQL predefined Keyword lists.
CMD Parser does syntactic check. If users’ input does not follow these language syntax or grammar rules, it returns an error.

Semantic check:

This is performed by Normalizer.
In its simplest form, it checks whether Column name, Table name being queried exist in Schema. And if it exists, bind it to Query. This is also known as Binding.
Complexity increases when user queries contain VIEW. Normalizer performs the replacement with the internally stored view definition and much more.

Create Query Tree:

This step generates different execution tree in which query can be run.
Note that, all the different trees have the same desired output.

Optimizer
The work of the optimizer is to create an execution plan for the user’s query. This is the plan that will determine how the user query will be executed.


Similarly, MS SQL Optimizer works on inbuilt exhaustive/heuristic algorithms. The goal is to minimize query run time. All the Optimizer algorithms are propriety of Microsoft and a secret. Although, below are the high-level steps performed by MS SQL Optimizer. Searches of Optimization follows three phases as shown in the below diagram:




Phase 0: Search for Trivial Plan:
This is also known as Pre-optimization stage.
For some cases, there could be only one practical, workable plan, known as a trivial plan. There is no need for creating an optimized plan. The reason is, searching more would result in finding the same run time execution plan. That too with the extra cost of Searching for optimized Plan which was not required at all.If no Trivial plan found, then 1st Phase starts

Phase 1: Search for Transaction processing plans
This includes the search for Simple and Complex Plan.
Simple Plan Search: Past Data of column and Index involved in Query, will be used for Statistical Analysis. This usually consists but not restricted to one Index Per table. Still, if the simple plan is not found, then more complex Plan is searched. It involves Multiple Index per table..

Phase 2: Parallel Processing and Optimization.
If none of the above strategies work, Optimizer searches for Parallel Processing possibilities. This depends on the Machine’s processing capabilities and configuration If that is still not possible, then the final optimization phase starts. Now, the final optimization aim is finding all other possible options for executing the query in the best way. Final optimization phase Algorithms are Microsoft Propriety.


Storage Engine
The work of the storage Engine is to store data in storage system like disk or san and retrieve the data when needed before we deep dive into storage engine , lets have a look at how data is stored database and type of tiles available

Data File and Extent


Data File, physically stores data in the form of data pages, with each data page having a size of 8KB, forming the smallest storage unit in SQL Server. These data pages are logically grouped to form extents. No object is assigned a page in SQL Server.

The maintenance of the object is done via extents. The page has a section called the Page Header with a size of 96 bytes, carrying the metadata information about the page like the Page Type, Page Number, Size of Used Space, Size of Free Space, and Pointer to the next page and previous page, etc.




Primary file
Every database contains one Primary file.
This store all important data related to tables, views, Triggers, etc.
Extension is .mdf usually but can be of any extension.

Secondary file
Database may or may not contains multiple Secondary files.
This is optional and contain user-specific data.
Extension is .ndf usually but can be of any extension.

Log file
Also known as Write ahead logs.
Extension is .ldf
Used for Transaction Management.
This is used to recover from any unwanted instances. Perform important task of Rollback to uncommitted transactions.

Access Method

It acts as an interface between query executor and Buffer Manager/Transaction Logs.

Access Method itself does not do any execution.

The first action is to determine whether the query is:

Select Statement (DDL)

Non- Select Statement (DDL & DML)

Depending upon the result, the Access Method takes the following steps:

If the query is DDL, SELECT statement, the query is pass to the Buffer Manager for further processing.
And if query if DDL, NON-SELECT statement, the query is pass to Transaction Manager. This mostly includes the UPDATE statement


Buffer Manager
Buffer manager manages core functions for modules below:

Plan Cache
Data Parsing: Buffer cache & Data storage
Dirty Page

We will learn Plan, Buffer and Data cache in this section. We will cover Dirty pages in the Transaction


Plan Cache
Existing Query plan: The buffer manager checks if the execution plan is there in the stored Plan Cache. If Yes, then query plan cache and its associated data cache is used.
First time Cache plan: Where does existing Plan cache come from?
If the first-time query execution plan is being run and is complex, it makes sense to store it in in the Plane cache. This will ensure faster availability when the next time SQL server gets the same query. So, it’s nothing else but the query itself which Plan execution is being stored if it is being run for the first time.



 














SQL Performance Improvement


SQL Performance Improvement

  1. SQL query optimization basics
  2. Add missing indexes
  3. Check for unused indexes
  4. Avoid using multiple OR in the FILTER predicate
  5. Avoid too many JOINs.

Missing Indexes

SQL Server, via the Management Studio GUI, execution plan XML, or missing index DMVs, will let us know when there are missing indexes that could potentially help a query perform better:



This warning is useful in that it lets us know that there is a potentially easy fix to improve query performance. It is also misleading in that an additional index may not be the best way to resolve a latency issue. The green text provides us with all of the details of a new index, but we need to do a bit of work before considering taking SQL Server’s advice:
Avoid Running Queries in a Loop

Running queries in a loop can significantly slow your runtime. In some cases, you may be able to bulk insert and update data, which is far more efficient than using loops.

How can you select which queries to optimize?

Before you can optimize any queries, you have to decide which ones are best to optimize. Unfortunately, many people skip this critical step, but by targeting specific, troublesome queries with significant impacts on execution time, you can dramatically increase performance.
If you are less selective when deciding which queries to optimize, you may end up wasting time and money by optimizing those that don’t significantly contribute to performance, don’t impact other queries, or don’t result in problems users will notice.
When starting the MS SQL database query optimization process, look for queries that are consistently or occasionally slow, have red flags, or are major contributors to the total execution time.

Queries That Majorly Contribute to Total Execution Time

If more than five percent of total execution time can be attributed to a single query, try to optimize the query in question. Focusing your efforts on optimizing major contributors rather than those that don’t significantly contribute to performance will enable you to use your time more efficiently.

SQL-Cluster Add Disk from Cluster Configuration

SQL-Cluster Add Disk from Cluster Configuration 

Permissions:->..

To add or remove drives from cluster you must have local admin rights on the server.

 The drive added by windows admin should be visible in My Computer as below.





Also should be visible in Windows Failover Cluster Manger in "Available Storage" Section in

Cluster Summary as Below




                             Right Click on SQL Server Service and select "Add Storage"





                                            It will open the window as below 




 

              One you click OK, it will be visible in SQL server services resources windows



But it is still not used by SQL server services which can be checked by method mentioned in step 2.

In failover cluster manager, click on more actions in Actions pane in right side. It will display ‘Show Dependency Report’, click on it




 


                                     To connect the drive to SQL server services





Navigate to SQL Server service, Right Click on it and select properties&Now go in dependencies tab




 

 

        As per above screen, there is no Drive 7 (i.e DriveK) is available as dependency.

                     So add the new drive as “AND” dependent as shown below




 

Click Apply, Ok

 

And then check Dependency report again, where Drive 7 is no longer floating in the air.


Note: To verify that the Drive is added successfully to SQL Server Instance from SSMS try to access the Drive from SSMS.


For example, take a backup of one of the Databases and look for $K to place the backup, which is not visible in SSMS (But is visible from My Computer) before adding dependency