SQL Keywords
Here is a list of SQL Keywords that we will learn
A
ALLcan be added to aUNIONto include duplicates, or lets us compare to multiple values in a subquery.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 the Primary Key, Foreign Key, any default values, 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 in 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(xx, n, date1)addsnxxtodate1(nmay be negative). See the Queries page for possible values forxx.- e.g.,
DATEADD(yy, 5, HireDate)returns the date 5 years after theHireDate.
- e.g.,
DATEDIFF(xx, date1, date2)returns the number ofxxfromdate1todate2. See the Queries page for possible values forxx.- e.g.,
DATEDIFF(dd, OrderDate, ShipDate)returns the number of days betweenOrderDateandShipDate.
- e.g.,
DATENAME(xx, date1)returns a string representation of thexxofdate1. See the Queries page for possible values forxx.- e.g.,
DATENAME(dw, '2020-01-01')returnsWednesday.
- e.g.,
DATEPART(xx, date1)returns integer representation of thexxofdate1. See the Queries page for possible values forxx.- 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).DELETEstatements remove record(s) from a table. More on the DML page. e.g.,DELETE FROM Student WHERE GraduationStatus = 'Y'.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 DROP a table that has triggers associated with it, the triggers are dropped as well.
DROP TRIGGERdeletes a trigger from the database.DROP VIEWdeletes a view from the database.
E
EXEC ProcedureName ParameterNameis how we execute a stored procedure called ProcedureName with a parameter called ParameterName. 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!
G
- e.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 to true. Optionally, anIFstatement may have anELSEblock: that code will only run if the original condition evaluates to false.IF EXISTS (...)will run the query in parentheses, and will return true if 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 INSERT
INSERT INTO Item (ItemID,
ItemName,
Cost,
Description)
VALUES (123,
'Whatchamacallit',
SELECT AVG(Cost) FROM Item -- INSERTing a value from a subquery,
NULL)
INSERT INTO Student(FirstName,LastName)
SELECT FirstName,Lastname FROM Employee
-- this is essentially 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 are joining a parent to child, OR child to parent, you will 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 are joining parent to child, you will get parents regardless of whether they have child records.
- If you are joining child to parent, you will 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 qre joining parent to child, you will get only child records, so you should use
INNER JOINinstead. - If you are joining child to parent, you will get parents regardless of whether they have child records.
- If you qre joining parent to child, you will get only child records, so you should use
table1 FULL OUTER JOIN table2returns all records that exist in either table.- If you are joining parent to child, you will get parents regardless of whether they have child records, so you should use
LEFT JOINinstead. - If you are joining child to parent, you will get parents regardless of whether they have child records, so you should use
RIGHT JOINinstead.
- If you are joining parent to child, you will 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 LEFTparents regardless of whether they have child records use INNER JOINinsteadRIGHTuse INNER JOINinsteadparents 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)returns length number of characters, starting at the left. e.g.,LEFT('12345', 2)returns the first2characters of12345:12.- 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.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 is 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 = 10” is correct. “WHERE VALUE = 5 OR 10” is incorrect, because “10” is not a boolean expression.
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.RIGHT(column | expression, length)returns length number of characters, starting at the right. e.g.,RIGHT('12345', 2)returns the last2characters of the string:45.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 is also how we can assign literal values to multiple variables, or assign values to a variable
FROMaSELECTstatement. 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 is also how we can assign literal values to multiple variables, or assign values to a variable
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 iss 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.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 does not 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 - The
UPDATE()function returns true if anINSERTorUPDATEwas attempted on a specified column. These are used in triggers to let us branch around the logic if the column of interest wasn’t updated.
- e.g.,
UPPER(column | expression)returns a string inUPPERCASE. 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 will 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 to true only ifFirsNameis exactlyBob; any extra letters, punctuation, or spacing, or another word entirely, evaluates to false.
- 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 < 5is true if the value ofSubtotalis less than (not equal to) the value5.
- e.g.,
<=means less than or equal to- e.g.,
Subtotal <= 5is true if the value ofSubtotalis less than, or exactly, the value5.
- e.g.,
>means greater than- e.g.,
Total > 10is true if the value of Total is greater than (not equal to) the value10.
- e.g.,
>=means greater than or equal to- e.g.,
Total >= 10is true if the value of Total is greater than, or exactly, the value10.
- e.g.,