Microsoft SQL Server

Topics related to Microsoft SQL Server:

Getting started with Microsoft SQL Server

This is a set of examples highlighting basic usage of SQL Server.

OVER Clause

PIVOT / UNPIVOT

Using PIVOT and UNPIVOT operators you transform a table by shifting the rows (column values) of a table to columns and vise-versa. As part of this transformation aggregation functions can be applied on the table values.

Database Snapshots

A database snapshot is a read-only, static view of a SQL Server database which is transactionally consistent with the source database as of the moment of the snapshot's creation.

A database snapshot always resides on the same server instance as its source database. As the source database is updated, the database snapshot is updated.

A snapshot differs from a backup since the process of snapshot creation is instantaneous and the snapshot occupies space only as changes in the source database are applied. A backup on the other hand stores a full copy of the data as on the time of backup creation.

Additionally, a snapshot gives an instant read only copy of the database, while a backup needs to be restored to a server in order to be readable (and once restored can be written to as well)

Database snapshots are only available in the Enterprise and Developer editions.

Retrieve information about the database

As with other relational database systems, SQL Server exposes metadata about your databases.

This is provided through the ISO Standard INFORMATION_SCHEMA schema, or the SQL Server-specific sys catalog views.

The STUFF Function

FOR XML PATH

There are also several other FOR XML modes:

  • FOR XML RAW - Creates one <row> element per row.
  • FOR XML AUTO - Attempts to heuristically autogenerate a hierarchy.
  • FOR XML EXPLICIT - Provides more control over the shape of the XML, but is more cumbersome than FOR XML PATH.

Cursors

Normally you would want to avoid using cursors as they can have negative impacts on performance. However in some special cases you may need to loop through your data record by record and perform some action.

Join

Common Table Expressions

It is necessary to separate a CTE from the previous statement with a semi-colon (;) character.

i.e. ;WITH CommonTableName (...) SELECT ... FROM CommonTableName ...

A CTE's scope is a single batch, and only downstream of its definition. A batch may contain multiple CTEs, and a CTE may reference another CTE defined earlier in the batch, but a CTE may not reference another CTE that is defined later in the batch.

Move and copy data around tables

Dates

as per https://msdn.microsoft.com/en-us/library/ms187819.aspx, DateTimes are only precise to 3ms.

Rounding of datetime Fractional Second Precision datetime values are rounded to increments of .000, .003, or .007 seconds, as shown in the following table.

User-specified valueSystem stored value
01/01/98 23:59:59.9991998-01-02 00:00:00.000
------------
01/01/98 23:59:59.9951998-01-01 23:59:59.997
01/01/98 23:59:59.996
01/01/98 23:59:59.997
01/01/98 23:59:59.998
------------
01/01/98 23:59:59.9921998-01-01 23:59:59.993
01/01/98 23:59:59.993
01/01/98 23:59:59.994
------------
01/01/98 23:59:59.9901998-01-01 23:59:59.990
01/01/98 23:59:59.991
------------

If more precision is required, time, datetime2 or datetimeoffset should be used.

Limit Result Set

If ORDER BY clause is used, limiting applies to the ordered result set.

Retrieve Information about your Instance

With Ties Option

Variables

JSON in Sql Server

The OPENJSON function is only available under compatibility level 130. If your database compatibility level is lower than 130, SQL Server will not be able to find and execute OPENJSON function. Currently all Azure SQL databases are set to 120 by default. You can change the compatibility level of a database using the following command:

ALTER DATABASE <Database-Name-Here> SET COMPATIBILITY_LEVEL = 130

Window functions

Partitioning

Stored Procedures

GROUP BY

Generating a range of dates

COALESCE

Split String function in Sql Server

INSERT INTO

CREATE VIEW

String Functions

Resource Governor

Resource Governor in SQL Server is a feature that allows you to manage resource usage by different applications and users. It kicks in realtime by setting CPU and memory limits. It will help preventing that one heavy process will eat up all system resources while for example smaller tasks are awaiting them.

Only available in Enterprise Editions

ORDER BY

WHILE loop

Using a WHILE loop or other iterative process is not normally the most efficient way to process data in SQL Server.

You should prefer to use a set-based query on the data to achieve the same results, where possible

System database - TempDb

Migration

Primary Keys

MERGE

Performs insert, update, or delete operations on a target table based on the results of a join with a source table. For example, you can synchronize two tables by inserting, updating, or deleting rows in one table based on differences found in the other table.

Full-Text Indexing

FOR JSON

SELECT statement

DBMAIL

Index

Queries with JSON data

Storing JSON in SQL tables

OPENJSON

Ranking Functions

Trigger

Converting data types

NULLs

SQL Server provides other methods to handle nulls, such as IS NULL, IS NOT NULL, ISNULL(), COALESCE() and others.

