EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials MySQL Tutorial MySQL String Functions
Secondary Sidebar
MySQL Tutorial
  • Functions
    • MySQL Function
    • MySQL Aggregate Function
    • MySQL String functions
    • MySQL Date Functions
    • MySQL Window Functions
    • MySQL Math Functions
    • MySQL Boolean
    • Cursor in MySQL
    • Condition in MySQL
    • MySQL BETWEEN
    • Insert in MySQL
    • MySQL IFNULL()
    • MySQL TIMESTAMPDIFF()
    • MySQL COALESCE()
    • MySQL count()
    • MIN() in MySQL
    • MySQL Numeric
    • MySQL field()
    • MySQL FIND_IN_SET()
    • MySQL avg()
    • MySQL MAX() Function
    • MySQL BIN()
    • MySQL Concat
    • MySQL DECODE()
    • MySQL REGEXP_REPLACE()
    • MySQL Asynchronous
    • MySQL innodb_buffer_pool_size
    • MySQL key_buffer_size
    • MySQL TRUNCATE()
    • MySQL ROW_NUMBER()
    • NOT in MySQL
    • MySQL IN Operator
    • LIKE in MySQL
    • ANY in MySQL
    • MySQL NOT IN
    • MySQL CHECK Constraint
    • MySQL DISTINCT
    • MySQL ALL
    • MySQL Union
    • MySQL UNION ALL
    • MySQL EXISTS
    • MySQL ON DELETE CASCADE
    • MySQL REGEXP
    • MySQL Index
    • MySQL Add Index
    • MySQL REINDEX
    • MySQL UNIQUE INDEX
    • MySQL Clustered Index
    • MySQL? InnoDB Cluster
    • Table in MySQL
    • ALTER TABLE MySQL
    • MySQL Temporary Table
    • MySQL Clone Table
    • MySQL Repair Table
    • MySQL Lock Table
    • MySQL Optimize Table
    • TRUNCATE TABLE MySQL
    • MySQL Table Dump
    • MySQL Update Set
    • MySQL ALTER TABLE Add Column
    • MySQL RANK()
    • MySQL CTE
    • MySQL LAG()
    • MySQL GROUP_CONCAT()
    • MySQL EXTRACT()
    • MySQL REPLACE
    • MySQL AUTO_INCREMENT
    • MySQL SYSDATE()
    • MySQL NULLIF()
    • MySQL Substring
    • MySQL SUBSTRING_INDEX()
    • MySQL LOWERCASE
    • MySQL Row
    • MySQL NOW
    • MySQL CEIL
    • MySQL Alias
    • MySQL Trigger
    • MySQL SHOW Triggers
    • MySQL UPDATE Trigger
    • MySQL DELETE Trigger
    • MySQL AFTER UPDATE Trigger
    • MySQL Stored Procedure
    • ROLLUP in MySQL
    • MySQL? INSTR()
    • MySQL Subquery
    • MySQL Timestamp
    • MySQL? Hour()
    • MySQL MOD()
    • MySQL DATE_FORMAT()
    • ALTER Column in MySQL
    • MySQL Rename Column
    • MySQL Interval
    • MySQL CURDATE
    • MySQL BIT
    • MySQL Binlog
    • MySQL Average
    • MySQL TEXT
    • MySQL SHOW
    • MySQL Offset
    • MySQL Timezone
    • mysql_real_escape_string
    • MySQL Datetime
    • MySQL DATE_SUB()
    • MySQL FULLTEXT
    • MySQL DATE_ADD()
    • MySQL sum()
    • MySQL Merge
    • MySQL BigInt
    • MySQL ROUND
    • MySQL VARCHAR
    • MySQL Decimal
    • MySQL Limit
    • MySQL today()
    • MySQL WEEKDAY
    • MySQL Split
    • MySQL Create Function
    • MySQL BLOB
    • MySQL encode()
    • MySQL Primary Key
    • MySQL Foreign Key
    • Unique Key in MySQL
    • MySQL Drop Foreign Key
    • MySQL DROP TRIGGER
    • MYSQL Database
    • Delete Database MySQL
    • MySQL Root
    • MySQL Root Password
    • MySQL Client
    • MySQL Users
    • MySQL?User Permissions
    • MySQL add user
    • MySQL List User
    • MySQL Show Users
    • MySQL User Password
    • MySQL?Cardinality
    • MySQL Workbench
    • MySQL Backup
    • MySQL REVOKE
    • MySQL Dump
    • MySQL Cluster
    • MySQL Partitioning
    • MySQL Full Text Search
    • MySQL Admin Tool
    • MySQL Export Database
    • MySQL Export to CSV
  • Basic
    • MySQL floor
    • MySQL DESCRIBE table
    • MySQL encryption
    • Introduction to MySQL
    • Is SQL Server a Database?
    • What is MySQL
    • Is MySQL Programming Language
    • MySQL Server
    • MySQL Community Server
    • How To Install MySQL
    • MySQL Versions
    • MySQL OpenSource
    • MySQL GUI Tools
    • MySQL Grant
    • MySQL Error 1064
    • MySQL Drop Database
    • MySQL not equal
    • MySQL SELECT INTO Variable
    • MySQL Commands
    • MySQL Operators
    • What is MySQL Schema
    • Wildcards in MySQL
    • MySQL Constraints
    • MySQL Administration
    • MySQL Data Type
    • MYSQL COMMIT
    • MySQL FORMAT
    • Timestamp to Date in MySQL
    • MySQL DATEDIFF
    • MySQL?Incremental Backup
    • MySQL JSON Data Type
    • MySQL ENUM
    • MySQL Default Port
    • Cheat Sheet MySQL
  • Queries
    • MySQL Queries
    • MySQL Query Commands
    • SELECT in MySQL
    • MySQL INSERT IGNORE
    • MySQL having
    • ORDER BY in MySQL
    • MySQL Cheat Sheet
    • MySQL ORDER BY Random
    • MySQL ORDER BY DESC
    • MySQL GROUP BY
    • MySQL GROUP BY Count
    • MySQL GROUP BY month
    • MySQL WHERE Clause
    • MySQL WITH
    • MySQL FETCH
    • MySQL DDL
    • MySQL DML
    • MySQL WHERE IN Array
    • MySQL Fetch Array
    • MySQL ISNULL
    • MySQL Index Types
    • Mysql? Export Schema
    • Amazon RDS for MySQL
    • MySQL greatest
  • Database
    • What is Data Modeling
    • What is Data Processing
    • DBMS Architecture
    • DBMS Keys
    • Careers in Database Administration
    • What is MySQL Database
    • MySQL Relational Database
    • How to Connect Database to MySQL
    • MySQL Database Repair
    • RDBMS Interview Questions
    • DBMS Interview Questions
  • Joins
    • Joins in MySQL
    • MySQL Outer Join
    • Left Outer Join in MySQL
    • MySQL Self Join
    • Natural Join in MySQL
    • MySQL DELETE JOIN
    • MySQL Update Join
    • MySQL Cross Join
  • Advanced
    • MySQL Formatter
    • MySQL TINYINT
    • MySQL Grant All Privileges
    • MySQL DROP TABLE
    • MySQL rename database
    • MySQL Flush Privileges
    • MySQL super Privilege
    • MySQL Character Set
    • MySQL Log File
    • MySQL Flush Log
    • Grant Privileges MySQL
    • MySQL WHILE LOOP
    • IF Statement in MySQL
    • MySQL CASE Statement
    • MySQL IF Function
    • MySQL IF EXISTS
    • MySQL UUID
    • Views in MySQL
    • MySQL Replication
    • MySQL Partition
    • Toad for MySQL
    • Navicat for MySQL
    • MySQL AES_Encrypt
    • MySQL Performance Tuning
    • MySQL Transaction
    • MySQL? sort_buffer_size
    • MySQL? Sync
    • MySQL? Query Cache
    • MySQL Collation
    • MySQL ODBC Driver
    • MySQL Partitioning
    • MySQL InnoDB
    • MySQL Float vs Decimal
    • MySQL Union vs Union All
  • Interview Questions
    • MySQL Interview Questions

