// 무료 참조

SQL Server cheat sheet (T-SQL)

The T-SQL you type against SQL Server and Azure SQL, grouped by task. T-SQL has its own habits for counting rows, joining and typing, so nothing here is pasted from another dialect.

sqlly.app/sql-cheat-sheets/sql-server

SELECT basics

Everything from a table
SELECT * FROM dbo.customers;
First 10 rows, ordered
SELECT TOP (10) * FROM dbo.customers ORDER BY last_name;
Expression with an alias
SELECT first_name + ' ' + last_name AS full_name FROM dbo.customers;
Unique values
SELECT DISTINCT country FROM dbo.customers;
Conditional value
SELECT name, CASE WHEN points >= 100 THEN 'gold' ELSE 'standard' END AS tier FROM dbo.members;

조인

Inner join
SELECT o.id, c.name FROM dbo.orders o JOIN dbo.customers c ON o.customer_id = c.id;
Left join keeps unmatched rows
SELECT c.name, o.id FROM dbo.customers c LEFT JOIN dbo.orders o ON o.customer_id = c.id;
Both sides, matched or not
SELECT e.name, m.name FROM dbo.employees e FULL OUTER JOIN dbo.managers m ON m.employee_id = e.id;
Top N per group with CROSS APPLY
SELECT c.name, t.placed_at FROM dbo.customers c CROSS APPLY (SELECT TOP (3) o.placed_at FROM dbo.orders o WHERE o.customer_id = c.id ORDER BY o.placed_at DESC) t;

필터링

Combined conditions
SELECT * FROM dbo.orders WHERE country = 'DE' AND placed_at >= '2026-01-01';
Any of a list
SELECT * FROM dbo.orders WHERE status IN ('new', 'paid');
Range
SELECT * FROM dbo.orders WHERE total BETWEEN 100 AND 500;
Pattern match
SELECT * FROM dbo.customers WHERE name LIKE 'A%' AND name NOT LIKE '%test%';
Exists elsewhere
SELECT * FROM dbo.customers c WHERE EXISTS (SELECT 1 FROM dbo.orders o WHERE o.customer_id = c.id);

Aggregation

Count per group
SELECT country, COUNT(*) AS customers FROM dbo.customers GROUP BY country;
Groups after filtering with HAVING
SELECT customer_id, SUM(total) AS spent FROM dbo.orders GROUP BY customer_id HAVING SUM(total) > 1000;
Rank within a partition
SELECT name, department, RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS rnk FROM dbo.employees;
Count distinct values
SELECT COUNT(DISTINCT country) FROM dbo.customers;

Insert, update, delete

Single and multi-row insert
INSERT INTO dbo.customers (first_name, last_name) VALUES (N'Ada', N'Lovelace'), (N'Grace', N'Hopper');
Update through a join
UPDATE c SET c.tier = 'gold' FROM dbo.customers c JOIN dbo.totals t ON t.customer_id = c.id WHERE t.spent >= 1000;
Delete in batches
DELETE TOP (100) FROM dbo.audit_events WHERE archived = 1;
Upsert with MERGE
MERGE INTO dbo.targets t USING dbo.sources s ON t.id = s.id WHEN MATCHED THEN UPDATE SET t.name = s.name WHEN NOT MATCHED THEN INSERT (id, name) VALUES (s.id, s.name);
Read back a new key
INSERT INTO dbo.customers (first_name) OUTPUT INSERTED.id VALUES (N'Ada');

Create, alter, drop

Create a table
CREATE TABLE dbo.orders (id BIGINT IDENTITY(1,1) PRIMARY KEY, customer_id BIGINT NOT NULL REFERENCES dbo.customers (id), total DECIMAL(10,2) NOT NULL DEFAULT 0, placed_at DATETIME2 NOT NULL DEFAULT SYSDATETIME());
Add a column
ALTER TABLE dbo.customers ADD tier NVARCHAR(20) NOT NULL DEFAULT N'standard';
Change a column type
ALTER TABLE dbo.customers ALTER COLUMN tier NVARCHAR(40) NOT NULL;
Drop if it exists
DROP TABLE IF EXISTS dbo.temp_results;

인덱스

Index a join key
CREATE INDEX IX_orders_customer_id ON dbo.orders (customer_id);
Composite index
CREATE INDEX IX_orders_placed ON dbo.orders (placed_at DESC, customer_id);
Unique index
CREATE UNIQUE INDEX UX_customers_email ON dbo.customers (email);
Filtered index
CREATE INDEX IX_orders_open ON dbo.orders (customer_id) WHERE status = 'open';

