By: Jeremy Kadlec | Updated: 2024-04-18 | Comments (2) | Related: > TSQL
Problem
I need SQL Server Structured Query Language (T-SQL) examples to help me finish my job quickly. I want to be able to bookmark a resource and then use it on a daily basis when needed as I build apps. Can you please enumerate the most common commands as a SQL Server T-SQL Quick Reference guide?
Solution
The goal of this tip is to create a living document that helps Developers, DBAs, Data Analysts, etc., on a daily basis when working with the SQL Server DBMS on-premises or in the cloud (Azure, Amazon, AWS, or Google). Feel free to bookmark this article and suggest code to include in this tip in the comments section below.
If you are a beginner with the SQL Server relational database management system (RDBMS), consider the following articles as a starting point: Learning SQL Server and What is SQL Server.
Getting Started with SQL Basic Commands
SQL Server Tables and Views
Command | Description | Resources |
---|---|---|
Table | Physical structure consisting of columns and rows to store data. Tables are specified in FROM and JOIN clauses to access them via SELECT, INSERT, UPDATE, and DELETE commands. |
Create Tables in SQL Server with T-SQL
How to create a table using SQL Server Management Studio SQL Create Table using SQL Server Management Studio How To Create a Table in SQL Server Create a Table in Microsoft SQL Server Understanding Column Properties for a SQL Server Table Remodel Poorly Designed SQL Server Database Tables |
View | Virtual table that consists of a SELECT statement. The View can actually be a subset of columns from one table or multiple tables JOINed in the view to simplify data access. |
SQL Server Views Getting Started
CREATE VIEW SQL Server Tutorial Create, Alter, Drop and Query SQL Server Views Insert and Delete SQL Server Data with Views Insulating SQL Server Tables in Views |
CREATE | Generally the first Data Definition Language (DDL) command used by SQL Server professionals to create objects such as tables, views, stored procedures, functions, indexes, etc. For example, the CREATE TABLE command creates a table with a specific schema owner, name, columns, column properties (data types, null, defaults), primary key, and foreign keys. |
Create Tables in SQL Server with T-SQL
CREATE OR ALTER statement in SQL Server |
ALTER | The second of the DDL commands that is used to change an object. For example, with a table, a column can be added, the length of a data type can be increased, the data type can be changed, etc. | Append Columns to SQL Server Table and Add Data to the Table |
DROP | The third of the DDL commands and is used to remove an object from a database. Keep in mind that when an object is dropped without an explicit transaction, it is no longer available. With a table, that means the data is gone. With a stored procedure or function, the logic is gone. To recover an object, you would need to recover from a database backup or retrieve the latest version of code in your source control system. Often, it is safer to rename an object and let it reside in the database for a safe period of time before dropping it. |
DROP TABLE IF EXISTS Examples for SQL Server
Drop Table SQL Server Examples with T-SQL and SQL Server Management Studio Drop All Tables in a SQL Server Database Drop All Tables in SQL Server and Generate a List of Objects to Drop |
Primary Key | The Primary Key is one or more columns that uniquely identifies a row. In general, all tables should have a Primary Key, which should be an Integer data type. Examples of a Primary Key could be OrderID, CustomerID, ProductID, etc. |
SQL Server Primary Key
Surrogate Key vs Natural Key Differences and When to Use in SQL Server Finding primary keys and missing primary keys in SQL Server Data Modeling: Understanding First Normal Form in SQL Server Understanding First Normal Form in SQL Server Explore the Role of Normal Forms in Dimensional Modeling |
Foreign Key | A Primary Key and a Foreign Key comprise a relationship between two tables called Referential Integrity. This ensures data properly relates to corresponding records once your database has been normalized. An example of a foreign key could be a CustomerID in the SalesOrderHeader table to know which customer will be billed for the transaction. |
How to create a SQL Server foreign key
Create SQL Server Tables Using Foreign Keys for Referential Integrity SQL Server Database Design with a One To One Relationship Find Violating SQL Server Foreign Key Values Disable, enable, drop and recreate SQL Server Foreign Keys Drop and Re-Create All Foreign Key Constraints in SQL Server SQL Server Foreign Key Update and Delete Rules |
Data Types | In a table, data types are defined at the column level. Examples include integers (whole numbers), numeric or decimal, variable or fixed character strings, dates and times, money, etc. |
SQL Server Data Types Quick Reference Guide
SQL Server Bit Data Type SQL Server differences of char, nchar, varchar and nvarchar data types Money and Decimal Data Types for Monetary Values with SQL Server Comparison of the VARCHAR(max) and VARCHAR(n) SQL Server Data Types |
NULL | In a table, NULL is defined at the column level. NULL is an unknown value that can be stored as a valid value. NULL values can also be evaluated in SQL queries. | |
Constraints | Constraints can be set up at a table level to ensure a specific rule is enforced to ensure data validity. Constraints include: Primary Key Foreign Key Unique Check Default |
Enforcing business rules using SQL Server CHECK constraints
Working with DEFAULT constraints in SQL Server Should I Use a UNIQUE Constraint or a Unique Index in SQL Server? Finding and fixing SQL Server database constraint issues Enforce a Unique Constraint Where Order Does Not Matter in SQL Server |
Indexes | Indexes are created at a table level to bring order to the table, improve data access performance, and improve the user experience. There are numerous types of indexes for various use cases. |
SQL Server Index Tutorial
Types of SQL Server Indexes SQL Server Indexing Basics SQL Server Index Basics SQL Server Indexes to Improve Query Performance |
Clustered | A clustered index physically orders the data according to the indexed columns. A table can only have one clustered index. The leaf nodes of the index store the data for the rest of the columns in the table, so when a lookup is performed on this type of index, no other structures need to be referenced. |
SQL Server Clustered Indexes
Creating Indexes with SQL Server Management Studio Indexing in SQL with Clustered and Non-Clustered Indexes SQL Server Clustered Tables vs Heap Tables |
Non-Clustered | A non-clustered index (or regular b-tree index) is an index where the order of the rows does not match the physical order of the actual data. Instead, it is ordered by the columns that make up the index. In a non-clustered index, the leaf pages of the index do not contain any actual data but instead contain pointers to the actual data. These pointers would point to the clustered index data page where the actual data exists (or the heap page if no clustered index exists on the table). |
SQL Server non-clustered Indexes
When SQL Server Nonclustered Indexes Are Faster Than Clustered Indexes |
Filtered | A Filtered Index, which is an optimized non-clustered index, allows us to define a filter predicate, a WHERE clause, while creating the index. |
Evaluating SQL Server Filtered Indexes in a Multi Table SQL Join
SQL Server Filtered Indexes What They Are, How to Use and Performance Advantages SQL Server Filtered Index Example |
Columnstore | Columnstore indexes store the index data for each column on a specific page, so any type of scan query (i.e., data warehouse type queries) performs much better than if the column were indexed with a regular b-tree index. |
Columnstore index feature in SQL Server
Faster SQL Server SELECT COUNT(*) Queries with Columnstore Indexes SQL Server 2012 Column Store Index Example SQL Server Column Store Index Performance |
Trigger | A SQL Server Trigger is a block of procedural code executed when a specified event occurs with which the trigger is associated. The most common triggers are DML triggers that log events, such as when a user INSERTS, UPDATES, or DELETES a row in a table, which is issued in a SQL query or stored procedure. SQL triggers can also be used to log (insert into a log table) when a user connects to a database. SQL triggers can also record when a user or event modifies a table and more. |
An Introduction to SQL Triggers
SQL Server Trigger Example SQL Server DDL Trigger to Capture for Create, Alter and Drop Commands SQL Server Trigger After Update for a Specific Value How to View Triggers in SQL Server Management Studio How to Create, Modify or Drop a SQL Server Trigger |
Additional T-SQL Commands for SQL Databases
Command | Description | Resources |
---|---|---|
TOP | Used in SELECT and DELETE commands to access a specified number or percentage of rows. |
Trick to Optimize TOP clause in SQL Server
SQL Server Performance Comparison of TOP vs ROW_NUMBER |
COUNT | Used in SELECT code as an aggregate function that returns the number of rows in a specified table. |
SQL COUNT Function
Count of rows with SQL Server COUNT Getting Starting with SQL COUNT() and COUNT_BIG() Functions |
DISTINCT | Used in a SQL SELECT statement to return a distinct set of values. |
SQL SELECT DISTINCT Examples
SELECT DISTINCT SQL Command to Return a Unique List of Values |
COUNT DISTINCT | Combination of two aggregate functions. Used in SELECT code that returns the number of unique rows in a specified table. | SQL COUNT and SQL COUNT DISTINCT in SQL Server |
SELECT INTO | SELECT command that inserts data into a new table based on the logic specified. Often used for testing or backing up a subset of data. |
SQL SELECT INTO Examples
Creating a table using the SQL SELECT INTO SQL SELECT INTO Examples for New Tables SQL Server Performance of SELECT INTO vs INSERT INTO for temporary tables Performance Improvement for SQL Server SELECT... INTO T-SQL Statement SELECT...INTO Enhancements in SQL Server 2017 |
INSERT SELECT | INSERT command that adds records to an existing table based on logic specified in the SELECT statement. | SQL INSERT INTO SELECT Examples |
UNION and UNION ALL | Combine multiple datasets into one comprehensive dataset with numerous SELECT commands. | UNION vs. UNION ALL in SQL Server |
INTERSECT and EXCEPT | Microsoft introduced the INTERSECT and EXCEPT operators to further extend what you could already do with the UNION and UNION ALL operators. INTERSECT – The final result set where values in both of the tables match EXCEPT – The final result set where data exists in the first dataset and not in the second dataset | Compare SQL Server Datasets with INTERSECT and EXCEPT |
CASE | The CASE expression is used to build IF … THEN … ELSE statements into your T-SQL code. It is used within a SQL statement, such as SELECT or UPDATE. Don't mistake CASE for the IF ELSE control-of-flow construct, which evaluates the conditional execution of SQL statements. |
SQL Server T-SQL CASE Statement Examples
SQL Server CASE Expression Overview SQL CASE Statement in Where Clause to Filter Based on a Condition or Expression Many Uses of SQL CASE Expression in a JOIN Clause Three Use Case Examples for SQL Subqueries SQL BETWEEN Operator for WHERE Clause, CASE, INSERT, DELETE and UPDATE statements Using the CASE expression instead of dynamic SQL in SQL Server |
FROM and JOIN Commands in MS SQL Server
Command | Description | Resources |
---|---|---|
FROM Clause | Used in SELECT, UPDATE, and DELETE commands to specify the tables or views to access the needed data. | |
JOIN | Used in the FROM clause of SELECT, UPDATE, or DELETE commands to match records between one or more tables or views. |
SQL JOIN Types with Examples
Learn about SQL Joins on Multiple Columns Join 3 Tables in SQL SQL Update Statement with Join Join SQL Server tables where columns include NULL values Find Mismatched Data between SQL Server Tables using LEFT JOIN, EXCEPT, NOT IN and NOT EXISTS |
INNER JOIN | Used in SELECT, UPDATE, and DELETE commands to match records between one or more tables or views. |
SQL Server Join Example
Getting Started with SQL INNER JOIN |
LEFT JOIN | A LEFT OUTER JOIN between tables \ views A and B can be described as always taking all records from table A and returning any matching rows from table B in SELECT, UPDATE, and DELETE logic. | SQL LEFT JOIN Examples |
RIGHT JOIN | A RIGHT OUTER JOIN between tables \ views A and B can be described as always taking all records from table B and returning any matching rows from table A in SELECT, UPDATE, and DELETE logic. | SQL RIGHT JOIN Examples |
CROSS APPLY | Microsoft introduced the APPLY operator in SQL Server 2005. It's like a JOIN clause, which allows for the joining of two table expressions. The key difference between the JOIN and APPLY operators is when you have a table-valued expression on the right side and want to evaluate it for each row from the left table expression. |
SQL Server CROSS APPLY
Unpivoting Multiple Sets of Columns in SQL Server using CROSS APPLY Return TOP (N) Rows using APPLY or ROW_NUMBER() in SQL Server |
OUTER APPLY | The APPLY operator is like a JOIN clause, which allows for the joining of two table expressions. The key difference between the JOIN and APPLY operators is when you have a table-valued expression on the right side and want to evaluate it for each row from the left table expression. | SQL Server OUTER APPLY |
T-SQL WHERE Clause Logic
Command | Description | Resources |
---|---|---|
WHERE | Filter records to meet specific criteria in SELECT, UPDATE, or DELETE code with common logic listed below. |
SQL WHERE Tutorial
SQL WHERE Clause Explained How to use the SQL WHERE Clause with Examples |
AND, OR, NOT | Logical Operators used in the WHERE and HAVING clause with the following logic: AND displays records where ALL the conditions specified are true OR displays records where ANY of the conditions specified are true NOT displays records where the condition(s) specified are NOT TRUE |
Learn how to write SQL Queries with AND, OR, and NOT Logical Operators
SQL Logical Operators ALL, AND, ANY, BETWEEN, EXISTS, IN, LIKE, NOT, OR, SOME |
LIKE | The LIKE operator in SQL Server is used to compare a character string against a pattern. This pattern can include regular characters and wildcard characters. The LIKE operator is often used in the WHERE clause of a SQL statement to find rows that match a specified pattern: % - matches any string of zero or more characters _ - matches any single character using an underscore [] - matches any single character within the specified range or set of characters [^] - matches any single character not within the specified range or set of characters |
SQL Server LIKE Syntax with Wildcard Characters
SQL LIKE Statement SQL WHERE LIKE to Construct More Efficient Queries |
IN | The IN operator is used to replace a group of arguments using the = operator that are combined with an OR in for SELECT, UPDATE, or DELETE statement. It can make code easier to read and understand. Generally, it will not change performance characteristics. |
SQL WHERE IN Filtering Examples for SELECT, UPDATE, and DELETE
SQL IN Operator |
NOT IN | The NOT IN operator replaces a group of arguments using the <> (or !=) operator combined with an AND. It can make code easier to read and understand for SELECT, UPDATE, or DELETE SQL commands. Generally, it will not change performance characteristics. | SQL NOT IN Operator |
NOT Equal | The SQL Server NOT Equal operators are used to test that one value, often a column, does not match the value of another. These operators can also be used in T-SQL code as a part of WHILE loops, IF statements, HAVING clauses, join predicates, SQL GROUP BY, or CASE statements. |
SQL Server NOT Equal Operators
Not Equal in SQL WHERE Clause Examples |
EXISTS | The EXISTS operator doesn't check for values but instead checks for the existence of rows. Typically, a subquery is used in conjunction with EXISTS. It doesn't matter what the subquery returns as long as rows are returned. |
SQL Server IN vs EXISTS
SQL Logical Operators ALL, AND, ANY, BETWEEN, EXISTS, IN, LIKE, NOT, OR, SOME SQL EXISTS vs IN vs JOIN Performance Comparison Find Mismatched Data between SQL Server Tables using LEFT JOIN, EXCEPT, NOT IN and NOT EXISTS |
NOT EXISTS | ||
BETWEEN | The SQL BETWEEN operator is used in SELECT, UPDATE, DELETE, and INSERT commands in the WHERE clause, generally when trying to find values between dates or number ranges. NOT BETWEEN can also be used for logic outside of a specific range. |
SQL BETWEEN Operator for WHERE Clause, CASE, INSERT, DELETE and UPDATE statements
Searching between two date values in SQL Server SQL Logical Operators ALL, AND, ANY, BETWEEN, EXISTS, IN, LIKE, NOT, OR, SOME |
NULL | A NULL value is a special marker in the column to denote that a value does not exist. It is important to understand that a NULL column value is different than having a blank (empty string) or 0 value in a column. E.g., ' ' or (empty string) <> NULL, 0 <> NULL. NOT NULL logic in the WHERE clause is used to find any non-NULL values. |
SQL WHERE IS NOT NULL for SELECT, INSERT, UPDATE and DELETE
Learn about SQL NULL values and how SQL Server handles NULL in Queries |
IS NOT NULL | The SQL IS NOT NULL condition is used to test for a non-NULL value. It returns TRUE if a non-NULL value is found and FALSE otherwise. | SQL WHERE IS NOT NULL for SELECT, INSERT, UPDATE and DELETE |
ISNULL | The ISNULL() function is used to check if a value is null, and if it is, it will return the replacement value specified when calling the function. |
Using the SQL ISNULL() Function
Deciding between COALESCE and ISNULL in SQL Server COALESCE(), ISNULL() , NULLIF() and alternatives in SQL Server, Oracle and PostgreSQL |
COALESCE | The SQL function COALESCE() is a basic SQL function used to evaluate a list of values and return the first non-NULL value. The COALESCE function is used as an alternative to the ISNULL() function or the CASE statement. The advantage over the ISNULL() function is that ISNULL() only takes two parameters, and COALESCE() can take many parameters. The advantage over a CASE statement is that it is easier to write and less code. |
Deciding between COALESCE and ISNULL in SQL Server
COALESCE SQL Function |
Order By, Group By, and Having T-SQL Commands
Command | Description | Resources |
---|---|---|
ORDER BY | Sort the result set for a SELECT statement in ascending (ASC) or descending (DESC) order. |
SQL ORDER BY Clause Examples
SQL ORDER BY Clause Learn how to use SQL ORDER BY in Your Queries Advanced Use of the SQL Server ORDER BY Clause Different Methods to Sort SQL Server Result Sets |
GROUP BY | Aggregate data from numerous rows with common data values. |
Learning the SQL GROUP BY Clause
Group By in SQL Server with CUBE, ROLLUP and GROUPING SETS Examples |
HAVING | The HAVING clause corresponds to the GROUP BY clause and can be considered a means to filter the final result set. Often, the HAVING clause has COUNT or SUM logic greater than a threshold. | SQL Aggregate Functions |
Intermediate and Advanced T-SQL Commands
Command | Description | Resources |
---|---|---|
Subquery | Subqueries are queries that are nested inside another query or statement. They are permitted wherever SQL Server allows an expression and are indicated by enclosing the subquery in parenthesis. |
Introduction to Subqueries in SQL Server
SQL Server Subquery Example SQL Server Uncorrelated and Correlated Subquery |
SQL IF, BEGIN, END, ELSE, ELSEIF | The IF statement is very simple to use. It works exactly like the WHERE clause of a SQL statement, except it isn't attached to a query. The keyword IF is followed by an argument or group of arguments combined with AND or OR keywords. An argument is a logical comparison that evaluates to either true or false. Some examples of an argument might be "@NumberValue < 1", "@TextValue ='Hello' ", or "BooleanFunction()" | Build Conditional SQL Server Logic - SQL IF, BEGIN, END, ELSE, ELSEIF |
Dynamic SQL | SQL Server offers a few ways of running a dynamically built SQL statement. Here are a few options: Writing a SELECT statement or SQL Query with SQL variables Using EXEC Using sp_executesql |
Execute Dynamic SQL commands in SQL Server
Dynamic SQL execution on remote SQL Server using EXEC AT Run a Dynamic Query against SQL Server without Dynamic SQL Using the CASE expression instead of dynamic SQL in SQL Server |
Cursor | A SQL Server cursor is a set of T-SQL logic to loop over a predetermined number of rows one at a time. The purpose of the cursor may be to update one row at a time or perform an administrative process, such as SQL Server database backups, in a sequential manner. |
SQL Server Cursor Example
Run same command on all SQL Server databases without cursors Iterate through SQL Server database objects without cursors SQL Server Loop through Table Rows without Cursor Different Ways to Write a Cursor in SQL Server Scroll Cursors in SQL Server Convert a Cursor to Set Based Logic |
WHILE | A WHILE loop is used to iterate over rows in a sequential manner. |
SQL Server Loop through Table Rows without Cursor
Learn the SQL WHILE LOOP with Sample Code SQL WHILE Loop for Processing Time Series Data Avoiding WHILE 1 = 1 loops in SQL Server |
Temporary Tables | Temporary tables store data in a tabular format, i.e., columns and rows. Local temporary tables are only accessible from their creation context, such as the connection. Global temporary tables are accessible from other connections. Both local and global temp tables reside in the Tempdb database. |
SQL Server CTE vs Temp Table vs Table Variable Performance Test
SQL Server Performance Issues using SQL JOIN with a Temporary Table vs a Table Variable Local vs Global SQL Server Temporary Tables SQL Server Global Temporary Table Visibility Create SQL Server temporary tables with the correct collation Parameter Sniffing Issue with Temporary Tables in SQL Server 2022 SQL Server Temp Table vs Table Variable Performance Testing SQL Server Performance of SELECT INTO vs INSERT INTO for temporary tables |
Table Variables | A table variable is a local variable created as a table type via a declaration statement that begins with an @ sign. It includes column names with data types and constraints. Table variables can be declared within batches, functions, and stored procedures used in SELECT, INSERT, UPDATE, and DELETE statements. Unlike permanent and temp tables, table variables cannot be created and populated via the INTO clause in a SELECT statement. |
SQL Server Table Variable Example
SQL Server CTE vs Temp Table vs Table Variable Performance Test Differences between SQL Server temporary tables and table variables Exploring SQL Server 2014 Table Variables |
MERGE | The MERGE operation merges data from a source result set to a target table based on a condition that you specify and whether the data from the source already exists in the target. The new SQL command combines the sequence of conditional INSERT, UPDATE, and DELETE commands in a single atomic statement, depending on the existence of a record. |
Using MERGE in SQL Server to insert, update and delete at the same time
Use Caution with SQL Server's MERGE Statement Resolving the MERGE statement attempted to UPDATE or DELETE the same row more than once error Performance Considerations with SQL MERGE vs INSERT, UPDATE, DELETE Using the SQL Server MERGE Statement to Process Type 2 Slowly Changing Dimensions SQL UPDATE from SELECT, JOIN or MERGE |
CTE | A CTE is a 'temporary named result set' that remains in memory for the scope of a single execution of a SELECT, INSERT, UPDATE, DELETE, or MERGE statement. |
CTE in SQL Server Examples
SQL Server CTE vs Temp Table vs Table Variable Performance Test Recursive Queries using Common Table Expressions (CTE) in SQL Server Fix SQL Server CTE Maximum Recursion Exhausted Error SQL Server Common Table Expressions (CTE) usage and examples |
Random | Learn how to generate random data, dates, etc., or retrieve a random set of records from a table. |
Populate Large Tables with Random Data for SQL Server Performance Testing
Retrieving random data from SQL Server with TABLESAMPLE Generate Random Dates in T-SQL Generate Unique Random Number in SQL Server Different ways to get random data for SQL Server data sampling Simple SQL Server Function to Generate Random 8 Character Password Generating Random Numbers in SQL Server Without Collisions |
Ranking | ROW_NUMBER() returns a sequential integer for every row in our partition. ROW_NUMBER() starts again at 1 when SQL encounters a new partition. The RANK() function behaves like ROW_NUMBER() in that it returns a ranking based on the ORDER BY; however, RANK() distinguishes ties. DENSE_RANK() is almost identical to RANK(), except it doesn't allow gaps. NTILE() divides the results into equal groups based on your input. |
Understanding SQL Ranking Functions ROW_NUMBER(), RANK(), DENSE_RANK() and
NTILE()
How to find Nth Highest Record using DENSE_RANK SQL Server Function SQL Server ROW_NUMBER for Ranking Rows SQL Server Performance Comparison of TOP vs ROW_NUMBER SQL Server Ranking Functions Row_Number and Rank |
Rollup | Rolling up data from multiple rows into a single row may be necessary for concatenating data, reporting, exchanging data between systems, and more. This can be accomplished by using PIVOT, STUFF, and FOR XML. |
Rolling up multiple rows into a single row and column for SQL Server data
SQL Server PIVOT and UNPIVOT Examples Group By in SQL Server with CUBE, ROLLUP and GROUPING SETS Examples Advanced report examples in SQL Server using PIVOT and GROUPING SETS |
Bitwise Operators | T-SQL provides bitwise operators to perform logical operations on SQL Server database table columns, including OR, AND, and XOR. |
SQL Server Bitwise operators to store multiple values in one column
T-SQL Bitwise Operators in SQL Server |
SQL Injection | Many of us use dynamic SQL because we have requirements that dictate runtime choice—allowing the user to select the columns, table name, or even entire where clauses. There are different ways to implement dynamic SQL, and some are more prone to SQL injection than others. SQL injection is a major security threat, likely responsible for nearly any data breach you read about in the news. | Protecting Yourself from SQL Injection in SQL Server |
Next Steps
- We hope this is a useful SQL Quick Reference Guide for learning SQL syntax.
- Interested in another database back-ends and programming languages, then check out these tips:
- If there is a topic you would like included in this SQL Quick Reference Guide or want more information about a particular topic or command, please post your request in the comments section below.
About the author
This author pledges the content of this article is based on professional experience and not AI generated.
View all my tips
Article Last Updated: 2024-04-18