Related Courses

MS SQL Certification Courses

Oracle Certification Courses

PL/SQL Certification Courses

MySQL String Functions

By Priya PedamkarPriya Pedamkar

MySQL String functions

Introduction to MySQL String Functions

MySQL has a number of pre-defined set of string functions, which can be applied on string characters in order to perform several operations in the SQL programming scenarios. Few of the commonly used operations are RIGHT used to fetch the number of characters in the rightmost part of the string, CONCAT used for string concatenation, SPACE used to get return value for number of space characters in a string, INSERT used to insert a new string within another string specific to the position with the number of characters to be inserted, etc.

To illustrate various MySQL String functions, we first need to create a database. The following database will be referred to in all the examples:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

MySQL String Functions -1

MySQL String Functions -2

MySQL String Functions

String function is easy to use. Here we will discuss how to use string functions in MySQL programming with the help of examples

1. ASCII(str)

Returns the ASCII value of the leftmost character of the string str.

Select FirstName, ASCII(FirstName) from Person

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (86,112 ratings)

MySQL String Functions -3

2. BIN(N)

Return binary equivalent of N, where N is an Int/BigInt.

Select Phone, BIN(Phone) from Person

MySQL String Functions -4

3. BIT_LENGTH(str)

Returns the length of the string str in bits.

