You are on page 1of 25

SQLShack

Skip to content

 SQL Server training

 Español

SQL Cheat Sheet for Newbies


February 21, 2023 by Esat Erkec

In this SQL cheat sheet, we’ll look at sample SQL queries that can help you learn basic T-SQL
queries as quickly as possible.

Introduction
Transact-SQL (T-SQL) is an extension of the Structured Query Language (SQL) that is used to
manipulate and fetch data from the Microsoft SQL Server. Despite the clear and rigid
specifications of standard SQL, it does allow database vendors to add their extensions to set
them apart from other products. Moving from this idea, T-SQL had been developed by Microsoft
to program SQL Server and it has a common widely-usage. This SQL cheat will allow you to learn
SQL queries quickly and simply.

Pre-requisites
To practice the examples on this SQL Cheat Sheet, you can use the following query to create the
tables and also populate them with some synthetic data. Besides this option, you can use
this SQL Fiddle link, to practice exercises online.
1

2 CREATE TABLE Online_Customers (Customer_Id INT


PRIMARY KEY IDENTITY(1, 1),
3
Customer_Name VARCHAR(100),
4
Customer_City VARCHAR(100),
5
Customer_Mail VARCHAR(100))
6
GO
7
CREATE TABLE Orders (Order_Id INT PRIMARY KEY
8 IDENTITY(1, 1),

9 Customer_Id INT,

10
11 Order_Total float,

12 Discount_Rate float,

13 Order_Date DATETIME)

14 GO

15 CREATE TABLE Sales (Sales_Id INT PRIMARY KEY


IDENTITY(1, 1),
16
Order_Id INT,
17
Sales_Total FLOAT)
18
GO
19
INSERT INTO [dbo].Online_Customers(Customer_Name,
20 Customer_City, Customer_Mail)

21 VALUES(N'Salvador', N'Philadelphia',
N'tyiptqo.wethls@chttw.org')
22
INSERT INTO [dbo].Online_Customers(Customer_Name,
23
Customer_City, Customer_Mail)
24
VALUES(N'Gilbert', N'San Diego', N'rrvyy.wdumos@lklkj.org')
25
INSERT INTO [dbo].Online_Customers(Customer_Name,
26 Customer_City, Customer_Mail)

27 VALUES(N'Ernest', N'New York', N'ymuea.pnxkukf@dwv.org')

28 INSERT INTO [dbo].Online_Customers(Customer_Name,


Customer_City, Customer_Mail)
29
VALUES(N'Stella', N'Phoenix', N'xvsfzp.rjhtni@rdn.com')
30
INSERT INTO [dbo].Online_Customers(Customer_Name,
31 Customer_City, Customer_Mail)

32 VALUES(N'Jorge', N'Los Angeles', N'oykbo.vlxopp@nmwhv.org')

33 INSERT INTO [dbo].Online_Customers(Customer_Name,


Customer_City, Customer_Mail)
34
VALUES(N'Jerome', N'San Antonio', N'wkabc.ofmhetq@gtmh.co')
35
INSERT INTO [dbo].Online_Customers(Customer_Name,
36
Customer_City, Customer_Mail)
37
VALUES(N'Edward', N'Chicago', N'wguexiymy.nnbdgpc@juc.co')
38
INSERT INTO [dbo].Online_Customers(Customer_Name,
39 Customer_City, Customer_Mail)

40 VALUES(N'John', N'Chicago', N'jxkn.nnbdgpc@juc.co')

41 GO

42 INSERT INTO [dbo].Orders(Customer_Id, Order_Total,


Discount_Rate, Order_Date)
43
VALUES(3, 1910.64, 5.49, CAST('03-Dec-2019' AS DATETIME))
44
INSERT INTO [dbo].Orders(Customer_Id, Order_Total,
45 Discount_Rate, Order_Date)

46 VALUES(4, 150.89, 15.33, CAST('11-Jun-2019' AS DATETIME))


47 INSERT INTO [dbo].Orders(Customer_Id, Order_Total,
Discount_Rate, Order_Date)
48
VALUES(5, 912.55, 13.74, CAST('15-Sep-2019' AS DATETIME))
49
INSERT INTO [dbo].Orders(Customer_Id, Order_Total,
50 Discount_Rate, Order_Date)

51 VALUES(7, 418.24, 14.53, CAST('28-May-2019' AS


DATETIME))
52
INSERT INTO [dbo].Orders(Customer_Id, Order_Total,
53
Discount_Rate, Order_Date)

