Skip to main content
Quick Reference

SQL Server Cheatsheet

SQL Server on one page — T-SQL tables, IDENTITY, TOP and OFFSET, joins, grouping, indexes, transactions, and the traps around NULL and GO.

10 sections 10 tables 14 code snippets

Connect

sqlcmd, Windows login

sqlcmd -S localhost -d shop -E

Pick the database

USE shop;
GO
SELECT name FROM sys.tables;

The names

NameMeaning
DatabaseUSE shop selects it. A name can be shop.dbo.books
Schemadbo is the default. Two tables can share a name in different schemas
Port 1433The default instance. A named instance looks like localhost\SQLEXPRESS
-EWindows authentication. -U is a SQL login. Do not put the password on the command line
GOA client batch separator. The engine never sees it. A variable does not survive the next GO
SSMSThe same batches. Azure Data Studio runs them too

This page is T-SQL. A statement outside an explicit transaction commits when it succeeds.

Create a table

Identity and Unicode text

CREATE TABLE dbo.books (
  id int IDENTITY(1, 1) PRIMARY KEY,
  title nvarchar(200) NOT NULL,
  pages int NOT NULL,
  price decimal(8, 2) NOT NULL,
  published date NULL,
  CONSTRAINT pages_chk CHECK (pages > 0)
);

Column rules

PieceEffect
IDENTITY(1, 1)Starts at 1 and adds 1. Uniqueness still needs a key
PRIMARY KEYClustered unless you say NONCLUSTERED. The table is stored in that order
nvarchar(200)200 Unicode characters. varchar follows the collation code page, unless that collation is UTF-8
N'Dune'A Unicode literal. A literal without N can lose characters
decimal(8, 2)Exact money. 8 is the total digits, 2 of them after the point
date vs datetime2date is a calendar day. datetime2 keeps a precise time. Old datetime rounds to .000, .003, or .007 seconds

Insert

Several rows, and the new id

INSERT INTO dbo.books (title, pages, price)
OUTPUT inserted.id
VALUES
  (N'Dune', 412, 18.50),
  (N'Neuromancer', 271, 14.00);

What comes back

CallReturns
OUTPUT inserted.idThe identity values this statement created. This is the one to use
SCOPE_IDENTITY()The last identity in this scope. A trigger on another table does not change it
@@IDENTITYThe last identity on the connection, including one a trigger just made
IDENT_CURRENTThe table last identity, from any session
Omitted idThe next identity value
SET IDENTITY_INSERT dbo.books ONLets you supply id. Turn it off in the same session

Select

Top 10 after the sort

SELECT TOP (10) title, pages
FROM dbo.books
WHERE pages >= 300
ORDER BY pages DESC;

A later page

SELECT title, pages
FROM dbo.books
ORDER BY id
OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY;

SELECT SYSDATETIME();

Read rules

FormMeaning
TOP (10)Stops after 10 rows. Without ORDER BY those 10 are not defined
OFFSET ... FETCHThe page clause. ORDER BY is required
No FROMLegal. SELECT SYSDATETIME() needs no DUAL
ISNULL(price, 0)A stand-in. The result type is the type of price
COALESCEThe standard function. It can take more than two arguments
IS NULLThe null test. An empty string is a value, so it is not null

Update & delete

Change a price

UPDATE dbo.books
SET price = 19
WHERE title = N'Dune';

Remove the short ones

DELETE FROM dbo.books
WHERE pages < 100;

Write rules

StatementTouches
UPDATE ... SETThe named columns on rows that pass WHERE. A successful statement commits
DELETE FROMWhole rows that pass WHERE. The table stays
No WHEREEvery row. The client will not ask you to confirm
@@ROWCOUNTRows affected by the last statement
TRUNCATE TABLE dbo.booksEmpties the table and resets IDENTITY. It fails when a foreign key points here
Inside BEGIN TRANSACTIONThe change waits. See the transactions section

Joins

Orders with their book

SELECT o.id, b.title, o.amount
FROM dbo.orders AS o
INNER JOIN dbo.books AS b ON b.id = o.book_id;

SELECT o.id, b.title
FROM dbo.orders AS o
LEFT JOIN dbo.books AS b ON b.id = o.book_id;

Which rows survive

