ByteBoard Notes Notes

Remove spaces from a string with LTRIM(), RTRIM() and TRIM()

Informatics Practices XII · Experiment 33 of 38 · SQL

12-IPSQL queries
Expt. No.33
Page No.66

LTRIM, RTRIM, TRIM

Aim

To remove leading, trailing and both kinds of spaces from a string and check the result with LENGTH().

Concepts used

Queries

SELECT LENGTH('   Byte Board   ');SELECT LENGTH(LTRIM('   Byte Board   ')), LENGTH(RTRIM('   Byte Board   ')), LENGTH(TRIM('   Byte Board   '));SELECT TRIM('   Byte Board   ');

A marked line continues the line above it. In your file, write it on the same line.

Output

mysql> SELECT LENGTH(' Byte Board '); +----------------------------+ | LENGTH(' Byte Board ') | +----------------------------+ | 16 | +----------------------------+ 1 row in set
mysql> SELECT LENGTH(LTRIM(' Byte Board ')), LENGTH(RTRIM(' Byte Board ')), LENGTH(TRIM(' Byte Board ')); +-----------------------------------+-----------------------------------+----------------------------------+ | LENGTH(LTRIM(' Byte Board ')) | LENGTH(RTRIM(' Byte Board ')) | LENGTH(TRIM(' Byte Board ')) | +-----------------------------------+-----------------------------------+----------------------------------+ | 13 | 13 | 10 | +-----------------------------------+-----------------------------------+----------------------------------+ 1 row in set
mysql> SELECT TRIM(' Byte Board '); +--------------------------+ | TRIM(' Byte Board ') | +--------------------------+ | Byte Board | +--------------------------+ 1 row in set

✓ Printed by running this query set, not typed by hand.

Result

The string with 3 spaces on each side has length 16. LTRIM removed the 3 leading spaces (13), RTRIM the 3 trailing ones (13) and TRIM both (10). The space inside "Byte Board" was kept.

Viva voce: what the examiner may ask

01Does TRIM remove the space between two words?

No. It removes spaces only at the start and end.

02Why is LENGTH used to check the result?

Spaces are invisible in the output, so the length shows how many were removed.

03Which function removes only leading spaces?

LTRIM (left trim).

Variations for the lab test

  1. Trim a name that was entered with extra spaces before comparing it.
  2. Display LENGTH(tname) and LENGTH(TRIM(tname)) for the teacher table.
  3. Trim a string with spaces only on the right.
! Common mistake Expecting TRIM to remove all spaces: "Byte Board" keeps its middle space.
Back to the 12-IP index