VALUES(55, 512.55, 13.74, CAST('15-Jun-2019' AS


DATETIME))

INSERT INTO [dbo].Orders(Customer_Id, Order_Total,


Discount_Rate, Order_Date)

VALUES(57, 118.24, 14.53, CAST('28-Dec-2019' AS


DATETIME))

GO

INSERT INTO [dbo].Sales(Order_Id, Sales_Total)VALUES(3,


370.95)

INSERT INTO [dbo].Sales(Order_Id, Sales_Total)VALUES(4,


882.13)

INSERT INTO [dbo].Sales(Order_Id, Sales_Total)VALUES(12,


370.95)

INSERT INTO [dbo].Sales(Order_Id, Sales_Total)VALUES(13,


882.13)

INSERT INTO [dbo].Sales(Order_Id, Sales_Total)VALUES(55,


170.95)

INSERT INTO [dbo].Sales(Order_Id, Sales_Total)VALUES(57,


382.13)

SQL Cheat Sheet


Comma Descript
nd Syntax ion

Used to
fetch
data
SELEC SELECT col1,col2,col3,…,coln FROM from a
T Table_Name table

Used to
limit the
number
SELECT TOP(1) col1,col2,col3,…,coln of the
TOP FROM Table_Name result set

ORDER SELECT col1,col2,col3,…,coln FROM Used to


BY Table_Name ORDER BY col1,col2,col3 sort
…,coln result set
accordin
g to
specified
columns
in the
ascendin
g or
descendi
ng order

Used to
determin
e how
many
rows the
COUNT SELECT COUNT(col1) FROM result set
() Table_Name returns.

Used to
fetch
distinct
values of
the
specified
DISTIN SELECT DISTINCT col1 FROM column(s
CT Table_Name ).

Used to
fetch
matched
rows of
SELECT col1,col2,col3,…,coln FROM TableA
INNER Table_A INNER JOIN Table_B ON and
JOIN Table_A.col = Table_B.col TableB

Used to
fetch all
rows of
TableA
and
matched
SELECT col1,col2,col3,…,coln FROM rows
LEFT Table_A LEFT JOIN Table_B ON from
JOIN Table_A.col = Table_B.col TableB

Used to
fetch all
rows of
TableB
and
matched
SELECT col1,col2 FROM Table_A RIGHT rows
RIGHT JOIN Table_B ON Table_A.col = from
JOIN Table_B.col TableA

Used to
filter the
result set
SELECT col1,col2,col3,…,coln FROM of the
WHERE Table_Name WHERE col1=’col_value’ table

Used to
SELECT col1,col2,col3,…,coln FROM filter
Table_Name WHERE col1 LIKE wildcard
LIKE ‘col_value%’ patterns.

IN SELECT col1,col2,col3,…,coln FROM Used to


filter
multiple
Table_Name WHERE col1 IN values
(‘col_value1′,’col_value2′,’col_value3′, for a
…,’col_valuen’) column.

Used to
combine
two or
more
condition
s in
filtering.
The
matched
row(s)
must
satisfy
SELECT col1,col2,col3,…,coln FROM all
Table_Name WHERE col1 = col_value’ condition
AND AND col2=’col_value’ s

Used to
combine
two or
more
condition
s in
filtering.
The
matched
row(s) is
enough
to satisfy
one of
SELECT col1,col2,col3,…,coln FROM the
Table_Name WHERE col1 = col_value’ condition
OR OR col2=’col_value’ s.

Used to
filter the
result set
accordin
SELECT col1,col2,col3,…,coln FROM g to the
BETWE Table_Name WHERE col1 BETWEEN given
EN ‘col_value1’ AND ‘col_value2’ result set

SQL SELECT Statement


The SELECT statement is used to fetch data from any database table. The syntax of the SQL
SELECT statement is:

2 SELECT Column_Name_1, Column_Name_2, .....,


Column_Name_N FROM Table_Name;
3

In this syntax the Column_Name_1, Column_Name_2, ….., and Column_Name_N indicate the
column name of the tables and we should separate them with a comma (;)after placing the FROM
clause we need to write the table name which we want to fetch data.
1

2 SELECT CustomerName, CustomerCity FROM Online_Customers

If we want to retrieve all columns of the table we can use an asterisk sign (*) in the SELECT
statements.
1

2 SELECT * FROM Online_Customers

Tip: Although using the asterisk sign (*) is included in our SQL Cheat Sheet, we recommend not
using it as much as possible as, because it may cause performance problems.

