This document provides a cheat sheet on SQL Server, covering topics like creating and querying databases and tables, inserting, updating, and deleting data. Key points include:
- SQL Server is a relational database developed by Microsoft that allows storing, managing, and processing data. T-SQL extends SQL for advanced database operations.
- SSMS is the graphical tool for managing SQL Server databases, allowing administrators and developers to design databases and write queries.
- Basic SQL commands are demonstrated for creating tables, inserting data, updating data through queries, and deleting data.
- Aggregation functions like COUNT, AVG, MIN, MAX and SUM are shown to group and analyze data in queries.
This document provides a cheat sheet on SQL Server, covering topics like creating and querying databases and tables, inserting, updating, and deleting data. Key points include:
- SQL Server is a relational database developed by Microsoft that allows storing, managing, and processing data. T-SQL extends SQL for advanced database operations.
- SSMS is the graphical tool for managing SQL Server databases, allowing administrators and developers to design databases and write queries.
- Basic SQL commands are demonstrated for creating tables, inserting data, updating data through queries, and deleting data.
- Aggregation functions like COUNT, AVG, MIN, MAX and SUM are shown to group and analyze data in queries.
SQL Server is a popular relational database management system
developed by Microsoft. It is widely used for storing, managing, CREATING TABLES QUERYING DATA INSERTING DATA 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, An example of a single-table query: (1, 'River'), 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, triggers, WHERE Id != 3 You may specify the columns in which the data is added. The and indexes. Use IDENTITY to increment the ID automatically with each new GROUP BY Species remaining columns are filled with default values or NULLs. record. HAVING AVG(Age) > 3 INSERT INTO Habitat (Name) VALUES SQL Server Management Studio (SSMS) is the official graphical CREATE TABLE Habitat ( ORDER BY AVG(Age) DESC; ('Savanna'); tool for managing SQL Server databases. It offers a Id INT PRIMARY KEY IDENTITY, comprehensive interface for administrators and developers to Name VARCHAR(64) An example of a multiple-table query: 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), AGGREGATION AND GROUPING WHERE Id = 2; Age INT, AVG(expr) − average value of expr for the group. HabitatId INT, COUNT(expr) − count of expr values within the group. CREATING AND DISPLAYING FOREIGN KEY (HabitatId) MAX(expr) − maximum value of expr values within the DELETING DATA REFERENCES Habitat(Id) 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. This deletes all rows satisfying the WHERE condition. Use the ALTER TABLE or the EXEC statement to modify a table 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: structure. SELECT COUNT(*) statement: SELECT * FROM Animal; TRUNCATE TABLE Animal; FROM sys.databases; To change a table name: EXEC sp_rename 'AnimalSchema.Animal', 'Pet' To use a specified database: To count the non-NULL values in a column: SELECT COUNT(Name) SQL SERVER CONVENTIONS USE Zoo; To add a column to a table: In SQL Server, use square brackets to handle table or column FROM Animal; 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 multiple To get information about a specified table: To delete a table: FROM Animal SQL statements together. It is typically used in SQL Server exec sp_help 'Animal' DROP TABLE Animal; GROUP BY HabitatId; 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() function: SELECT 'Michael'; To get the number of seconds in a week: DATEADD(day, -3, '2014-04-05'); DATE – stores the year, month, and day in the YYYY-MM-DD Unicode strings are enclosed in single quotes and prefixed with SELECT 60 * 60 * 24 * 7; -- result: 604800 -- result: '2014-04-02' format. capital N: The supported range is '0001-01-01' to '9999-12-31'. In SQL Server, the division operator / performs an integer division To find the difference between two dates, use the DATEDIFF() SELECT N'Michél'; on integer arguments. For example: TIME – stores the hours, minutes, seconds, and nanoseconds in function: CONCATENATION SELECT 25 / 4; -- result 6 the HH:MM:SS[.nnnnnnn] format. SELECT DATEDIFF(year, '2019-05-15', Use the CONCAT() function to concatenate two strings: The supported range is '00:00:00.0000000' to '2017-05-15'); To avoid the integer division, make sure at least one of the SELECT CONCAT(N'Hi ', N'there!'); '23:59:59.9999999'. -- result: -2 arguments is not an integer: -- result: Hi there! SELECT DATEDIFF(month, '2019-06-15', SELECT CAST(25 AS DECIMAL) / 4; SMALLDATETIME – stores the date and time in the YYYY-MM- CONCAT() treats NULL as an empty string: '2023-12-15'); -- result 6.25 DD HH:MM:SS format. SELECT CONCAT(N'Learn ', NULL, N'SQL.com'); -- result: 54 SELECT 25.0 / 4; The supported range is '1900-01-01' to '2079-06-06'. -- result: LearnSQL.com The supported date parts are: year, quarter, month, -- result 6.25 SQL Server allows specifying a separating character (separator) DATETIME – stores the date and time in the YYYY-MM-DD dayofyear, day, week, hour, minute, second, using the CONCAT_WS() function. The separator is placed To get the remainder of a division: HH:MM:SS[.nnn] format. millisecond, microsecond, nanosecond. between the concatenated values: SELECT MOD(13, 2); -- result: 1 The supported range is '1753-01-01' to '9999-12-31'. 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 EXTRACTING PARTS OF DATES N'Norris'); -- result: 1 Olivier Norris HH:MM:SS[.nnnnnnn] format. SELECT ROUND(1234.56789, 3); To extract a part of a date, use the functions YEAR(), MONTH(), FILTERING THE OUTPUT -- result: 1234.568 The supported range is '0001-01-01 00:00:00.0000000' or DAY(): To fetch the city names that are not Berlin: to '9999-12-31 23:59:59.9999999'. SELECT YEAR(CAST('2021-12-31' AS date)); To round a number up: -- result: 2021 SELECT Name DATETIMEOFFSET – stores the date and time in the YYYY-MM- SELECT CEILING(13.1), CEILING(-13.9); SELECT MONTH(CAST('2021-12-31' AS date)); FROM City DD HH:MM:SS[.nnnnnnn][+|-]hh:mm format. -- result: 14, -13 -- result: 12 WHERE Name != N'Berlin'; The supported range is '0001-01-01 00:00:00.0000000' SELECT DAY(CAST('2021-12-31' AS date)); TEXT OPERATORS To round a number down: to '9999-12-31 23:59:59.9999999' in UTC. -- result: 31 To fetch the city names that start with a 'P' or end with an 's': SELECT FLOOR(13.8), FLOOR(-13.2); SELECT Name -- result: 13, -14 WHAT TIME IS IT? You may also use the DATEPART() function: FROM City To get the current datetime without the time-zone offset: SELECT DATEPART(year, '2013-09-15'); WHERE Name LIKE N'P%' OR Name LIKE N'%s'; USEFUL NULL FUNCTIONS SELECT GETDATE(); -- result: 2023-07-27 -- result: 2013 To fetch the city names that start with any letter followed by To fetch the names of the cities whose rating values are not 07:21:13.937 Supported date parts are: year, quarter, month, 'ublin' (like Dublin in Ireland or Lublin in Poland): missing: dayofyear, day, week, weekday, hour, minute, second, To get the current datetime without the time-zone offset in SELECT Name SELECT Name millisecond, microsecond, nanosecond, tzoffset, DATETIME2 data type (higher fractional seconds precision): FROM City FROM City iso_week. SELECT SYSDATETIME(); -- result: 2023-07-27 WHERE Name LIKE N'_ublin'; WHERE Rating IS NOT NULL; 07:21:13.9398213 OTHER USEFUL TEXT FUNCTIONS COALESCE(x, y, ...) To get the current datetime in UTC: CHANGING THE TIME ZONE To get the count of characters in a string: SELECT GETUTCDATE(); -- result: 2023-07-27 Use AT TIME ZONE to convert a date and time value into a To replace NULL in a query with something meaningful: SELECT LEN(N'LearnSQL.com'); -- result: 12 07:21:13.937 target time zone. You may use meaningful time zone names such SELECT Domain, To convert all letters to lowercase: as 'Pacific Standard Time'. SQL Server uses the names COALESCE(Domain, 'domain missing') or in datetime2 data type (higher fractional seconds precision): SELECT LOWER(N'LEARNSQL.COM'); stored in the Windows Registry. FROM Contacts; SELECT SYSUTCDATETIME(); -- result: 2023-07- -- result: learnsql.com The COALESCE() function takes any number of arguments and 27 07:21:13.9398213 To add the target time-zone offset to a datetime value without To convert all letters to uppercase: returns the value of the first argument that is not NULL. offset information: SELECT UPPER(N'LearnSQL.com'); To get the current datetime with the time-zone offset: SELECT start_time AT TIME ZONE 'UTC'; -- result: LEARNSQL.COM NULLIF(x, y) SELECT SYSDATETIMEOFFSET(); To get just a part of a string: To save yourself from division-by-0 errors: -- result: 2023-07-27 07:21:13.9398213 +00:00 To convert values between different time zones: SELECT SUBSTRING(N'LearnSQL.com', 1, 5); SELECT LastMonth, ThisMonth, SELECT '2023-07-20 12:30:00' -- result: Learn ThisMonth * 100.0 / NULLIF(LastMonth, 0) CREATING VALUES AT TIME ZONE 'UTC' To replace a part of a string: AS BetterByPercent To create a date, time, or datetime, write the value as a string and AT TIME ZONE 'Eastern Standard Time'; SELECT REPLACE(N'LearnSQL.com', 'SQL', FROM VideoViews; cast it to the proper type. -- result: 2023-07-20 08:30:00 'Python'); The NULLIF(x, y) function returns NULL if x equals y, else it SELECT CAST('2021-12-31' AS date), Specify the known time-zone offset first (here, UTC) and then the -- result: LearnPython.com returns the value of x value. CAST('2021-12-31 23:59:29' AS 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