Here is a (hopefully) exhaustive list of all the SQL keywords and functions we’ve learned!
🔥 Tip: Use Ctrl-F (or Command-F on a Mac 🍎) to search for specific words on this page.
A
ALLcan be added to aUNIONto include duplicates, or lets us compare to multiple values in a subquery:WHERE Grade > ALL (SELECT Grade …).ALTER PROCEDUREreplaces the previously saved query in a stored procedure.ALTER TABLElets us make changes to a table that already exists, like adding an a new column or constraint. The DDL page explains exactly what types of changes we can make.ALTER TRIGGERreplaces the SQL in an existing trigger with new logic.ALTER VIEWlets us replace the query defining a view with a new query.ANDis used between two boolean expressions, if we need both expressions to be true. You need a full and complete expression on both sides ofAND.ANYcompares against any of the values:WHERE Grade > ANY (SELECT Grade … )AVG()is a function that returns the average of numeric values.
B
BEGIN TRANSACTIONmarks the beginning of a transaction. This is the point we come back to if theTRANSACTIONis laterROLLedBACK.BETWEENwill return records between 2 values, including those 2 values: e.g.WHERE Mark BETWEEN 50 AND 100
C
COMMIT TRANSACTIONmarks the end of the transaction, and makes everything that happened sinceBEGIN TRANSACTIONpermanent.CONSTRAINTs can be added to define thePRIMARY KEY,FOREIGN KEY, anyDEFAULTvalues, or conditions a column has (e.g. what values are allowed, or what format the value must be in). More on constraints on the DDL page.COUNT(*)returns the number of rows returned by a query.COUNT(ColumnName)returns the number of non-null values in the specified column.CREATE NONCLUSTERED INDEXlets us create a new index, which speeds up data retrieval.CREATE PROCEDURElets us create a set of SQL statements that is stored in the database, and can be run as needed. Check out the Stored Procedures page for more info.CREATE TABLEcreates the structure for a new table in our database (see DDL page for syntax)IDENTITY(seed, increment)is what we add to each column that is a technical key (i.e. SQL will generate the value for us)
CREATE TRIGGERcreates a new trigger that will be executed by a specific kind of DML statement on a specific table. Learn more on the triggers page.CREATE VIEWlets us save a specific query, andSELECTfrom that view just like we select from a table. More on the Views page.
D
DATEADD(units, num, date)addsnumunitstodate(nummay be negative). See the Queries page for possible values forunits.- e.g.
DATEADD(yy, 5, HireDate)returns the date5years after theHireDate.
- e.g.
DATEDIFF(units, date1, date2)returns the number ofunitsfromdate1todate2. See the Queries page for possible values forunits.- e.g.
DATEDIFF(dd, OrderDate, ShipDate)returns the number of days betweenOrderDateandShipDate.
- e.g.
DATENAME(units, date)returns a string representation of theunitsofdate. See the Queries page for possible values forunits.- e.g.
DATENAME(dw, '2020-01-01')returnsWednesday.
- e.g.
DATEPART(units, date)returns integer representation of theunitsofdate. See the Queries page for possible values forunits.- e.g.
DATEPART(mm, '2020-03-01')returns3because March is the 3rd month of the year. YEAR(date1)functions the same asDATEPART(yy, date1)- e.g.
YEAR('2020-03-01')returns2020.
- e.g.
MONTH(date1)functions the same asDATEPART(mm, date1)- e.g.
MONTH('2020-03-01')returns3.
- e.g.
DAY(date1)functions the same asDATEPART(dd, date1)- e.g.
DAY('2020-03-01')returns1.
- e.g.
- e.g.
DECLARElets us create a new variable.- e.g.
DECLARE @FirstName VARCHAR(10), @LastName VARCHAR(20)
- e.g.
DELETEstatements remove record(s) from a table. More on the DML page.- e.g.
DELETE FROM Student WHERE GraduationStatus = 'Y'
- e.g.
DISTINCTcan be added to aSELECTorCOUNT()to only count unique rows or values.DROP INDEXdeletes an index from the database.DROP PROCEDUREdeletes a stored procedure.DROP TABLEdeletes a table from the database: both its structure AND its contents.- If you
DROPa table that has triggers associated with it, the triggers are dropped as well.
- If you
DROP TRIGGERdeletes a trigger from the database.DROP VIEWdeletes a view from the database.
E
EXEC ProcedureName ParameterNameis how we execute a stored procedure calledProcedureNamewith a parameter calledParameterName. Some SPs have no parameters, some have one, some have many: if we have multiple parameters, we separate them with commas like this:EXEC ProcedureName Param1, Param2.- e.g.
EXEC sp_help Customersruns thesp_helpon theCustomerstable. - e.g.
EXEC sp_helptext CustomerViewrunssp_helptexton theCustomerViewview. It can also be used to get the definition of triggers!
- e.g.
G
GetDate()returns the current datetime (i.e. today’s date).GOis a batch terminator. It basically says, “Hey SQL, execute up to this point. Everything after this point is a separate batch.”
I
IFis a conditional statement: the code within anIFblock will only run if its condition evaluates toTRUE. Optionally, anIFstatement may have anELSEblock: that code will only run if the original condition evaluates toFALSE.IF EXISTS (...)will run the query within the parentheses, and will returnTRUEif at least one record is returned. This is helpful to check if there are existing records toUPDATEorDELETEbefore trying toUPDATEorDELETEthem.INlets us check for an exact match within a list of values. e.g.WHERE StudentID IN (20001, 20002, 20004)INSERTlets us add a new row (or rows) to a table. We can add using hardcoded values, the results of a subquery, or the results of aSELECTstatement! More on the DML page. Some examples:INSERT INTO Staff (FirstName, LastName) VALUES ('Bob', 'Smith') , ('Bob', 'Jones') --inserting 2 rows in a single INSERTINSERT INTO Item (ItemID , ItemName , Cost , Description) VALUES (123 , 'Thingamabob' , SELECT AVG(Cost) FROM Item -- INSERTing a value from subquery! , NULL)INSERT INTO Student (FirstName, LastName) SELECT FirstName, LastName FROM Employee -- this is basically copying values from one table to another
J
JOINlets us join data from multiple tables.table1 INNER JOIN table2returns only records that exist in both tables.- If you’re joining a parent to child, OR child to parent, you’ll only get records for parents that have child records.
table1 LEFT JOIN table2returns all records in table1, regardless of whether they exist in table2.- If you’re joining parent to child, you’ll get parents regardless of whether they have child records.
- If you’re joining child to parent, you’ll get only child records, so you should use
INNER JOINinstead.
table1 RIGHT JOIN table2returns all records in table2, regardless of whether they exist in table1.- If you’re joining parent to child, you’ll get only child records, so you should use
INNER JOINinstead. - If you’re joining child to parent, you’ll get parents regardless of whether they have child records.
- If you’re joining parent to child, you’ll get only child records, so you should use
table1 FULL OUTER JOIN table2returns all records that exist in either table.- If you’re joining parent to child, you’ll get parents regardless of whether they have child records, so you should use
LEFT JOINinstead. - If you’re joining child to parent, you’ll get parents regardless of whether they have child records, so you should use
RIGHT JOINinstead.
- If you’re joining parent to child, you’ll get parents regardless of whether they have child records, so you should use
-
How to pick a
JOINtype:joining Parent to Child joining Child to Parent INNERonly records for parents that have child records only records for parents that have child records LEFTall parents regardless of whether they have child records use INNER JOINinsteadRIGHTuse INNER JOINinsteadall parents regardless of whether they have child records FULL OUTERuse LEFT JOINinsteaduse RIGHT JOINinstead
L
LEN(column | expression)returns the length of a string or expression. e.g.LEN('hello')has the value5.LEFT(column | expression, length)returnslengthnumber of characters, starting at the left.- e.g.
LEFT('12345', 2)returns the first2characters of12345:12.
- e.g.
- The
LIKEoperator lets us do pattern matching on a character. This is useful in aCHECKconstraint or in aWHEREclause. Check out the DDL page to see the wildcards we can use within our patterns. LOWER(column | expression)returns a string in all lowercase.- e.g.
LOWER('Bob')returnsbob.
- e.g.
LTRIM(column | expression)trims any leading whitespace from a string (e.g. spaces and tabs at the start of a string).
M
MAX()retuns the maximum value from a column of numeric, date, or character values.MIN()retuns the minimum value from a column of numeric, date, or character values.
N
NOTcan be added to many other keywords:NOT IN,NOT BETWEEN,NOT NULL.NULLis the absence of a value. We can test whether or not a value is null by usingIS NULLin our clause.- We do not use “
= NULL”. Why?NULLis not a value so it’s impossible to be equal to it.
- We do not use “
O
ORis used between two boolean expressions, if we need either to be true. Both sides of the expression need to be a full and complete boolean expression:- e.g.
WHERE Value = 5 OR Value = 10is correct. WHERE VALUE = 5 OR 10is incorrect, because10is not a boolean expression.
- e.g.
P
PRINTlets us print informational messages to the screen to help with testing and debugging.
R
RAISERROR('error message', 16, 1)is how we raise errors to a user. For example: if a parameter is missing, a DML statements fails, or anUPDATEorDELETEaffects zero records. We should always include helpful error messages so the user knows what went wrong.REVERSE(column | expression)returns a string in reverse order:- e.g.
REVERSE('123')returns321.
- e.g.
RIGHT(column | expression, length)returnslengthnumber of characters, starting at the right.- e.g.
RIGHT('12345', 2)returns the last2characters of the string:45.
- e.g.
ROLLBACK TRANSACTIONmarks the end of a transaction, and “undoes” everything that happened sinceBEGIN TRANSACTION.RTRIM(column | expression)trims any trailing whitespace (e.g. spaces and tabs at the end of a string) from a string.
S
SELECTis how we start a query that retrieves data from our database. Details on all its parts are available on the Queries page.- It’s also how we can assign literal values to multiple variables, or assign values to a variable using the results of a
SELECTstatement. Check out the Stored Procedures page for more info. - We can also use it to get info from our databases, like a list of triggers:
SELECT Name FROM SysObjects WHERE Type = 'TR'
- It’s also how we can assign literal values to multiple variables, or assign values to a variable using the results of a
SETlets us assign a literal value to a variable: e.g.SET @FirstName = 'Bob'SOMEcompares against any of the values:WHERE Grade > SOME (SELECT Grade … )- It’s the same as
ANY.
SUBSTRING(column | expression, start, length)returns a subset of characters from a string or expression.- e.g.
SUBSTRING('abcdefg', 2, 3)returns3characters, starting at position2:bcd.
- e.g.
SUM()is a function that returns the sum of a column containing numeric values. e.g.SUM(GST)will take all the values in theGSTcolumn, add them together, and return the total.
U
UNIONlets us combine the results of multiple SQL queries, as long as they have the same number of columns and similar data types. The columns are named according to the first query in theUNION(i.e. the names of the columns in subsequent queries doesn’t appear in the results).UPDATEstatements let us change the values of one or more columns in existing rows. More on the DML page.- e.g.
UPDATE Student SET FirstName = 'Bob', LastName = 'Smith' WHERE StudentID = 123
- e.g.
- The
UPDATE(ColumnName)function returnsTRUEif anINSERTorUPDATEwas attempted on the specified column. These are used in triggers to let us branch around the logic if the column of interest wasn’t updated. UPPER(column | expression)returns a string in UPPERCASE. e.g.UPPER('Bob')returnsBOB.
Other Operators
@@erroris a global variable that holds the error code for the most recently executed statement. If that statement did not error, it has a value of0. We’ll check its value after every DML statement.@@identityreturns the most recently used identity value.@@rowcountreturns the number of rows affects by the most recent statement.=lets us look for an exact match (is equal to)- e.g.
FirstName = 'Bob'evaluates toTRUEonly if FirsName is exactly “Bob”. Any extra letters, punctuation, or spacing, or another word entirely, evaluates toFALSE.
- e.g.
<>or!=both mean is not equal to- e.g.
@@error <> 0is how we check if@@errorhas a value other than0.
- e.g.
<means less than- e.g.
Subtotal < 5isTRUEif the value ofSubtotalis strictly less than the value5.
- e.g.
<=means less than or equal to- e.g.
Subtotal <= 5isTRUEif the value ofSubtotalis less than, or exactly equal to, the value5.
- e.g.
>means greater than- e.g.
Total > 10isTRUEif the value ofTotalis strictly greater than the value10.
- e.g.
>=means greater than or equal to- e.g.
Total >= 10isTRUEif the value ofTotalis greater than, or exactly equal to, the value10.
- e.g.