SQL Server Cheat Sheet
SQL Server is a popular relational database management
system developed by Microsoft. It is widely used for storing, CREATING TABLES QUERYING DATA INSERTING DATA
managing, and processing data in various environments. To create a table: To select data from a table, use the SELECT command. To insert data into a table, use the INSERT command:
CREATE TABLE Habitat ( INSERT INTO Habitat VALUES
Id INT, (1, 'River'),
An example of a single-table query:
Transact-SQL (T-SQL) is an extension of the SQL language, Name VARCHAR(64) (2, 'Forest');
SELECT Species, AVG(Age) AS AverageAge
designed specifically for SQL Server. It allows for advanced );
FROM Animal
database operations such as defining stored procedures,
WHERE Id != 3 You may specify the columns in which the data is added. The
triggers, and indexes. Use IDENTITY to increment the ID automatically with each GROUP BY Species remaining columns are filled with default values or NULLs.
new record. HAVING AVG(Age) > 3 INSERT INTO Habitat (Name) VALUES
CREATE TABLE Habitat ( ORDER BY AVG(Age) DESC; ('Savanna');
SQL Server Management Studio (SSMS) is the official
Id INT PRIMARY KEY IDENTITY,
graphical tool for managing SQL Server databases. It offers a
Name VARCHAR(64)
comprehensive interface for administrators and developers An example of a multiple-table query:
to design databases, write queries, and optimize database
);
SELECT City.Name, Country.Name UPDATING DATA
performance, among other tasks. FROM City To update the data in a table, use the UPDATE command:
To create a table with a foreign key:
[INNER | LEFT | RIGHT | FULL] JOIN Country UPDATE Animal
CREATE TABLE Animal (
ON City.CountryId = Country.Id; SET
Download Microsoft SQL Server here: Id INT PRIMARY KEY IDENTITY,
Species = 'Duck',
https://www.microsoft.com/en-us/sql-server/sql-server- Name VARCHAR(64),
Name = 'Quack'
downloads Species VARCHAR(64),
Age INT,
AGGREGATION AND GROUPING WHERE Id = 2;
HabitatId INT, AVG(expr) − average value of expr for the group.
COUNT(expr) − count of expr values within the group.
CREATING AND DISPLAYING
FOREIGN KEY (HabitatId)
REFERENCES Habitat(Id) MAX(expr) − maximum value of expr values within the DELETING DATA
group. To delete data from a table, use the DELETE command:
DATABASES );
MIN(expr) − minimum value of expr values within the DELETE FROM Animal
To create a database: group. WHERE Id = 1;
CREATE DATABASE Zoo; MODIFYING TABLES SUM(expr) − sum of expr values within the group.
Use the ALTER TABLE or the EXEC statement to modify a This deletes all rows satisfying the WHERE condition.
table structure. To count the rows in the table: To delete all data from a table, use the TRUNCATE TABLE
To list all databases on a server:
SELECT * SELECT COUNT(*) statement:
FROM sys.databases; To change a table name: FROM Animal; TRUNCATE TABLE Animal;
EXEC sp_rename 'AnimalSchema.Animal',
'Pet'
To count the non-NULL values in a column:
To use a specified database: SELECT COUNT(Name) SQL SERVER CONVENTIONS
USE Zoo; To add a column to a table: FROM Animal; In SQL Server, use square brackets to handle table or column
ALTER TABLE Animal names that contain spaces, special characters, or reserved
ADD COLUMN Name VARCHAR(64); keywords. For example:
To delete a specified database: To count unique values in a column:
SELECT
DROP DATABASE Zoo; SELECT COUNT(DISTINCT Name)
To change a column name: [First Name],
FROM Animal;
EXEC sp_rename 'AnimalSchema.Animal.Id', [Age]
To create a schema: 'Identifier', 'COLUMN'; FROM [Customers];
CREATE SCHEMA AnimalSchema; GROUP BY
To change a column data type: To count the animals by species: Often, you refer to a table by its full name that consists of the
ALTER TABLE Animal SELECT Species, COUNT(Id) schema name and the table name (for example,
DISPLAYING TABLES ALTER COLUMN Name VARCHAR(128); FROM Animal
GROUP BY Species;
AnimalSchema.Habitat, sys.databases). For
simplicity, we use plain table names in this cheat sheet.
To list all tables in a database:
To delete a column:
SELECT *
ALTER TABLE Animal To get the average, minimum, and maximum ages by habitat:
FROM sys.tables;
DROP COLUMN Name; SELECT HabitatId, AVG(Age), THE GO SEPARATOR
MIN(Age), MAX(Age) In SQL Server, GO is a batch separator used to execute
To get information about a specified table: To delete a table: FROM Animal multiple SQL statements together. It is typically used in SQL
exec sp_help 'Animal' DROP TABLE Animal; GROUP BY HabitatId; Server Management Studio and similar tools.
LearnSQL.com is owned by Vertabelo SA
Check out our interactive SQL from A to Z in MS SQL Server track and other online courses at LearnSQL.com vertabelo.com | CC BY-NC-ND Vertabelo SA
SQL Server Cheat Sheet
TEXT FUNCTIONS NUMERIC FUNCTIONS DATE AND TIME DATE ARITHMETICS
Character strings are enclosed in single quotes: Use +, -, *, / to do some basic math. There are 6 main time-related types in MySQL: To add or subtract from a DATE, use the DATEADD()
SELECT 'Michael'; To get the number of seconds in a week: DATE – stores the year, month, and day in the YYYY-MM-DD function:
Unicode strings are enclosed in single quotes and prefixed SELECT 60 * 60 * 24 * 7; -- result: 604800 format. DATEADD(day, -3, '2014-04-05');
with capital N: The supported range is '0001-01-01' to '9999-12- -- result: '2014-04-02'
SELECT N'Michél'; In SQL Server, the division operator / performs an integer 31'.
division on integer arguments. For example: TIME – stores the hours, minutes, seconds, and nanoseconds To find the difference between two dates, use the DATEDIFF()
CONCATENATION SELECT 25 / 4; -- result 6 in the HH:MM:SS[.nnnnnnn] format. function:
Use the CONCAT() function to concatenate two strings: The supported range is '00:00:00.0000000' to SELECT DATEDIFF(year, '2019-05-15',
SELECT CONCAT(N'Hi ', N'there!'); To avoid the integer division, make sure at least one of the '23:59:59.9999999'. '2017-05-15');
-- result: Hi there! arguments is not an integer: SMALLDATETIME – stores the date and time in the YYYY- -- result: -2
CONCAT() treats NULL as an empty string: SELECT CAST(25 AS DECIMAL) / 4; MM-DD HH:MM:SS format. SELECT DATEDIFF(month, '2019-06-15',
SELECT CONCAT(N'Learn ', NULL, -- result 6.25 The supported range is '1900-01-01' to '2079-06- '2023-12-15');
N'SQL.com'); SELECT 25.0 / 4; 06'. -- result: 54
-- result: LearnSQL.com -- result 6.25 DATETIME – stores the date and time in the YYYY-MM-DD The supported date parts are: year, quarter, month,
SQL Server allows specifying a separating character HH:MM:SS[.nnn] format. dayofyear, day, week, hour, minute, second,
To get the remainder of a division: The supported range is '1753-01-01' to '9999-12- millisecond, microsecond, nanosecond.
(separator) using the CONCAT_WS() function. The separator
SELECT MOD(13, 2); -- result: 1 31'.
is placed between the concatenated values:
SELECT CONCAT_WS(' ', 1, N'Olivier',
To round a number to three decimal places:
DATETIME2 – stores the date and time in the YYYY-MM-DD
HH:MM:SS[.nnnnnnn] format.
EXTRACTING PARTS OF DATES
N'Norris'); -- result: 1 Olivier Norris
SELECT ROUND(1234.56789, 3); To extract a part of a date, use the functions YEAR(),
The supported range is '0001-01-01
FILTERING THE OUTPUT -- result: 1234.568
00:00:00.0000000' to '9999-12-31
MONTH(), or DAY():
To fetch the city names that are not Berlin: SELECT YEAR(CAST('2021-12-31' AS date));
23:59:59.9999999'.
SELECT Name To round a number up: -- result: 2021
DATETIMEOFFSET – stores the date and time in the YYYY-
FROM City SELECT CEILING(13.1), CEILING(-13.9); SELECT MONTH(CAST('2021-12-31' AS date));
MM-DD HH:MM:SS[.nnnnnnn][+|-]hh:mm format.
WHERE Name != N'Berlin'; -- result: 14, -13 -- result: 12
The supported range is '0001-01-01
SELECT DAY(CAST('2021-12-31' AS date));
TEXT OPERATORS To round a number down: 00:00:00.0000000' to '9999-12-31
-- result: 31
To fetch the city names that start with a 'P' or end with an SELECT FLOOR(13.8), FLOOR(-13.2); 23:59:59.9999999' in UTC.
's':
SELECT Name
-- result: 13, -14 WHAT TIME IS IT? You may also use the DATEPART() function:
SELECT DATEPART(year, '2013-09-15');
To get the current datetime without the time-zone offset:
FROM City
WHERE Name LIKE N'P%' OR Name LIKE N'%s';
USEFUL NULL FUNCTIONS SELECT GETDATE(); -- result: 2023-07-27
-- result: 2013
Supported date parts are: year, quarter, month,
To fetch the names of the cities whose rating values are not 07:21:13.937
To fetch the city names that start with any letter followed by dayofyear, day, week, weekday, hour, minute,
missing: To get the current datetime without the time-zone offset in
'ublin' (like Dublin in Ireland or Lublin in Poland): second, millisecond, microsecond, nanosecond,
SELECT Name DATETIME2 data type (higher fractional seconds precision):
SELECT Name tzoffset, iso_week.
FROM City SELECT SYSDATETIME(); -- result: 2023-07-
FROM City
WHERE Rating IS NOT NULL; 27 07:21:13.9398213
WHERE Name LIKE N'_ublin';
To get the current datetime in UTC: CHANGING THE TIME ZONE
OTHER USEFUL TEXT FUNCTIONS COALESCE(x, y, ...) SELECT GETUTCDATE(); -- result: 2023-07-27 Use AT TIME ZONE to convert a date and time value into a
To get the count of characters in a string: 07:21:13.937 target time zone. You may use meaningful time zone names
To replace NULL in a query with something meaningful:
SELECT LEN(N'LearnSQL.com'); -- result: 12 or in datetime2 data type (higher fractional seconds such as 'Pacific Standard Time'. SQL Server uses
SELECT Domain,
To convert all letters to lowercase: precision): the names stored in the Windows Registry.
COALESCE(Domain, 'domain missing')
SELECT LOWER(N'LEARNSQL.COM'); SELECT SYSUTCDATETIME(); -- result: 2023-
FROM Contacts;
-- result: learnsql.com 07-27 07:21:13.9398213 To add the target time-zone offset to a datetime value
The COALESCE() function takes any number of arguments
To get the current datetime with the time-zone offset: without offset information:
To convert all letters to uppercase: and returns the value of the first argument that is not NULL.
SELECT SYSDATETIMEOFFSET(); SELECT start_time AT TIME ZONE 'UTC';
SELECT UPPER(N'LearnSQL.com');
-- result: 2023-07-27 07:21:13.9398213
-- result: LEARNSQL.COM NULLIF(x, y) +00:00 To convert values between different time zones:
To get just a part of a string: To save yourself from division-by-0 errors: SELECT '2023-07-20 12:30:00'
SELECT SUBSTRING(N'LearnSQL.com', 1, 5); SELECT LastMonth, ThisMonth, CREATING VALUES AT TIME ZONE 'UTC'
-- result: Learn ThisMonth * 100.0 / NULLIF(LastMonth, 0) To create a date, time, or datetime, write the value as a string AT TIME ZONE 'Eastern Standard Time';
To replace a part of a string: AS BetterByPercent and cast it to the proper type. -- result: 2023-07-20 08:30:00
SELECT REPLACE(N'LearnSQL.com', 'SQL', FROM VideoViews; SELECT CAST('2021-12-31' AS date), Specify the known time-zone offset first (here, UTC) and then
'Python'); The NULLIF(x, y) function returns NULL if x equals y, CAST('2021-12-31 23:59:29' AS the
-- result: LearnPython.com else it returns the value of x value. DATETIME2); time zone to which you want to convert.
LearnSQL.com is owned by Vertabelo SA
Check out our interactive SQL from A to Z in MS SQL Server track and other online courses at LearnSQL.com vertabelo.com | CC BY-NC-ND Vertabelo SA