Transaction isolation levels

Advanced options

IF...ELSE

TRY/CATCH

TRY/CATCH is a language construct specific to MS SQL Server's T-SQL.

It allows error handling within T-SQL, similar to that seen in .NET code.

Data Types

User Defined Table Types

UDTs have following restrictions -

  • can not be used as a column in a table or a field in a structured user-defined types
  • a non-clustered index cannot be created in a UDT unless the index is the result of creating a PRIMARY KEY or UNIQUE constraint on the UDT
  • UDT definition CANNOT be modified after it is created

Table Valued Parameters

In-Memory OLTP (Hekaton)

Temporal Tables

SQL Server 2016 introduces support for system-versioned temporal tables as a database feature that brings built-in support for providing information about data stored in the table at any point in time rather than only the data that is correct at the current moment in time.

A system-versioned temporal table is a new type of user table in SQL Server 2016, designed to keep a full history of data changes and allow easy point in time analysis. This type of temporal table is referred to as a system-versioned temporal table because the period of validity for each row is managed by the system (i.e. database engine). Every temporal table has two explicitly defined columns, each with a datetime2 data type. These columns are referred to as period columns. These period columns are used exclusively by the system to record period of validity for each row whenever a row is modified.

Insert

Sequences

SCOPE_IDENTITY()

Views

Views are stored queries that can be queried like regular tables. Views are not part of the physical model of the database. Any changes that are applied to the data source of a view, such as a table, will be reflected in the view as well.

Use of TEMP Table

Temporary Tables are really very helpful.

The table can be created at runtime and can do all operations which are done in a normal table.

These tables are created in a tempdb database.

Used when ?

  1. We have to do complex join operation.

  2. We do large number of row manipulation in stored procedures.

  3. Can replace the usage of cursor.

Thus increases the performance.

Scheduled Task or Job

Isolation levels and locking

Sorting/ordering rows

Privileges or Permissions

Foreign Keys

SQLCMD

You either need to be in the path where SQLCMD.exe exists or add it to your PATH environment variable.

File Group

cross apply

Basic DDL Operations in MS SQL Server

Computed Columns

UNION

Subqueries

Last Inserted Identity

CLUSTERED COLUMNSTORE

Parsename

Installing SQL Server on Windows

Aggregate Functions

Querying results by page

Schemas

Backup and Restore Database

Transaction handling

Natively compiled modules (Hekaton)

Database permissions

Basic Syntax:

{GRANT| REVOKE | DENY} {PERMISSION_NAME} [ON {SECURABLE}] TO {PRINCIPAL};
  • {GRANT| REVOKE | DENY} - What you're trying to accomplish
    • Grant: "Give this permission to the stated principal"
    • Revoke: "Take this permission away from the stated principal"
    • Deny: "Make sure the stated principal never has this permission (i.e. "DENY SELECT" means that regardless of any other permissions, SELECT will fail for this principal)
  • PERMISSION_NAME - The operation that you're attempting to affect. This will depend on the securable. For instance, it doesn't make sense to GRANT SELECT on a stored procedure.
  • SECURABLE - The name of the thing on which you're trying to affect permissions on. This is optional. Saying GRANT SELECT TO [aUser]; is perfectly acceptable; it means "for any securable for which the SELECT permission makes sense, GRANT that permission".
  • PRINCIPAL - For whom you are trying to affect permissions. At a database level, this can be a role (application or database) or user (mapped to a login or not) for example.

Spatial Data

Dynamic SQL

Pagination

Query Hints

Modify JSON text

Row-level security

Dynamic data masking

Export data in txt file by using SQLCMD

Encryption

Managing Azure SQL Database

Common Language Runtime Integration

Delimiting special characters and reserved words

Generally speaking, it is best not to use T-SQL Reserved Words as table names, column names, programming object names, alias etc. So the method to escape these keywords should only be applied if you are inheriting a database design that cannot be changed.

For reserved words, usage of the square brackets is not mandatory. When using a tool such as SQL Server Management Studio, the reserved words will be highlighted to bring attention to the fact that they are reserved.

CASE Statement

Above example is just to show the syntax for using case statements in SQL Server with day of week example. Although same can output can be achieved by using "SELECT DATENAME(WEEKDAY, GETDATE())" as well.

DBCC

BULK Import

Query Store

Service broker

Analyzing a Query

Microsoft SQL Server Management Studio Shortcut Keys

Permissions and Security

PHANTOM read

Filestream

Drop Keyword

String Aggregate functions in SQL Server

SQL Server Evolution through different versions (2000 - 2016)

SQL Server Management Studio (SSMS)

Logical Functions

Dynamic SQL Pivot

Alias Names in Sql Server

bcp (bulk copy program) Utility