JoinKeeps
INNER JOINOnly rows that match on both sides
LEFT JOINEvery left row. Missing right-side columns are NULL
ONThe match. Put a right-table filter here, or a left join collapses
AS oA short name. Required once both tables have id
WHERE b.id IS NULLLeft rows whose book is missing
WITH (NOLOCK)Reads rows other people have not committed. Those rows can disappear or change

Group & count

Revenue per book

SELECT b.id, b.title,
       COUNT(*) AS sold,
       SUM(o.amount) AS revenue
FROM dbo.orders AS o
INNER JOIN dbo.books AS b ON b.id = o.book_id
GROUP BY b.id, b.title
HAVING SUM(o.amount) > 100
ORDER BY revenue DESC;

Aggregate rules

FormMeaning
COUNT(*)Rows in the group, including rows with NULL
COUNT(published)Rows where published is not NULL
SUM / AVGSkip NULL. AVG of no rows is NULL, not zero
GROUP BYEvery selected column that is not aggregated must be listed
HAVINGFilters groups. WHERE cannot see SUM
ROW_NUMBER() OVER (...)A number per row. It does not collapse the group. Filter it in an outer query

Indexes & foreign keys

Index the column you look up

CREATE INDEX idx_books_title ON dbo.books (title);

ALTER TABLE dbo.orders
  ADD CONSTRAINT fk_orders_book
  FOREIGN KEY (book_id) REFERENCES dbo.books (id);

CREATE INDEX idx_orders_book ON dbo.orders (book_id);

What the engine stores

KeyDetail
ClusteredThe table itself, in key order. One per table. A primary key is clustered unless you say otherwise
NonclusteredA separate structure. It carries the clustering key so it can find the row
(title, pages)Serves title, and title plus pages. Not pages alone
UNIQUERejects a second equal value. Only one NULL is allowed
Foreign keyDoes not create an index on book_id. Add that index yourself
A missing child indexA parent delete scans the child and holds locks longer

Transactions

Two writes, one outcome

SET XACT_ABORT ON;
BEGIN TRANSACTION;
UPDATE dbo.books SET price = price - 1 WHERE id = 1;
INSERT INTO dbo.orders (book_id, amount) VALUES (1, 17.50);
COMMIT;

When the work sticks

FactWhy it matters
AutocommitOn. One statement outside a transaction commits when it succeeds
BEGIN TRANSACTIONHolds the following statements until COMMIT or ROLLBACK
SET XACT_ABORT ONA runtime error rolls the transaction back instead of leaving it open
DDLCREATE, ALTER, and DROP can sit inside the transaction and roll back with it
Identity and rollbackThe consumed identity value is not reused. Gaps are normal, including after a restart
TRUNCATE in a transactionCan roll back. It still resets the identity and takes a stronger lock than DELETE

Interview traps

Traps worth memorising

TrapWhat happensPrefer
LIMIT 10Not T-SQLTOP (10) or OFFSET ... FETCH
TOP (10) with no ORDER BYAny 10 rowsAn ORDER BY that ends in a unique column
Comparing a title to an empty stringMatches empty titles. An empty string is not NULLIS NULL only when you mean NULL
Adding NULL with +The result is NULLCONCAT, which keeps the other part
@@IDENTITY after an insertA trigger may have changed itOUTPUT inserted.id or SCOPE_IDENTITY()
Expecting identity values with no gapsA rollback, a failed insert, or a restart can skip numbersA key that may have gaps
UNIQUE and two NULLsThe second NULL is rejectedA filtered unique index when many NULLs are valid
GO between two statements that share a variableThe variable is gone. GO started a new batchOne batch when the variable must live
varchar and a literal without NCharacters outside the code page can be lost. Use nvarchar and an N prefixnvarchar and an N prefix
datetime for a precise timeValues round to .000, .003, or .007 secondsdatetime2
WITH (NOLOCK)You can read a row that is later rolled backThe default isolation, unless a dirty read is acceptable
A foreign key and no child indexParent deletes scan and lock the childAn index on the referencing column

The page

ORDER BY id
OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY

The new id

OUTPUT inserted.id

How to use this page: connect with sqlcmd, create dbo.books, and insert one Unicode title with OUTPUT inserted.id. Then SELECT TOP (10) with an ORDER BY, and wrap two writes in BEGIN TRANSACTION before you COMMIT.