Character functions: CONCAT, SUBSTR, LENGTH, INSTR
Describe the use of the character functions CONCAT, SUBSTR, LENGTH, and INSTR.
Oracle CONCAT, SUBSTR, LENGTH, INSTR with Example
Character Functions: CONCAT, SUBSTR, LENGTH, INSTR
Four commonly used string functions are concatenate, substring, length, and instring.
CONCAT or ||
The concatenation function uses different syntax for different programming languages and software. For Oracle, you have two choices:
Use two vertical bars (||) to connect the two columns you wish to combine. This is by far the most commonly used variation and you can easily concatenate three columns (or expressions or literal values) together by repeating the vertical bars.
Use the CONCAT(a,b) function. This function concatenates the first column with the second column. To add a third column, you must add another CONCAT(a,b) around the first one.
Here is an example (using the course project) of the first, most commonly used, form of concatenation:
SELECT CITY || ', ' || STATE || ' ' || ZIP
The results look like this:
Omaha, NE 98765
Makena, HI 99800
Hollywood, CA 10293
Kihei, HI 39873
This simple function tells you the length (in number of characters) of the data in a column, expression, or literal. In the case of VARCHAR2 datatype columns, the defined length of the column is often higher than the actual data stored in each row's column.
Use the Oracle length function to count the characters.
If a field contains no data (is null) then its length is null.
The instring function returns a number – the number of the position within the field of the character you specify.
The SlideShow below shows the syntax and examples for the INSTR function.
The substring function, which returns part of the column, is written like as follows:
SUBSTR(col1, start, length)
You can combine the substring function with the instring function and create a useful tool.
Here is an example, using the Pet Store schema.
Let us say you want to retrieve only the first sentence from each Pet Log entry. You can use the substring function to return a portion of the data, but the exact length of the sentence varies with each entry. By using the instring function, you can locate the first period (.) found in the data. This is where the sentence ends. Add one to this number, and you can retrieve the complete sentence,
including the period. The diagram below shows the SQL query that does it.
The first command you see in the figure is a SQL*Plus column formatting command. It lets me show you the entire contents of the column in a narrow window. See the module titled "The Oracle SQL*Plus environment" for more information on SQL*Plus commands.
In the next lesson, you will learn use of the character functions UPPER, INITCAP, RTRIM, and SOUNDEX.