CHAPTER 4: Using Built-in Functions and Expressions Flashcards

(242 cards)

1
Q

Q: What operator is used to concatenate strings in T-SQL?

A

A: The + operator is used to concatenate strings.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Q: How can you concatenate columns in a query with a space in between?

A

SELECT FirstName + ‘ ‘ + LastName AS [Full Name] FROM Person.Person;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Q: What happens if you concatenate a string with a NULL using the + operator?

A

A: The result is NULL.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Q: Why is it important to alias concatenated expressions?

A

A: Without an alias, the resulting column header will be “(No column name),” making the results harder to interpret.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Q: What is the purpose of the CONCAT function in T-SQL?

A

A: The CONCAT function concatenates multiple values into a single string and automatically handles NULLs by ignoring them.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Q: How does the CONCAT function handle NULL values?

A

A: NULL values are ignored, and the function concatenates the remaining values.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Q: What is an example of using CONCAT with literal strings?

A

SELECT CONCAT(‘I ‘, ‘love’, ‘ T-SQL’) AS RESULT;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Q: Can the CONCAT function handle nonstring data types?

A

A: Yes, nonstring values are implicitly converted to strings before concatenation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Q: What is an example of using CONCAT with variables?

A

DECLARE @a VARCHAR(30) = ‘My birthday is on ‘;
DECLARE @b DATE = ‘1980-08-25’;
SELECT CONCAT(@a, @b) AS RESULT;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Q: How can CONCAT be used with table data?

A

SELECT CONCAT(AddressLine1, PostalCode) AS Address FROM Person.Address;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Q: How does this query handle NULLs?

SELECT CONCAT(‘This’, NULL, ‘ works’) AS RESULT;

A

A: The result is “This works” because NULL values are ignored.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Q: Why might you prefer CONCAT over the + operator for string concatenation?

A

A: CONCAT handles NULL values gracefully by ignoring them, whereas + returns NULL if any value is NULL.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Q: What is the purpose of the ISNULL function in T-SQL?

A

A: The ISNULL function replaces NULL values with a specified replacement value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Q: How does the COALESCE function differ from ISNULL?

A

A: COALESCE accepts multiple arguments and returns the first non-NULL value, while ISNULL accepts only two arguments.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Q: Provide an example of using ISNULL to handle NULLs in a concatenation.

A

SELECT FirstName + ISNULL(‘ ‘ + MiddleName, ‘’) + ‘ ‘ + LastName AS [Full Name]
FROM Person.Person;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Q: Why might developers prefer COALESCE over ISNULL?

A

A: COALESCE is ANSI-compliant, more versatile, and can handle multiple arguments, whereas ISNULL is a proprietary SQL Server feature.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Q: How does COALESCE work with NULL values in concatenation?

A

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;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Q: What issue can occur when using ISNULL incorrectly in concatenation?

A

A: Extra spaces may appear if the space is not included within the ISNULL function.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Q: What must you do to concatenate nonstring values to strings in T-SQL?

A

A: Convert the nonstring values to strings using CAST, CONVERT, or CONCAT.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Q: What happens if you attempt to concatenate a string and a number without converting the number?

A

A: An error will occur because integers have higher precedence than strings.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Q: What is the syntax for using the CAST function to convert a value to a string?

A

CAST(<value> AS <new>)</new></value>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Q: What is the syntax for using the CONVERT function to convert a value to a string?

A

CONVERT(<new>, <value>)</value></new>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Q: Provide an example of using CAST to convert and concatenate a value.

A

SELECT CAST(BusinessEntityID AS NVARCHAR) + ‘: ‘ + LastName + ‘, ‘ + FirstName AS ID_Name
FROM Person.Person;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Q: Provide an example of using CONVERT to convert and concatenate a value.

A

