CHAPTER 4: Using Built-in Functions and Expressions Flashcards
Q: What operator is used to concatenate strings in T-SQL?
A: The + operator is used to concatenate strings.
Q: How can you concatenate columns in a query with a space in between?
SELECT FirstName + ‘ ‘ + LastName AS [Full Name] FROM Person.Person;
Q: What happens if you concatenate a string with a NULL using the + operator?
A: The result is NULL.
Q: Why is it important to alias concatenated expressions?
A: Without an alias, the resulting column header will be “(No column name),” making the results harder to interpret.
Q: What is the purpose of the CONCAT function in T-SQL?
A: The CONCAT function concatenates multiple values into a single string and automatically handles NULLs by ignoring them.
Q: How does the CONCAT function handle NULL values?
A: NULL values are ignored, and the function concatenates the remaining values.
Q: What is an example of using CONCAT with literal strings?
SELECT CONCAT(‘I ‘, ‘love’, ‘ T-SQL’) AS RESULT;
Q: Can the CONCAT function handle nonstring data types?
A: Yes, nonstring values are implicitly converted to strings before concatenation.
Q: What is an example of using CONCAT with variables?
DECLARE @a VARCHAR(30) = ‘My birthday is on ‘;
DECLARE @b DATE = ‘1980-08-25’;
SELECT CONCAT(@a, @b) AS RESULT;
Q: How can CONCAT be used with table data?
SELECT CONCAT(AddressLine1, PostalCode) AS Address FROM Person.Address;
Q: How does this query handle NULLs?
SELECT CONCAT(‘This’, NULL, ‘ works’) AS RESULT;
A: The result is “This works” because NULL values are ignored.
Q: Why might you prefer CONCAT over the + operator for string concatenation?
A: CONCAT handles NULL values gracefully by ignoring them, whereas + returns NULL if any value is NULL.
Q: What is the purpose of the ISNULL function in T-SQL?
A: The ISNULL function replaces NULL values with a specified replacement value.
Q: How does the COALESCE function differ from ISNULL?
A: COALESCE accepts multiple arguments and returns the first non-NULL value, while ISNULL accepts only two arguments.
Q: Provide an example of using ISNULL to handle NULLs in a concatenation.
SELECT FirstName + ISNULL(‘ ‘ + MiddleName, ‘’) + ‘ ‘ + LastName AS [Full Name]
FROM Person.Person;
Q: Why might developers prefer COALESCE over ISNULL?
A: COALESCE is ANSI-compliant, more versatile, and can handle multiple arguments, whereas ISNULL is a proprietary SQL Server feature.
Q: How does COALESCE work with NULL values in concatenation?
A: It skips NULL values and uses the first non-NULL value, e.g.:
SELECT FirstName + COALESCE(‘ ‘ + MiddleName, ‘’) + ‘ ‘ + LastName AS [Full Name]
FROM Person.Person;
Q: What issue can occur when using ISNULL incorrectly in concatenation?
A: Extra spaces may appear if the space is not included within the ISNULL function.
Q: What must you do to concatenate nonstring values to strings in T-SQL?
A: Convert the nonstring values to strings using CAST, CONVERT, or CONCAT.
Q: What happens if you attempt to concatenate a string and a number without converting the number?
A: An error will occur because integers have higher precedence than strings.
Q: What is the syntax for using the CAST function to convert a value to a string?
CAST(<value> AS <new>)</new></value>
Q: What is the syntax for using the CONVERT function to convert a value to a string?
CONVERT(<new>, <value>)</value></new>
Q: Provide an example of using CAST to convert and concatenate a value.
SELECT CAST(BusinessEntityID AS NVARCHAR) + ‘: ‘ + LastName + ‘, ‘ + FirstName AS ID_Name
FROM Person.Person;
Q: Provide an example of using CONVERT to convert and concatenate a value.
SELECT CONVERT(NVARCHAR(10), BusinessEntityID) + ‘: ‘ + LastName + ‘, ‘ + FirstName AS ID_Name
FROM Person.Person;
Q: What is the difference between appending and adding a numeric value in concatenation?
A: Appending requires converting the number to a string, while adding combines the numeric values:
CAST(BusinessEntityID AS NVARCHAR(10)) + ‘1’; – Appends “1”
BusinessEntityID + 1; – Adds 1
Q: Why should you always specify the length when using CAST or CONVERT?
A: To ensure the correct size for the output string, as the default may not meet requirements (e.g., 30 for NVARCHAR or 1 for variables).
Q: When should you use CONCAT instead of CAST or CONVERT?
A: Use CONCAT when concatenating multiple values because it automatically handles NULLs and converts data types to strings.
Q: What operator is used for addition in T-SQL?
A: The + operator.
Q: What operator is used for subtraction in T-SQL?
A: The - (hyphen) operator.
Q: What operator is used for multiplication in T-SQL?
A: The * operator.
Q: What operator is used for division in T-SQL?
A: The / operator.
Q: What is the purpose of the modulo (%) operator in T-SQL?
A: It returns the remainder of a division operation. For example, 5 % 2 returns 1.
Q: How can the modulo operator determine if a number is odd or even?
Use % 2:
If the result is 1, the number is odd.
If the result is 0, the number is even.
Q: What is the result of 10 / 3 in T-SQL if both operands are integers?
A: The result is 3 because integer division truncates the decimal part.
Q: How can you perform division in T-SQL to return a decimal value?
A: Use at least one operand as a decimal value, e.g., 10.0 / 3 returns 3.333.
Q: Write a query to multiply a column by 10.
SELECT OrderQty, OrderQty * 10 AS Times10
FROM Sales.SalesOrderDetail;
Q: How do you calculate a discounted total in T-SQL?
Use a formula like:
SELECT OrderQty * UnitPrice * (1.0 - UnitPriceDiscount) AS Calculated
FROM Sales.SalesOrderDetail;
Q: What is the purpose of parentheses in mathematical expressions in T-SQL?
A: Parentheses enforce the intended order of operations, overriding default operator precedence.
Q: Provide an example of using ISNULL with mathematical operators.
SELECT DiscountPct * ISNULL(MaxQty, 1000) AS MaxDiscount
FROM Sales.SpecialOffer;
Q: What is the default precedence for multiplication, division, and subtraction in T-SQL?
A: Multiplication (*) and division (/) have higher precedence than subtraction (-).
Q: How do parentheses affect the order of operations in T-SQL?
A: They change the order to ensure specific parts of the expression are calculated first.
Q: Write a query to calculate the maximum discount with a fallback for NULL values.
SELECT SpecialOfferID, MaxQty, DiscountPct,
DiscountPct * ISNULL(MaxQty, 1000) AS MaxDiscount
FROM Sales.SpecialOffer;
Q: What happens when performing an operation on two different data types in T-SQL?
A: The result will be of the data type with the highest precedence, if conversion is possible.
Q: Why does the expression 1 + ‘a’ fail in T-SQL?
A: A character (‘a’) cannot be converted to a numeric value, leading to a data type mismatch error.
Q: What does the RTRIM function do in T-SQL?
A: Removes spaces from the right side of a string.
Q: What does the LTRIM function do in T-SQL?
A: Removes spaces from the left side of a string.
Q: What does the TRIM function do in T-SQL?
A: Removes spaces from both sides of a string.
Q: What is the syntax for using the RTRIM, LTRIM, and TRIM functions?
RTRIM(<string>)
LTRIM(<string>)
TRIM(<string>)</string></string></string>
Q: Provide an example of using RTRIM to remove trailing spaces.
SELECT RTRIM(‘Hello ‘) AS TrimmedString;
Q: What does the LEFT function do in T-SQL?
A: Returns a specified number of characters from the left side of a string.
Q: What does the RIGHT function do in T-SQL?
A: Returns a specified number of characters from the right side of a string.
Q: What is the syntax for the LEFT and RIGHT functions?
LEFT(<string>, <number>)
RIGHT(<string>, <number>)</number></string></number></string>
Q: Provide an example of using LEFT to extract the first 5 characters of a string.
SELECT LEFT(‘AdventureWorks’, 5) AS FirstFive;
Q: Provide an example of using RIGHT to extract the last 4 characters of a string.
SELECT RIGHT(‘AdventureWorks’, 4) AS LastFour;
Q: What happens if the number of characters specified in LEFT or RIGHT exceeds the length of the string?
A: The function returns as many characters as possible without causing an error.
Q: How can TRIM be used to clean up string data in a query?
SELECT TRIM(‘ Hello World ‘) AS CleanedString;
Q: Write a query using LEFT and RIGHT functions to parse a name.
SELECT LastName, LEFT(LastName, 3) AS FirstThree, RIGHT(LastName, 3) AS LastThree
FROM Person.Person;
Q: What does the LEN function return in T-SQL?
A: The number of characters in a string.
Q: What does the DATALENGTH function return in T-SQL?
A: The number of bytes used by a data type or expression.
Q: How does DATALENGTH differ from LEN when working with NCHAR or NVARCHAR data types?
A: For NCHAR or NVARCHAR, DATALENGTH returns a value up to two times the LEN value because these data types use up to two bytes per character.
Q: What is the syntax for the LEN and DATALENGTH functions?
LEN(<string>)
DATALENGTH(<any>)</any></string>
Q: Provide an example of using LEN and DATALENGTH in a query.
SELECT LastName, LEN(LastName) AS “Length”, DATALENGTH(LastName) AS “Internal Data Length”
FROM Person.Person;
Q: What does the CHARINDEX function do in T-SQL?
A: It finds the numeric starting position of a search string within another string.
Q: What is the syntax for the CHARINDEX function?
CHARINDEX(<search>, <target>[, <start>])</start></target></search>
Q: What does the optional third parameter in CHARINDEX do?
A: It specifies the starting position to begin the search, ignoring the initial characters up to that position.
Q: How can you use CHARINDEX to find the first occurrence of the letter e in a string?
CHARINDEX(‘e’, LastName)
Q: Provide an example of using CHARINDEX to skip the first three characters in a search.
CHARINDEX(‘e’, LastName, 4)
Q: What happens when searching for a string in a case-sensitive database using CHARINDEX?
A: The function differentiates between cases; for example, searching for be and Be might return different results.
Q: Can CHARINDEX search for substrings longer than one character?
A: Yes, you can search for substrings like ‘be’ or ‘test’.
Q: Write a query to find the first occurrence of the substring be in a column.
SELECT CHARINDEX(‘be’, LastName) AS “Find be”
FROM Person.Person;
Q: Write a query to find the position of e after skipping the first three characters.
SELECT CHARINDEX(‘e’, LastName, 4) AS “Skip 3 Characters”
FROM Person.Person;
Q: What does the SUBSTRING function do in T-SQL?
A: It returns a portion of a string starting at a specified position and for a given length.
Q: What is the syntax for the SUBSTRING function?
SUBSTRING(<string>, <start>, <length>)</length></start></string>
Q: What happens if the start location in SUBSTRING is beyond the end of the string?
A: An empty string is returned.
Q: Provide an example of using SUBSTRING to extract the first 4 characters of a string.
SELECT SUBSTRING(LastName, 1, 4) AS “First 4 Characters” FROM Person.Person;
Q: What does the CHOOSE function do in T-SQL?
A: It selects a value from a list based on an index.
Q: What is the syntax for the CHOOSE function?
CHOOSE(<index>, <val_1>, <val_2>, ..., <val_n>)</val_n></val_2></val_1></index>
Q: Provide an example of using CHOOSE to select a value from an array.
SELECT CHOOSE(3, ‘a’, ‘b’, ‘c’, ‘d’) AS Result;
Q: What does the REVERSE function do in T-SQL?
A: It returns a string with its characters in reverse order.
Q: Provide an example of using REVERSE to reverse a string.
SELECT REVERSE(‘Hello, World!’) AS ReversedString;
Q: What do the UPPER and LOWER functions do in T-SQL?
A: UPPER converts a string to uppercase, and LOWER converts a string to lowercase.
Q: Provide an example of using UPPER and LOWER on a column.
SELECT UPPER(LastName) AS “UPPER”, LOWER(LastName) AS “LOWER” FROM Person.Person;
Q: Are searches in T-SQL case-sensitive by default?
A: No, searches are case-insensitive by default unless the column’s collation specifies case sensitivity.
Q: What does the REPLACE function do in T-SQL?
A: It replaces all occurrences of a specified string within another string.
Q: What is the syntax for the REPLACE function?
REPLACE(<string>, <string>, <replacement>)</replacement></string></string>
Q: Provide an example of using REPLACE to substitute one string for another.
SELECT REPLACE(‘AdventureWorks’, ‘Works’, ‘Shop’) AS ReplacedString;
Q: How can you use REPLACE to remove a string?
A: Replace it with an empty string (‘’), e.g.:
SELECT REPLACE(LastName, ‘a’, ‘’) AS “Remove a”;
Q: Can REPLACE use column values as the replacement string?
SELECT REPLACE(LastName, ‘a’, MiddleName) AS “Replace with MiddleName”;
Q: What does the STRING_SPLIT function do in T-SQL?
A: It splits a string into multiple rows based on a specified delimiter and returns the results as a table.
Q: What is the syntax for using STRING_SPLIT?
STRING_SPLIT(<string>, <delimiter>)</delimiter></string>
Q: Provide an example of splitting a comma-separated string into rows.
SELECT value
FROM STRING_SPLIT(‘1,2,3,4,5’, ‘,’);
Q: Can STRING_SPLIT handle delimiters other than commas?
A: Yes, any character can be used as the delimiter, e.g.,
SELECT value
FROM STRING_SPLIT(‘dog cat bird’, ‘ ‘);
Q: What is the syntax for using STRING_AGG?
STRING_AGG(<expression>, <delimiter>)</delimiter></expression>
Q: What does the STRING_AGG function do in T-SQL?
A: It concatenates values from multiple rows into a single delimited string.