SQL Aliases
Aliases are the temporary names that we can give to table or column names. So that, we can
make them more readable and understandable. Using the aliases does not make any changes
neither to the original table name or its column names.

2 SELECT

3 Customer.Customer_Name AS [Name of the Customer],


4 Customer.Customer_City AS [City Name of the Customer]

5 FROM Online_Customers Customer

6
As you can see, the column names of the result set have been changed after using aliases in the
above query because of the alias usage.

SQL TOP Statement


The SELECT TOP statement is used to limit the row numbers of the query resultset. For example,
the following query will return only 2 rows of the customer table randomly.

2 SELECT TOP(2)

3 Customer.Customer_Name AS [Name of the Customer],

4 Customer.Customer_City AS [City Name of the Customer]

5 FROM Online_Customers Customer

SQL ORDER BY Clause


The ORDER BY statement is used to sort the fetched result set of the query in either ascending or
descending according to one or more columns. For example, the following query will sort the
result set of the query according to “CustomerName” in a descending manner.
1

2 SELECT

3 Customer.Customer_Name AS [Name of the Customer],

4 Customer.Customer_City AS [City Name of the Customer]

5 FROM Online_Customers Customer

6 ORDER BY Customer_Name DESC

7
SQL COUNT() Function
In this part of the SQL Cheat Sheet, we will learn the COUNT() function. The SQL COUNT()
function returns the number of rows in the result set. For example, the following query will return
the number of rows in the Customer table.

2 SELECT

3 COUNT(Customer.Customer_City) AS [Row_Number]

4 FROM Online_Customers Customer

SQL DISTINCT Operator


The DISTINCT operator allows us to retrieve only distinct values of the specified columns in the
queries. As we can the following query only returns the different values of the city names.
SQL Join Operations
Due to the nature of the relational database relationship approach, we do not store all data in
one table. Because of this, we need to create a result set by combining the data we should get
data from different tables. This is exactly the point, joining the tables will help us. Commonly, we
use 3 different joining methods in SQL. Now let’s look at these 3 different join types which are
involved in our SQL Cheat Sheet.

The inner join allows joined tables to return rows that match each other.

The following query will return the customers who have only orders.

2 SELECT oc.Customer_Id AS [Customer_Id]

3 , o.Customer_Id AS [Customer_Id]

4 , oc.Customer_Name AS [Name of the Customer]

5 , oc.Customer_City AS [City Name of the Customer]

6 , o.Order_Total AS [Order_Total]

7 FROM Online_Customers AS oc

8 INNER JOIN Orders AS o

9 ON oc.Customer_Id = o.Customer_Id
10

The left join allows returning all rows from the left table and any matching records from the right
table.

The following query will return all customers and their matched orders of them.

2 SELECT oc.Customer_Id AS [Customer_Id]

3 , o.Customer_Id AS [Customer_Id]

4 , oc.Customer_Name AS [Name of the Customer]

5 , oc.Customer_City AS [City Name of the Customer]

6 , o.Order_Total AS [Order_Total]

7 FROM Online_Customers AS oc

8 LEFT JOIN Orders AS o

9 ON oc.Customer_Id = o.Customer_Id

10
The right join allows returning all rows from the right table and any matching records from the
right table.

The following query will return all orders and their matched customers of them.

2 SELECT oc.Customer_Id AS [Customer_Id]

3 , o.Customer_Id AS [Customer_Id]

4 , oc.Customer_Name AS [Name of the Customer]

5 , oc.Customer_City AS [City Name of the Customer]

6 , o.Order_Total AS [Order_Total]

7 FROM Online_Customers AS oc

8 RIGHT JOIN Orders AS o

9 ON oc.Customer_Id = o.Customer_Id

10
SQL Server Basic Filter Operations
In this part of the SQL Cheat Sheet, we will look at how to filter out the data from a table for the
basic requirements.

Equal Operator (=): We use the equal operator to compare the values of the column with any
value. For example, if we want to return customers who are located in New York we can use the
following query.
1

2 SELECT

3 Customer.Customer_Name AS [Name of the Customer],

4 Customer.Customer_City AS [City Name of the Customer]

5 FROM Online_Customers Customer

6 WHERE

7 Customer.Customer_City='New York'

Non-Equal Operator (<>): The Non-Equal operator works completely reverse of the equal
operator, and it returns all rows except rows equal to any value. For example, if we want to return
customers whose names are not equal to “Edward“, we can use the following query.
1