SELECT CONVERT(NVARCHAR(10), BusinessEntityID) + ‘: ‘ + LastName + ‘, ‘ + FirstName AS ID_Name
FROM Person.Person;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
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
25
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).
26
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.
27
Q: What operator is used for addition in T-SQL?
A: The + operator.
28
Q: What operator is used for subtraction in T-SQL?
A: The - (hyphen) operator.
29
Q: What operator is used for multiplication in T-SQL?
A: The * operator.
30
Q: What operator is used for division in T-SQL?
A: The / operator.
31
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.
32
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.
33
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.
34
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.
34
Q: Write a query to multiply a column by 10.
SELECT OrderQty, OrderQty * 10 AS Times10 FROM Sales.SalesOrderDetail;
35
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;
36
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.
37
Q: Provide an example of using ISNULL with mathematical operators.
SELECT DiscountPct * ISNULL(MaxQty, 1000) AS MaxDiscount FROM Sales.SpecialOffer;
38
Q: What is the default precedence for multiplication, division, and subtraction in T-SQL?
A: Multiplication (*) and division (/) have higher precedence than subtraction (-).
39
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.
40
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;
41
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.
42
43
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.
44
Q: What does the RTRIM function do in T-SQL?
A: Removes spaces from the right side of a string.
45
Q: What does the LTRIM function do in T-SQL?
A: Removes spaces from the left side of a string.
46
Q: What does the TRIM function do in T-SQL?
A: Removes spaces from both sides of a string.
47
Q: What is the syntax for using the RTRIM, LTRIM, and TRIM functions?
RTRIM() LTRIM() TRIM()
47
Q: Provide an example of using RTRIM to remove trailing spaces.
SELECT RTRIM('Hello ') AS TrimmedString;
47
Q: What does the LEFT function do in T-SQL?
A: Returns a specified number of characters from the left side of a string.
47
Q: What does the RIGHT function do in T-SQL?
A: Returns a specified number of characters from the right side of a string.
47
Q: What is the syntax for the LEFT and RIGHT functions?
LEFT(, ) RIGHT(, )
48
Q: Provide an example of using LEFT to extract the first 5 characters of a string.
SELECT LEFT('AdventureWorks', 5) AS FirstFive;
49
Q: Provide an example of using RIGHT to extract the last 4 characters of a string.
SELECT RIGHT('AdventureWorks', 4) AS LastFour;
49
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.
49
Q: How can TRIM be used to clean up string data in a query?
SELECT TRIM(' Hello World ') AS CleanedString;
50
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;
51
Q: What does the LEN function return in T-SQL?
A: The number of characters in a string.
52
Q: What does the DATALENGTH function return in T-SQL?
A: The number of bytes used by a data type or expression.
53
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.
54
Q: What is the syntax for the LEN and DATALENGTH functions?
LEN() DATALENGTH()
55
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;
56
Q: What does the CHARINDEX function do in T-SQL?
A: It finds the numeric starting position of a search string within another string.
57
Q: What is the syntax for the CHARINDEX function?
CHARINDEX(, [, ])
58
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.
59
Q: How can you use CHARINDEX to find the first occurrence of the letter e in a string?
CHARINDEX('e', LastName)
60
Q: Provide an example of using CHARINDEX to skip the first three characters in a search.
CHARINDEX('e', LastName, 4)
61
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.
62
Q: Can CHARINDEX search for substrings longer than one character?
A: Yes, you can search for substrings like 'be' or 'test'.
63
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;
64
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;
65
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.
66
Q: What is the syntax for the SUBSTRING function?
SUBSTRING(, , )
67
Q: What happens if the start location in SUBSTRING is beyond the end of the string?
A: An empty string is returned.
68
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;
69
Q: What does the CHOOSE function do in T-SQL?
A: It selects a value from a list based on an index.
70
Q: What is the syntax for the CHOOSE function?
CHOOSE(, , , ..., )
71
Q: Provide an example of using CHOOSE to select a value from an array.
SELECT CHOOSE(3, 'a', 'b', 'c', 'd') AS Result;
72
Q: What does the REVERSE function do in T-SQL?
A: It returns a string with its characters in reverse order.
73
Q: Provide an example of using REVERSE to reverse a string.
SELECT REVERSE('Hello, World!') AS ReversedString;
74
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.
75
Q: Provide an example of using UPPER and LOWER on a column.
SELECT UPPER(LastName) AS "UPPER", LOWER(LastName) AS "LOWER" FROM Person.Person;
76
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.
77
Q: What does the REPLACE function do in T-SQL?
A: It replaces all occurrences of a specified string within another string.
78
Q: What is the syntax for the REPLACE function?
REPLACE(, , )
79
Q: Provide an example of using REPLACE to substitute one string for another.
SELECT REPLACE('AdventureWorks', 'Works', 'Shop') AS ReplacedString;
80
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";
81
Q: Can REPLACE use column values as the replacement string?
SELECT REPLACE(LastName, 'a', MiddleName) AS "Replace with MiddleName";
82
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.
83
Q: What is the syntax for using STRING_SPLIT?
STRING_SPLIT(, )
84
Q: Provide an example of splitting a comma-separated string into rows.
SELECT value FROM STRING_SPLIT('1,2,3,4,5', ',');
85
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', ' ');
85
Q: What is the syntax for using STRING_AGG?
STRING_AGG(, )
86
Q: What does the STRING_AGG function do in T-SQL?
A: It concatenates values from multiple rows into a single delimited string.
87
87
87
87
87
88
89
Q: Provide an example of concatenating values into a comma-separated string using STRING_AGG.
SELECT STRING_AGG(Name, ', ') AS List FROM Production.ProductCategory;
89
Q: What does it mean to nest functions in T-SQL?
A: Using the result of one function as a parameter for another function.
89
Q: What is an example of nesting the RTRIM and LTRIM functions?
SELECT LTRIM(RTRIM(' test ')) AS TrimmedString;
89
Q: Provide an example of extracting the domain from an email address using nested functions.
SELECT EmailAddress, SUBSTRING(EmailAddress, CHARINDEX('@', EmailAddress) + 1, 50) AS DOMAIN FROM Production.ProductReview;
89
Q: Provide an example of finding a file name from a file path using nested functions.
SELECT physical_name, RIGHT(physical_name, CHARINDEX('\', REVERSE(physical_name)) - 1) AS FileName FROM sys.database_files;
89
Q: What is a good strategy for writing and debugging nested functions?
A: Work from the inside out, testing each inner function before integrating it into the outer functions.
90
Q: Where is the STRING_SPLIT function typically used in a query?
A: In the FROM clause, as it returns a table.
91
Q: How does STRING_AGG handle rows in a query?
A: It aggregates all rows into a single string, separated by the specified delimiter.
92
Q: Why is nesting functions useful in T-SQL?
A: It allows complex data manipulations by combining multiple function operations into a single query.
93
Q: What do the GETDATE and SYSDATETIME functions return in T-SQL?
A: They return the current date and time of the server.
94
Q: How do GETDATE and SYSDATETIME differ in precision?
A: GETDATE returns three decimal places for seconds, while SYSDATETIME returns seven decimal places.
95
Q: What does the DATEADD function do in T-SQL?
A: It adds a specified number of time units to a date.
95
Q: Are GETDATE and SYSDATETIME deterministic functions?
A: No, they are nondeterministic, returning different values each time they are called.
95
Q: What is the syntax for using DATEADD?
DATEADD(, , )
96
Q: How can you subtract time using DATEADD?
A: Use a negative number as the second parameter, e.g., DATEADD(day, -1, OrderDate).
97
Q: Provide an example of using DATEADD to add one month to a date.
SELECT DATEADD(month, 1, '2009-01-29') AS FebDate;
98
Q: What does the DATEDIFF function do in T-SQL?
A: It calculates the difference between two dates in a specified unit of time.
99
Q: What is the syntax for using DATEDIFF?
DATEDIFF(, , )
100
Q: Provide an example of calculating the number of days between two dates.
SELECT DATEDIFF(day, '2008-12-31', '2009-01-01') AS DayDiff;
101
Q: What does the DATENAME function return in T-SQL?
A: It returns the name of a specified date part (e.g., month or weekday) as a string.
102
Q: What does the DATEPART function return in T-SQL?
A: It returns the value of a specified date part as an integer.
103
Q: What is the syntax for DATENAME and DATEPART?
DATENAME(, ) DATEPART(, )
104
Q: Provide an example of using DATENAME to get the name of the month from a date.
SELECT DATENAME(month, OrderDate) AS OrderMonth FROM Sales.SalesOrderHeader;
105
Q: What happens when adding one month to January 29, 2009, using DATEADD?
A: It returns February 28, 2009, since February 29 doesn’t exist that year.
105
Q: Provide an example of using DATEPART to get the day of the month from a date.
SELECT DATEPART(day, OrderDate) AS OrderDay FROM Sales.SalesOrderHeader;
105
Q: Are the results of DATEDIFF rounded?
A: No, DATEDIFF returns the integer difference without decimal points.
105
Q: What do the DAY, MONTH, and YEAR functions do in T-SQL?
A: They extract the day, month, or year from a date value.
105
Q: What does the CONVERT function do in T-SQL?
A: It converts a value from one data type to another and can format dates using an optional style parameter.
105
Q: Provide an example of using the DAY, MONTH, and YEAR functions.
SELECT YEAR(OrderDate) AS OrderYear, MONTH(OrderDate) AS OrderMonth, DAY(OrderDate) AS OrderDay FROM Sales.SalesOrderHeader;
105
Q: What is the syntax for the DAY, MONTH, and YEAR functions?
DAY() MONTH() YEAR()
106
Q: What is the syntax for the CONVERT function?
CONVERT(, ,