Select FirstName, BIT_LENGTH(FirstName) from Person

MySQL String Functions -5

4. CHAR_LENGTH(str)

Returns the length of the string str in characters.

Select FirstName, CHAR_LENGTH(FirstName) from Person

MySQL String Functions -6

5. CONCAT(str1, str2, …., strn)

Returns a string formed by joining str1 to strn. If any sub-string is NULL, the result is NULL.

Select FirstName, LastName, CONCAT(FirstName, LastName) as DisplayName from Person

MySQL String Functions -7

6. CONCAT_WS(separator, str1, …, strn)

Returns a concatenated string separated by a separator.

Select FirstName, LastName, CONCAT_WS(' ', FirstName, LastName) as DisplayName from Person

MySQL String Functions -8

Select FirstName, LastName, CONCAT_WS(', ', LastName, FirstName) as DisplayName from Person

MySQL String Functions -9

7. FIELD(str, str1, str2, …, strn)

Returns the index position of string str amongst str1 to strn. Returns 0 if not found.

Select FirstName, LastName, FIELD('John', FirstName, LastName) as IsJohn from Person

MySQL String Functions -10

8. FORMAT(x, D)

Formats the number X to ‘#,###,###.##’ for display. D is the number of decimal places. By default, the format is en-US.

Select FORMAT(Phone, 0) as Phone from Person

MySQL String Functions -11

9. HEX(str) / UNHEX(hex_str)

Returns a hexadecimal equivalent of the string str. UNHEX returns the actual string.

Select FirstName, HEX(FirstName) from Person

MySQL String Functions -12

10. INSERT(str, pos, len, newstr)

Replaces the sub-string starting at position pos and of length len in the string str with newstr.

Select FirstName, LastName, INSERT(LastName, 3, 20, FirstName) as LoginID from Person

MySQL String Functions -13

11. INSTR(str, substr) / LOCATE(substr, str) / POSITION(substr IN str)

Returns the position of the first occurrence of substr in str.

Select FirstName, INSTR(FirstName, 'oo'), LOCATE('hn', FirstName), POSITION('al' IN FirstName) from Person

MySQL String Functions -14

12. LCASE() / LOWER() and UCASE() / UPPER()

Converts a string to lower case and upper case.

Select FirstName, LOWER(FirstName) as Lower, UPPER(FirstName) as Upper from Person

MySQL String Functions -15

13. LEFT(str, len) / RIGHT(str, len)

Returns the leftmost and rightmost len characters from the string str.