2 SELECT

3 Customer.Customer_Name AS [Name of the Customer],

4 Customer.Customer_City AS [City Name of the Customer]

5 FROM Online_Customers Customer

6 WHERE

7 Customer.Customer_Name<> 'Ernest'
8

We can use the following operators in T-SQL to filter out the rows of the tables.

Operator Description

= Equals to

<> Not Equal

!= Not Equal

> Greater than

>= Greater than to equals to

< Less than

<= Less than or equal to


Tip: There is no difference between the “<>” sign and “!=”, we can use both of them as non-
equal operators.

SQL Server LIKE Operator


The LIKE operator is a logical operator and filters the matched record in the table according to a
specified string pattern.

The percent wildcard (%) indicates zero or more characters. The following query returns the
customers whose name starts with an “S” character.
1

2 SELECT

3 Customer.Customer_Name AS [Name of the Customer],

4 Customer.Customer_City AS [City Name of the Customer]

5 FROM Online_Customers Customer

6 WHERE

7 Customer.Customer_Name LIKE 'S%'

8
The underscore (_) wildcard indicates exactly one character in a string pattern.
1

2 SELECT

3 Customer.Customer_Name AS [Name of the Customer],

4 Customer.Customer_City AS [City Name of the Customer]

5 FROM Online_Customers Customer

6 WHERE

7 Customer.Customer_City LIKE 'N_w Y_rk'

SQL Server IN Keyword


We’ll now take a look at another operator from the SQL Cheat Sheet. The IN operator allows us
to filter out multiple values in the WHERE clause. The values must be entered in parentheses and
separated with a comma sign.

2 SELECT

3 Customer.Customer_Name AS [Name of the Customer],

4 Customer.Customer_City AS [City Name of the Customer]

5 FROM Online_Customers Customer

6 WHERE

7 Customer.Customer_Name IN ('Salvador', 'Edward')

8
SQL Server AND Operator
The AND operator is used to combine two or more two conditions in the where clause and it
enables to return of data that satisfies all the conditions criteria. For example, the following query
returns customers whose customer name is “Edward” and who live in the city of “Chicago”. For
any row to be included in the query’s result set, it must satisfy both conditions.

2 SELECT

3 Customer.Customer_Name AS [Name of the Customer],

4 Customer.Customer_City AS [City Name of the Customer]

5 FROM Online_Customers Customer

6 WHERE

7 Customer.Customer_City ='Chicago'

8 AND Customer.Customer_Name='Edward'

SQL Server OR Operator


The OR operator is used to combine two or more two conditions in the where clause and returns
data that satisfies any of the conditions.

2 SELECT

3 Customer.Customer_Name AS [Name of the Customer],

4 Customer.Customer_City AS [City Name of the Customer]

5 FROM Online_Customers Customer

6 WHERE

7 Customer.Customer_City ='Chicago'
8 OR Customer.Customer_Name='Edward'

SQL Server BETWEEN Operator


The BETWEEN operator filters the values within a given range.

2 SELECT oc.Customer_Id AS [Customer_Id]

3 , o.Customer_Id AS [Customer_Id]

4 , oc.Customer_Name AS [Name of the Customer]

5 , oc.Customer_City AS [City Name of the Customer]

6 , o.Order_Total AS [Order_Total]

7 FROM Online_Customers AS oc

8 INNER JOIN Orders AS o

9 ON oc.Customer_Id = o.Customer_Id

10 WHERE Order_Total BETWEEN 158 AND 418.24

11

Summary
In this article, we looked at a SQL Cheat Sheet that helps to learn the fundamentals of T-SQL
queries.

See more
Seamlessly integrate a powerful, SQL formatter into SSMS and/or Visual Studio with ApexSQL
Refactor. ApexSQL Refactor is a SQL query formatter but it can also obfuscate SQL, refactor
objects, safely rename objects and more – with nearly 200 customizable options
Esat Erkec
Esat Erkec is a SQL Server professional who began his career 8+ years ago as a Software Developer.
He is a SQL Server Microsoft Certified Solutions Expert.

Most of his career has been focused on SQL Server Database Administration and Development. His
current interests are in database administration and Business Intelligence. You can find him
on LinkedIn.

View all posts by Esat Erkec

Related Posts:

1. In-Memory OLTP Series – Data migration guideline process on SQL Server 2016
2. How to create and configure a linked server in SQL Server Management Studio
3. Different ways to SQL delete duplicate rows from a SQL Table
4. Overview of Microsoft SQL Server Management Studio (SSMS)
5. Microsoft Clustering in SQL Server

