RIGHT function
The function RIGHT that complements LEFT returns a specified number of characters from the right of a character expression:
RIGHT(character_expression , integer_expression)
Here is, for example, the way to determine the names of the ships that start and end with the same letter:
SELECT name
FROM Ships
WHERE LEFT(name, 1) = RIGHT(name, 1)
[[ column ]] |
---|
NULL [[ value ]] |
The thing that we got an empty resulting set means that such ships are absent in our database. Let’s take a combination - a class and a name of a ship.
The combining of two string values into one is called concatenation, and in the SQL Server sign “+” is used for this operation ("||" in standard). So,
SELECT *
FROM (SELECT class +' '+ name AS cn
FROM Ships
) x
WHERE LEFT(cn, 1) = RIGHT(cn, 1)
[[ column ]] |
---|
NULL [[ value ]] |
Here we separate by space the class and the name of a ship. Besides, in order not to repeat the whole construction in the function argument, we use a subquery. The result will look like this:
Cn |
---|
Iowa Missouri |
North Carolina Washington |
But what if a string expression will contain only one character? The query will output it. You can easily check it by
SELECT *
FROM (SELECT class +' '+ name AS cn
FROM Ships
UNION ALL
SELECT 'a' AS nc
) x
WHERE LEFT(cn, 1) = RIGHT(cn, 1)
[[ column ]] |
---|
NULL [[ value ]] |
In order to exclude this case, one more useful function LEN can be used.
Suggested exercises: (-7)