Select FirstName, LastName, CONCAT(LEFT(LastName, 3), RIGHT(FirstName, 2)) as LoginID from Person

MySQL String Functions -16

14. LENGTH(str) / OCTET_LENGTH(str)

Returns the length of the string str in bytes. This is very much like CHAR_LENGTH function. The difference comes when there are multibyte characters in the string.

Select CHAR_LENGTH('€'), Length('€')

LENGTH

This happens because Euro (€) sign occupies 3 bytes in memory.

15. LPAD(str, len, padstr) / RPAD(str, len, padstr)

Inserts sub-string from position 0 of the string padstr at the beginning and end of the string str until the resultant string is of len characters.

Select FirstName, LastName, LPAD(CONCAT_WS(' ', FirstName, LastName), Char_Length(CONCAT_WS(' ', FirstName, LastName))+Char_Length('Mr. '), 'Mr. ') as DisplayName from Person

LPAD

16. LTRIM(str) / RTRIM(str) / TRIM(str)

Returns the string str after trimming white spaces from left, right or both ends.

Select LTRIM('    abc    ') as L, RTRIM('    abc    ') as R, TRIM('    abc    ') as T

MySQL String Functions -19

17. MID(str, pos, len) / SUBSTRING(str, pos, len)

Returns a substring from string str starting at position pos of length len.

Select FirstName, SUBSTRING(FirstName, 2, 4) as a sub from Person

MID

18. QUOTE(str)

This query quotes and un-quotes the string str. Special characters are escaped.

Select Address, QUOTE(Address) from Person

QUOTE

19. REPLACE(str, from_str, to_str)

Replaces all occurrences of sub-string from_str with sub-string to_str in the string str. It is case-sensitive.

Select Address, REPLACE(Address, 'S', 'ss') from Person

REPLACE

20. REVERSE(str)

Reverses the string str.

Select FirstName, REVERSE(FirstName) from Person

REVERSE

21. SPACE(N)

This one is quite funny. It simply returns a string of N blank spaces. Now I wonder what made them create this function! Anyway, try it out yourself.

22. SUBSTR(str, pos)/SUBSTRING(str, pos)/SUBSTR(str, pos, len)/SUBSTRING(str, pos, len)

Returns a substring from the string str starting from position pos, till the end if no len is specified or for len characters otherwise. Remember, Index starts from 1 in MySQL.

Select FirstName, LastName, SUBSTR(FirstName, 2), SUBSTRING(LastName, 2, 2) from Person

SUBSTR

23. SUBSTRING_INDEX(str, delim, count)

Returns a substring from the string str before or after the count occurrence of the delim character. If the count is positive, sub-string before the occurrence is returned. If the count is negative, sub-string after the occurrence is returned.

Select Address, SUBSTRING_INDEX(Address, '-', 1) as House, SUBSTRING_INDEX(Address, ',', 1) as Street, SUBSTRING_INDEX(Address, ',', -1) as City from Person

SUBSTRING

Conclusion

So, found some of these functions helpful? Did any of this help you solve a use-case you had? I am sure they do. Not just string functions, but MySQL built-in functions are a great way to achieve the results in minimal queries thereby re-using the existing code and leveraging the power of the framework to its full capacity.

Recommended Articles

This has been a guide to MySQL String functions. Here we discussed basic introduction and how to use string function in MySQL programming with the help of examples and code implementation. You may also look at the following articles to learn more –

  1. Different Types of MySQL Operators
  2. How To Install MySQL?
  3. Basic to Advance Commands of MySQL.
  4. Cheat Sheet MySQL
  5. How to Implement Insert Command in MySQL?
Popular Course in this category
SQL Training Program (7 Courses, 8+ Projects)
  7 Online Courses |  8 Hands-on Projects |  73+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

MS SQL Training (16 Courses, 11+ Projects)4.9
Oracle Training (14 Courses, 8+ Projects)4.8
PL SQL Training (4 Courses, 2+ Projects)4.7
2 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more