SQL Cheatsheet
Code snippets for common tasks with SQL Server and SQL Express
Updated: 04 October 2023
Mostly applies to SQL Server and SQL Express
Log Into Instance
Instance Level Operations
List Instance Databases
Create Database
Drop Database
Database Level Operations
List Database Tables
List Columns in Table
Create Table
Update Column Data Type
Add Column Constraint
Create Table with Links
Drop Table
Insert Item into Table
Retrieve Table Values
We can retrieve all values from a table with:
We can get a specific set of values with a condition
Or search for a pattern in a field with LIKE
:
Update Table Item
Values in List
We can use the IN
operator to select some data based on values being in a given list
Testing Statements
When running SQL queries it may sometimes be necessary to check if your query will work as expected before you actually run it you can wrap your query in:
ROLLBACK
will roll back to the DB status before the query was carried out
And once you have verified that the query did what you expected, you can change the ROLLBACK
to COMMIT
We can test a deletion of a Person
and view the result with:
And we can then COMMIT
this when we are sure it works
Table Joining
Inner Join
To use an Inner Join based on two tables we can use the INNER JOIN
keywords and then get the fields from the tables we want to use for our output table:
Inner Queries
You can use subqueries inside of SQL queries for the purpose of comparing data against without actually returning/selecting the data from the inner query