SQL commands, T-SQL

2,426 Views
Follow us!
Popular

 SQL Convert Date functions and formats


 SQL Variables: Basics and usage
 Different ways to SQL delete duplicate rows from a SQL Table
 SQL PARTITION BY Clause overview
 How to UPDATE from a SELECT statement in SQL Server
 SELECT INTO TEMP TABLE statement in SQL Server
 SQL WHILE loop with simple examples
 How to backup and restore MySQL databases using the mysqldump command
 SQL Server functions for converting a String to a Date
 Overview of SQL RANK functions
 The Table Variable in SQL Server
 Understanding the SQL MERGE statement
 SQL multiple joins for beginners with examples
 Understanding the SQL Decimal data type
 SQL Server table hints – WITH (NOLOCK) best practices
 INSERT INTO SELECT statement overview and examples
 CASE statement in SQL
 DELETE CASCADE and UPDATE CASCADE in SQL Server foreign key
 SQL CROSS JOIN with examples
 SQL Not Equal Operator introduction and examples
Trending
 SQL Server Transaction Log Backup, Truncate and Shrink Operations
 Six different methods to copy tables between databases in SQL Server
 How to implement error handling in SQL Server
 Working with the SQL Server command line (sqlcmd)
 Methods to avoid the SQL divide by zero error
 Query optimization techniques in SQL Server: tips and tricks
 How to create and configure a linked server in SQL Server Management Studio
 SQL replace: How to replace ASCII special characters in SQL Server
 How to identify slow running queries in SQL Server
 SQL varchar data type deep dive
 How to implement array-like functionality in SQL Server
 All about locking in SQL Server
 SQL Server stored procedures for beginners
 Database table partitioning in SQL Server
 How to drop temp tables in SQL Server
 How to determine free space and file size for SQL Server databases
 Using PowerShell to split a string into an array
 KILL SPID command in SQL Server
 How to install SQL Server Express edition
 SQL Union overview, usage and examples

Solutions
 Read a SQL Server transaction log
 SQL Server database auditing techniques
 How to recover SQL Server data from accidental UPDATE and DELETE operations
 How to quickly search for SQL database data and objects
 Synchronize SQL Server databases in different remote sources
 Recover SQL data from a dropped table without backups
 How to restore specific table(s) from a SQL Server database backup
 Recover deleted SQL data from transaction logs
 How to recover SQL Server data from accidental updates without backups
 Automatically compare and synchronize SQL Server data
 Open LDF file and view LDF file content
 Quickly convert SQL code to language-specific client code
 How to recover a single table from a SQL Server database backup
 Recover data lost due to a TRUNCATE operation without backups
 How to recover SQL Server data from accidental DELETE, TRUNCATE and DROP
operations
 Reverting your SQL Server database back to a specific point in time
 How to create SSIS package documentation
 Migrate a SQL Server database to a newer version of SQL Server
 How to restore a SQL Server database backup to an older version of SQL Server
Categories and tips

 ►Auditing and compliance (50)


 Azure (308)
 Azure Data Studio (46)
 Backup and restore (108)
 ►Business Intelligence (486)
 Data science (21)
 ►Database design (235)
 ►Database development (429)
 DBAtools (35)
 DevOps (23)
 DevSecOps (2)
 Documentation (22)
 ETL (76)
 ►Features (213)
 Importing, exporting (52)
 Installation, setup and configuration (122)
 Jobs (42)
 ▼Languages and coding (713)
o Cursors (9)
o DDL (9)
o DML (6)
o JSON (17)
o PowerShell (77)
o Python (38)
o R (16)
o SQL commands (206)
o SQLCMD (7)
o String functions (21)
o T-SQL (291)
o XML (15)
 Lists (12)
 Machine learning (37)
 Maintenance (99)
 Migration (50)
 Miscellaneous (1)
 ►Performance tuning (871)
 ►Professional development (71)
 Recovery (33)
 Security (85)
 Server management (24)
 SQL Azure (272)
 SQL Server Management Studio (SSMS) (91)
 SQL Server on Linux (22)
 ►SQL Server versions (177)
 ►Technologies (357)
 Uncategorized (4)
 Utilities (21)
Helpers and best practices

 BI performance counters
 SQL code smells rules
 SQL Server wait types

© 2023 Quest Software Inc. ALL RIGHTS RESERVED. | GDPR | Terms of Use | Privacy

You might also like