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 sqlcmd, Windows login sqlcmd -S localhost -d shop -E Pick the database USE shop;
GO
SELECT name FROM sys.tables; This page is T-SQL. A statement outside an explicit transaction commits when it succeeds. 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)
); 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); 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(); Change a price UPDATE dbo.books
SET price = 19
WHERE title = N'Dune'; Remove the short ones DELETE FROM dbo.books
WHERE pages < 100; 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; 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; 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); 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; 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. |