Information Technology · Ch 3 — Relational Database Management System - II
MySQL Built-in Functions I — String Functions
MySQL Built-in Functions I — String Functions
MySQL provides many ready-made built-in functions that perform common operations on values. They are grouped by the kind of data they work on: string (text) functions, mathematical (numeric) functions and date-time functions. This section covers the common string functions; the next two cover the others. A string function takes one or more text values and returns a text (or number) result. The most useful ones for a Std-12 student are:
LENGTH(str)— the number of characters in the string.LENGTH('MySQL')is5.UPPER(str)(alsoUCASE) — converts the text to capital letters.UPPER('das')is'DAS'.LOWER(str)(alsoLCASE) — converts to small letters.LOWER('DAS')is'das'.CONCAT(a, b, ...)— joins two or more strings into one.CONCAT('Aarti', ' ', 'Behera')is'Aarti Behera'.SUBSTR(str, start, length)(alsoSUBSTRING/MID) — takes out a piece of the string, beginning at positionstart(counting from 1) forlengthcharacters.SUBSTR('Behera', 1, 3)is'Beh'.LEFT(str, n)andRIGHT(str, n)— the firstnand the lastncharacters.LEFT('MySQL', 2)is'My';RIGHT('MySQL', 3)is'SQL'.TRIM(str)— removes spaces from both ends of the string (LTRIMandRTRIMremove them from the left or right only).INSTR(str, sub)— the position at which the substringsubfirst appears instr(0 if it does not occur).INSTR('Behera', 'he')is2.REPLACE(str, from, to)— replaces every occurrence of one piece of text with another.REPLACE('Sales', 'S', 'T')is'Tales'(the leading S becomes T).
These functions are used inside a SELECT. For example, to show each employee's name in capitals together with the length of the name:
SELECT UPPER(Name) AS NameCaps, LENGTH(Name) AS Letters
FROM Employee;
To display a greeting for each employee by joining fixed text with the name:
A built-in function that operates on text values, such as LENGTH, UPPER, LOWER, CONCAT, SUBSTR, LEFT, RIGHT, TRIM …
CONCAT(a, b, ...) joins several strings into one; SUBSTR(str, start, length) extracts a piece of a string beginning at position 'start' (counted from …