20.07.2013 Views

Beginning SQL

Beginning SQL

Beginning SQL

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 5<br />

The TRIM() Functions<br />

Trimming involves removing unwanted characters from the beginning or end of a string. In most<br />

database implementations, the only character that can be trimmed is the space. However, trimming<br />

spaces is very useful with a character data type column. A variable character column stores only the<br />

number of characters you ask it to store; however, a nonvarying character column pads out the string<br />

with spaces if the string being stored is less than the maximum number of characters the column can<br />

store.<br />

For example, define a new table using the following <strong>SQL</strong>:<br />

CREATE TABLE MyTable<br />

(<br />

first_column char(80)<br />

);<br />

The column first_column can hold up to 80 characters. Now, consider this INSERT statement:<br />

INSERT INTO MyTable (first_column)<br />

VALUES (‘ABC’);<br />

ABC plus seven blank spaces is stored. If you want the results to return only the characters you inserted and<br />

no spaces, you can trim off the spaces with one of the two trim functions: LTRIM() or RTRIM(). LTRIM()<br />

removes any spaces on the left of the characters, while RTRIM() removes any spaces on the right of the<br />

characters. So, if you want to remove the trailing spaces from the example table defined previously, you<br />

would use RTRIM():<br />

SELECT first_column, RTRIM(first_column)<br />

FROM MyTable;<br />

The results for this are as follows:<br />

first_column RTRIM(first_column)<br />

ABC ABC<br />

Notice that first_column is a lot wider than RTRIM(first_column) due to the extra spaces. Note also<br />

that some database systems don’t display the spaces even when they’re there. You no longer need<br />

MyTable, so delete it by running the following code:<br />

DROP TABLE MyTable;<br />

Your next stop on the tour of string functions is the function to find how many characters there are in a<br />

string — finally, a definitive answer to the question, “How long is a piece of string?”<br />

The LENGTH() Function<br />

172<br />

Sometimes it can be very useful to find out how many characters there are in a string. Oracle, IBM, and<br />

My<strong>SQL</strong> use the LENGTH() function to find out how long a string is. MS Access and MS <strong>SQL</strong> Server use<br />

the LEN() function, which does the same thing and works the same way.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!