String functions

Length and substring
SELECT LEN(name), SUBSTRING(name, 1, 3) FROM dbo.customers;
Find and replace
SELECT CHARINDEX('@', email), REPLACE(code, '-', '') FROM dbo.users;
Concatenate
SELECT CONCAT(first_name, ' ', last_name) FROM dbo.customers;
Trim and change case
SELECT TRIM(name), UPPER(code), LOWER(email) FROM dbo.customers;

Date functions

지금
SELECT SYSDATETIME(), GETDATE();
Add an interval
SELECT DATEADD(day, 7, placed_at) FROM dbo.orders;
Difference between dates
SELECT DATEDIFF(day, placed_at, SYSDATETIME()) FROM dbo.orders;
Extract a part
SELECT DATEPART(year, placed_at), DATEPART(quarter, placed_at) FROM dbo.orders;
Truncate to a date or the first of the month
SELECT CAST(placed_at AS date), DATEFROMPARTS(YEAR(placed_at), MONTH(placed_at), 1) FROM dbo.orders;
Truncate with DATETRUNC (2022+)
SELECT DATETRUNC(month, placed_at) FROM dbo.orders;

NULL handling

Substitute a default
SELECT ISNULL(nickname, first_name) FROM dbo.customers;
First non-NULL of many
SELECT COALESCE(nickname, first_name, 'unknown') FROM dbo.customers;
Guard a division by zero
SELECT total / NULLIF(quantity, 0) FROM dbo.orders;
Test for NULL
SELECT * FROM dbo.customers WHERE deleted_at IS NULL;

Paging

Page 3, 10 rows per page
SELECT * FROM dbo.orders ORDER BY placed_at DESC OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY;
Keyset paging: seek past the last row seen
SELECT TOP (10) * FROM dbo.orders WHERE placed_at < '2026-01-01' OR (placed_at = '2026-01-01' AND id < 123) ORDER BY placed_at DESC, id DESC;

SQL Server quirks worth knowing

  • Row counts use TOP or OFFSET/FETCH. LIMIT does not exist in T-SQL: write SELECT TOP (10) … 또는 OFFSET … FETCH NEXT … ROWS ONLY (which requires an ORDER BY).
  • Names are bracketed and schema-qualified. [dbo].[Order Details] is a quoted name (]] escapes a closing bracket). Names, bracketed or not, are case-insensitive under the default collation.
  • IDENTITY columns generate keys. IDENTITY(1,1) is the auto-number, and inserting explicit values needs SET IDENTITY_INSERT … ON. Read back a new key with SCOPE_IDENTITY() 또는 OUTPUT 절입니다.
  • Unicode is NVARCHAR, time is DATETIME2. 다음을 사용하세요 N'…' literals, DECIMAL(p,s) for money and SYSDATETIME() (또는 GETDATE()) for now. The floating-point type is FLOAT, there is no DOUBLE, 그리고 DATE holds a date with no time part.
  • GO is a client batch separator. It ends a batch in SSMS and sqlcmd but is not T-SQL, and variables do not survive across it.

Other SQL cheat sheets

To run this sheet against a live database, get the SQLly desktop app for SQL Server또는 모든 기능.

SQL Server cheat sheet FAQ

How do I limit the number of rows in SQL Server?

Use SELECT TOP (10) … for a simple cap, or OFFSET … FETCH NEXT … ROWS ONLY after an ORDER BY when you need paging. LIMIT is not T-SQL and is a syntax error.

How do I get the ID of the row I just inserted?

Read SCOPE_IDENTITY() in the same batch, or add an OUTPUT INSERTED.id clause to the INSERT, which also works for multi-row inserts. Avoid @@IDENTITY: it returns the last identity generated in the session in any scope, so a trigger that inserts into another table changes it.

What is the difference between GETDATE() and SYSDATETIME()?

Precision. GETDATE() returns DATETIME, which rounds to .000, .003 or .007 seconds; SYSDATETIME() returns DATETIME2(7), with 100 ns precision. Newer code should default to SYSDATETIME() and DATETIME2.

How do I copy a table quickly?

SELECT INTO creates the table on the fly: SELECT * INTO dbo.orders_backup FROM dbo.orders;. It copies the data, column types, nullability and the IDENTITY property, but not indexes, primary keys, defaults or other constraints.

// the sheet is the start

Run these against your own database

SQLly is a native SQL workbench for macOS, Windows and Linux. It connects to all five engines on these sheets, and its IntelliSense completes from your real schema.