Jump To
Introduction
- ⇒ Owned by Microsoft
- ⇒ Initial code was developed by Sybase Inc. in 1980’s
- ⇒ A Relational Database Management System (RDMS)
- ⇒ A Client-Server Database
- ⇒ Supports ANSI SQL (the standard SQL Language)
- ⇒ Contains T-SQL (SQL Servers own SQL Implementation)
- ⇒ Interface Tool : SQL Server Management Studio (SSMS)
.
Download Links
An application layer where all operating system resources are managed. Tasks include :
- ⇒ Memory and buffer management
- ⇒ Non preemptive scheduling
- ⇒ Resource governance
- ⇒ Exception handling
- ⇒ Deadlock detection
- ⇒ Extended events and IO etc.
Receives query requests, parses them, determine the best way to execute the query and finally requests the storage engine for data based on the optimized query.
. Storage EngineStores and retrieves data from storage systems such as disks and SAN (Storage area networks).
.- ⇒ Always Encrypted
- ⇒ Row level security
- ⇒ Dynamic Data Masking (DDM)
- ⇒ Transparent data encryption
- ⇒ Fine-grained auditing
- ⇒ Transport Layer Security
.
Tables
Contains a collection of rows, also referred to as records or tuples, and columns, also referred to as attributes.
.
Schemas
One or more object ownership groups contained within a database.
Each schema holds database objects such as tables, views and stored procedures.
.
.
Records all the system-level information for an instance of SQL Server. (logon accounts, endpoints, linked servers, system configuration settings etc)
. msdb dbUsed by SQL Server Agent for scheduling alerts and jobs.
. model dbUsed as the template for all databases created on the instance of SQL Server.
. Resource dbA read-only database that contains system objects that are included with SQL Server.
. tempdb dbA workspace for holding temporary objects or intermediate result sets.
. .Used to define the database schema.
example: Create, Drop, Alter, Rename etc.
. Data Manipulation Language (DML) :Used to manipulate data present in a database.
example: Select, Insert, Update, Delete
. Data Control Language (DCL) :Deals with the rights, permissions and other controls of a database system.
example: Grant, Alter, Revoke
. Transaction Control Language (TCL) :Deals with transactions within a database.
example: Commit, Rollback, Savepoint, Set Transaction
.Basics
TSQL
Style 1
Select * From
Products; — This is a comment
.
Style 2
/*
This is a C style, multiline comment
Everything in the middle gets commented.
*/
.
.
Syntax
WAITFOR
{
DELAY ‘time_to_pass’
| TIME ‘time_to_execute’
| [ ( receive_statement )
| ( get_conversation_group_statement ) ][ , TIMEOUT timeout ]}
.
Delay
WaitFor DELAY ’00:00:02′;
Print ‘This is print after a 2 sec delay.’;
.
Time
WAITFOR TIME ’22:20′;
PRINT ‘You will get the output at 10:20 P.M’;
.
Syntax
IF Boolean_expression
{ sql_statement }
[ ELSE
{ sql_statement } ]
.
Examples
.
WHILE Boolean_expression { sql_statement | BREAK | CONTINUE }
. Examples .LabelName: { code_to_execute } GOTO LabelName;
. Examples .- ⇒ Local temporary table : #TableName
- ⇒ Global temporary table : ##TableName
Using Table Variable
Create/Alter Syntax
.
Delete
DROP PROCEDURE stored_procedure_name;
.
Local Execution
EXECUTE|EXEC sp_recompile spName ‘param1’, ‘param2’
.
Remote Execution
EXEC Server.Database.Schema.spName
.
Examples
.
Transaction
- 1. Identity Insert Check
- 2. Nullability Constraint
- 3. Data-type check
- 4. INSTEAD OF trigger execution
- 5. Primary-key constraint
- 6. Check constraints
- 7. Foreign-key constraint
- 8. DML execution and update to the transaction log
- 9. AFTER trigger execution
- 10. Commit transaction
.
All or nothing. Each transaction is a complete unit of work, the entire transaction either succeeds or fails. No partial transactions.
. ConsistentEach transaction preserves database consistency. The database goes from one consistent state to another consistent state.
. IsolatedEach transaction is separated, or concealed, from the actions of other transactions.
. DurableEach transaction is permanent, regardless of system failure.
.sys Utils
SELECT * FROM sys.sql_modules WHERE object_id = OBJECT_ID(‘the-object-name’);
. Query 2SELECT OBJECT_DEFINITION (OBJECT_ID(‘the-object-name’)) AS ObjectDefinition;
. Query 3EXEC sp_helptext ‘the-object-name’
.SELECT [Name], Product, Provider, Data_Source FROM sys.servers WHERE Is_Linked = 1;
.Retrieves information about any object, in sysobjects or any user-defined data type in the systypes table.
.
List information about each object in a database.
EXEC sp_help;
GO
.
Display information about a single object.
EXEC sp_help ‘Person.Person’;
.
Full Text Search
⇒ Lets users and apps run full-text queries against character-based data in SQL Server tables.
⇒ Queries perform linguistic searches against text data in full-text indexes by operating on words and phrases based on the rules of a particular language such as English or Japanese.
. Set up full-text search . Manage CatalogsObject Explorer → DBName → Storage → Full Text Catalogs
. Set up full-text search .To match words and phrases
. FREETEXT and FREETEXTTABLETo match the meaning, but not the exact wording
. Query Samples .Views
Saved queries that can be used as data sources.
. Types- ⇒ Indexed views
- ⇒ Partitioned views
- ⇒ System views
- ⇒ De-normalize or flatten complex joins
- ⇒ Simplifying aggregate queries
- ⇒ Creating useful assembly blocks
An optional clause that ensures the consistency of the view by enforcing the where clause while inserting and updating through the view.
. .Helps prevent Schema changes which might result in a View breakage.
. .User Defined Functions
A Transact-SQL or common language runtime routine that accept parameters, perform an action, such as a complex calculation, and return the result of that action as a value.
.
Types
- ⇒ Scalar Functions
- ⇒ Table-Valued Functions
- ⇒ System Functions
.
Paging
- ⇒ Offset = 0 for the First fetch.
- ⇒ You can then supply the last RowNum as the offset starting from the next fetch.
- ⇒ You have to handle the next, previous according to the RowNum
- ⇒ You can also make use of the Total count in order to support paging like googles 1,2,3,4,5
Basic Powershell
⇒ Open Powershell in Admin mode
⇒ Type:
> Install-Module SQLSERVER > Install-Module SQLSERVER -AllowClobber
. Usage with SQL Server⇒ Performing Repeatable tasks
⇒ Updating changes to multiple machines
⇒ Configuring cloud services
. [ For more detail]⇒ SQLPS
⇒ Invoke-SQLcmd (run native T-SQL commands)
⇒ Declare SQL connection object
. Example⇒ SQLPS (New-Object cmdlet)
⇒ Native T-SQL (Create Database command)
. Using SQLPS . Using Native T-SQL⇒ SQLPS /SMO (New-Object cmdlet)
⇒ Native T-SQL (Create Database command)
. Using SQLPS . Using Native T-SQLData Manipulation
Built-in scalar string functions that perform an operation on a string and return a string or numeric value.
. ExamplesBuilt-in functions that perform an operation on numeric values.
. ExamplesJoins & Unions
Definition
A Join is a means for combining columns from one (self-join) or more tables by using values common to each. They merge data horizontally.
.
Types
The ANSI-standard SQL specifies five types of JOIN:
- ⇒ Inner Join
- ⇒ Left Outer Join
- ⇒ Right Outer Join
- ⇒ Full Outer Join
- ⇒ Cross Join
.
- ⇒ Also called the Natural Join
- ⇒ An intersection (common information) between two datasets.
.
ANSI-Standard Syntax
SELECT *
From DataSet1 as D1 Inner Join DataSet2 as D2
On D1.columnID = D2.columnID
.
non-ANSI Syntax / Old style
SELECT *
From DataSet1 as D1, DataSet2 as D2
WHERE D1.columnID = D2.columnID
.
It is recommended to use the more readable ANSI-Standard JOIN clauses instead of the old style joins.
.
Example
.
Left Outer Join
All the rows from the table in the left of the join and only matching rows from the right side of the join.
.
Right Outer Join
All the rows from the table in the right of the join and only matching rows from the left side of the join.
.
- ⇒ Left Join and Left Outer Join are equivalent.
- ⇒ Right Join and Right Outer Join are equivalent.
.
Syntax
SELECT *
From DataSet1 as D1 Left | Right [Outer] Join DataSet2 as D2
On D1.columnID = D2.columnID
.
Example
.
All data is returned from both tables regardless of matching data.
.
Syntax
SELECT *
From DataSet1 as D1 Full [Outer] Join DataSet2 as D2
On D1.columnID = D2.columnID
.
Example
.
- ⇒ A Cartesian product (multiplication) between two data sources.
- ⇒ All rows in the 1st table matches up with all rows in the 2nd table
SELECT col1, col2 From DataSet1 Cross Join DataSet2
. Example .- ⇒ Joining from one table back to the same table
- ⇒ Typically used for hierarchical structures
SELECT * From DataSet1 as D1 Inner Join DataSet1 as D2 On D1.columnID = D2.columnID
. Example .- ⇒ Combines the results of two or more queries into a distinct single result
- ⇒ Each SELECT statement within UNION must have the same number of columns, similar data types and must be in the same order
.
Syntax
SELECT col1, col2 FROM DataSet1
Union | Union All | Intersect | Except
SELECT col1, col2 FROM DataSet2;
.
- ⇒ Union: select only distinct data
- ⇒ Union All: allow duplicates
- ⇒ Intersect: Only those that are common to both (Vertical stacking unlike a join`s horizonal merge)
- ⇒ Except: Only those that are either in the first or the second select (uncommon to both)
.
Example
.
Used to join a table with the output of a table valued function.
. Types- ⇒ Cross Apply (Similar to Inner Join)
- ⇒ Outer Apply (Similar to Outer Join)
Sub Queries
Definition
A subquery is a query that is nested inside a SELECT, INSERT, UPDATE, or DELETE statement, or inside another subquery.
.
Flavors
- 1) Simple subquery – Runs once with the result being plugged in to the outer query. Subqueries are executed first followed by the outer query.
- .
- 2) Correlated Subquery – References the outer query. The outer query is executed first followed by the subquery being executed once for each row in the outer query.
.
Fundamentals
- ⇒ Also called Inner Query or Inner Select
- ⇒ Upto 32 levels of nesting is possible
- ⇒ DISTINCT keyword cannot be used with GROUP BY
- ⇒ ORDER BY can only be specified when
TOP
is also specified - ⇒ COMPUTE, For Browse and INTO clauses cannot be specified.
- ⇒ Views created using a subquery cannot be updated.
- ⇒ ntext, text, and image data types cannot be used in the select list
.
Aggregating Data
.
… FROM tableName TABLESAMPLE (num ROWS)
.
.
Distributed Queries
EXEC sp_addlinkedserver @server = ‘serverName’, @srvproduct = ‘SQL Server’
. Query 2EXEC sp_addlinkedserver @server = ‘serverName’, @datasrc=’Source-Name’, @srvproduct =”, @provider = ‘SQLOLEDB’
. ViewSELECT [Name], Product, Provider, Data_Source FROM sys.servers WHERE Is_Linked = 1;
. UsageSELECT *FROM [serverName].master.sys.databases
. DeleteEXEC sp_DropServer @server = ‘serverName’;
.Query 1
EXEC sp_addlinkedsrvlogin
@rmtsrvname = ‘server-name’,
@useself = ‘false’,
@locallogin = ‘local-login’,
@rmtuser = ‘user-name’,
@rmtpassword = ‘password’
.
Query 2
EXEC sp_addlinkedsrvlogin
@rmtsrvname = ‘ServerName’,
@useself = ‘false’
.
Delete
EXEC sp_droplinkedsrvlogin ‘Name’, NULL
.
Examples
Triggers
A special type of stored procedure that automatically runs when an event occurs in the database server.
.
DML Trigger
Runs when a user tries to modify data through a DML event.
events: INSERT, UPDATE, or DELETE
.
DDL Trigger
Runs in response to a variety of DDL events.
events: CREATE, ALTER, DROP etc.
.
Logon Trigger
Fires in response to the LOGON event that’s raised when a user’s session is being established.
.
DROP TRIGGER trigger_name
. Enable/DisableAlter Table table_name Enable|Disable Trigger trigger_name
.Enable/Disable Nested Triggers (Server Wide)
EXEC sp_configure ‘Nested Triggers’, 1 Reconfigure
.Enable/Disable Recursive Triggers (Database Wide)
ALTER DATABASE dbName SET RECURSIVE_TRIGGERS ON
. [ For more detail ]Error Handling
SELECT * FROM sys.messages SELECT * FROM Master.dbo.SysMessages
.Indexing
An on-disk structure associated with a table or view that is used in relational databases to improve query performance, faster data retrieval, table fragmentation etc.
.
- ⇒ Index contains keys built from one or more columns
- ⇒ Keys are stored in a structure (B-tree)
.
Index Types
- ⇒ Hash
- ⇒ Clustered
- ⇒ Nonclustered
- ⇒ memory-optimized Nonclustered
- ⇒ Unique
- ⇒ Columnstore
- ⇒ Index with included columns
- ⇒ Index on computed columns
- ⇒ Filtered
- ⇒ Spatial
- ⇒ XML
- ⇒ Full-text
.
Clustered Index
Sort and store the data rows in the table or view based on their key values.
.
Nonclustered Index
Contains the nonclustered index key values and each key value entry has a pointer to the data row that contains the key value.
.
Guarantees that the index key contains no duplicate values and therefore every row in the table is in some way unique.
. [ For more detail ]An optimized nonclustered index especially suited to cover queries that select from a well-defined subset of data.
. Advantages over full-table indexes- ⇒ Improved query performance and plan quality
- ⇒ Reduced index maintenance costs
- ⇒ Reduced index storage costs
JSON Manipulation
XML Manipulation
Retrieve the results of a SQL query as XML
. Modes- ⇒ RAW : Generates a single row element per row in the rowset.
- ⇒ AUTO : Generates nesting in the resulting XML by using heuristics
- ⇒ EXPLICIT : Allows more control over the shape of the XML
- ⇒ PATH : Provides simpler way for additional nesting of complex properties.