click below
click below
Normal Size Small Size show me how
SQL
Querying T-SQL
| Term | Definition |
|---|---|
| OUTER APPLY | Operator returns all the rows from the left table expression irrespective of its match with the right table expression. Like a LEFT OUTER JOIN. |
| CROSS APPLY | Operator returns only those rows from the left table expression (in its final output) if it matches with the right table expression. In other words, the right table expression returns rows for the left table expression match only. |
| TRY CATCH blocks | Are not allowed within functions. Error handling needs to be placed in the code that calls the function instead. |
| datetime to datetime2 conversion | Datetime must be in increments of 0.000, 0.003 or 0.007 in order to be converted to datetime2 without rounding. |
| PIVOT | Converts rows to columns |
| UNPIVOT | Converts columns to rows |
| datetimeoffset() | Stores the date and time in UTC and a timezone offset. This allows both UTC and a local time to be stored in the same field. |
| What kind of join can you use to invoke a table-valued function? | CROSS APPLY, OUTER APPLY |
| serializable | Prevents other users from modifying the data until the transaction has completed. |
| Windows identity of the user | ORIGINAL_LOGIN() |
| T-SQL conversion functions | CAST and CONVERT |
| CAST | FUNCTION (source_expression AS target_type) |
| CONVERT | FUNCTION(target_type, source_expression [,style_number]) |
| TRY_CAST, TRY_CONVERT, TRY_PARSE | Return a NULL if the conversion is not valid instead of failing. |
| DATEPART | FUNCTION(month,'20170212') = returns 2 |
| DATENAME | FUNCTION(month,'20170212') = returns 'February' |
| DATEFROMPARTS | FUNCTION(2017,02,12) = returns '2017-02-12' |
| EOMONTH | FUNCTION(SYSDATETIME()) = returns '2017-02-29' |
| DATEADD | FUNCTION(year,1,'20170212') = returns '2018-02-12' |
| DATEDIFF using day part | FUNCTION(day,'20160212','20170212') = returns 336 |
| DATEDIFF using year part | FUNCTION(year,'20161231','20170101') = returns 1 |
| SWITCHOFFSET | FUNCTION(SYSDATETIMEOFFSET(),'-08:00') = adjusts the input datetimeoffset value adjusted to a requested target offset (from the UTC time zone). |
| TODATETIMEOFFSET | FUNCTION(mydatetime, theoffsetvalue) |
| AT TIME ZONE | Function compensating for daylight savings time. FUNCTION 'UTC' |
| LEFT | FUNCTION('abcde',3) = returns 'abc' |
| RIGHT | FUNCTION('abcde',3 = returns 'cde' |
| CHARINDEX | FUNCTION(' ', 'Inigo Montoya') = returns 6 |
| PATINDEX | FUNCTION('%[0-9]%', 'abcd123efgh') = returns 5 |
| LEN | FUNCTION(N'xyz') = returns 3, removes trailing spaces. |
| DATALENGTH | FUNCTION(N'xyz') = returns 6. Counts 2 bytes per character, and does not removing trailing spaces. |
| REPLACE | FUNCTION('.1.2.3.', ',' , '/') = returns '/1/2/3/' |
| REPLICATE | FUNCTION('0', '10') = returns '0000000000' |
| COALESCE | Function that accepts a list of expressions as input and returns the first that is not NULL, or NULL if all are NULLs. The datatype of the returned input determines the datatype of the result. |
| ISNULL | Like COALESCE, but with only 2 inputs. The datatype of the first input determines the datatype of the result. |
| NULLIF | This function accepts 2 input expressions, returns NULL if they are equal, and returns the first input if they are not. |
| IIF | FUNCTION(<predicate>,<true_result>,<false_or_unknown_result>) = returns one value if an input predicate is true, and another value if it is false. |
| @@ROWCOUNT | System function that returns the number of rows affected by the last statement that you executed. |
| COMPRESS | System function that enables you to compress an input character or binary string using the GZIP algorithm into a result binary string. |
| CONTEXT_INFO | System function that enables you to set a binary string of up to 128 bytes that is associated with your session. It can be read from anywhere in your session. |
| NEWID() | Generates a UNIQUEIDENTIFIER typed value (GUID). |
| Function Determinism | Characteristic that indicates whether the function is guaranteed to return the same result given the same set of input values (including an empty set) in different invocations. |
| SCOPE_IDENTITY | Function that returns the last identity column that was inserted into an identity column. |
| THROW | Statement takes 3 parameters: error number, message, and state. Error number must be between 50000 and 2147483647 for user defined errors. State must be between 0 and 255. |
| FOR SYSTEM_TIME AS OF | Displays information that was valid at a specific point in time (temporal tables). |
| CUBE | Cannot be used in a SELECT statement. Part of GROUP BY clause. |
| RAISERROR | Cannot be used to report system errors. System errors have error numbers less than 50000. |
| RAISERROR | Error reporting that always requires parameters. |
| derived table | Can only be used within the current statement. |
| table-valued user-defined function | Can be used anywhere a table or view can be used. |
| WITH SCHEMABINDING | Required statement for indexed views. |
| Used in the GROUP BY clause. | GROUPING SETS, CUBED, ROLLUP. |
| GROUPING | FUNCTION(columnname) AS alias; accepts a single element as input and returns 0 when the element is part of the grouping set and 1 when it is not. |
| GROUPING_ID | FUNCTION(column1, column2, column3) AS alias; returns an id based on which elements are part of the grouping set. |
| ROW_NUMBER | FUNCTION() OVER (ORDER BY val) AS alias; function that computes unique incrementing integers starting with 1 within the window partition based on the window ordering (for entire result set). |
| RANK | FUNCTION() OVER (ORDER BY val) AS alias; function that computes incrementing integers starting with 1 for the result set. Assigns the same ranking value to rows that share the same ordering value but continues ranking by skipping the unused rank numbers. |
| DENSE_RANK | FUNCTION() OVER (ORDER BY val) AS alias; function that computes incrementing integers starting with 1 for the result set. Assigns the same ranking value to rows that share the same ordering value then continues with the next number in sequence. |
| NTILE | FUNCTION(10) OVER (ORDER BY val) AS alias; function that separates result set into groups of result set/10 and assigns each group an incrementing integer as ID. If there is a remainder, an extra row is added to each group from the top of the set. |
| Window Offset Functions | LAG, LEAD, FIRST_VALUE, LAST_VALUE |
| LAG | FUNCTION(val) OVER(PARTITION BY custid ORDER BY date) AS prev_val; function that returns the value of the previous row (default offset is 1 if not specified). |
| LAG | FUNCTION(val, 3, 0) OVER(PARTITION BY custid ORDER BY date) AS three_prev_val; function that returns the value of the row 3 previous, and if none exists for that offset, returns 0 instead of NULL. |
| LEAD | FUNCTION(val) OVER(PARTITION BY custid ORDER BY date) AS next_val; function that returns the value of the next row (default offset is 1 if not specified). |
| LEAD | FUNCTION(val, 2, 0) OVER(PARTITION BY custid ORDER BY date) AS two_next_val; function that returns the value of the next next row, or if none exists for that offset, returns 0 instead of NULL. |
| FIRST_VALUE | FUNCTION(val) OVER(PARTITION BY custid ORDER BY orderdate ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as val; returns the first value in the specified partition. |
| LAST_VALUE | FUNCTION(val) OVER(PARTITION BY custid ORDER BY orderdate ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) as val; returns the last value in the specified partition. |
| elements required for a table to be made temporal | Primary key constraint, begin and end columns (datetime2), table option SYSTEM_VERSIONING is set to ON, a linked history table. |
| FOR XML | Use after ORDER BY clause, and in conjunction with XMLNAMESPACES, to produce query results in XML. |
| OPENXML | Allows you to convert XML to tables. |
| XQuery | Allows you to query XML and return XML. Uses the following FLWOR expressions: for, let, where, order by, return. |
| FOR JSON AUTO | Formats JSON output automatically, based on the order of the columns in the select list and the order of the tables in the FROM list. |
| FOR JSON PATH | Allows you to format JSON output with more control, giving the ability to nest results. |
| OPENJSON | Allows you to convert JSON to tables. |
| JSON_VALUE | Allows you to extract a scalar value from JSON text. |
| JSON_QUERY | Allows you to extract an object or array from JSON text. |
| datatype for preserving whitespace and element tags | nvarchar(max) |
| datatype for storing canonical xml | xml |
| REPEATABLE READ | Ensures that a stored procedure cannot read modified data that is not yet committed. It ensures that other transactions cannot modify data that is being processed by the stored procedure. |
| SERIALIZABLE | Locks a range of records to ensure that data cannot be modified until the transaction is complete. |