5 SQL Functions for Manipulating Strings
Source: Google Images

5 SQL Functions for Manipulating Strings

SQL functions used for manipulating strings, commonly called string functions, are among most important SQL’s tools. In this article, we’ll look at five ways you can perform various operations on strings.

There are many SQL functions that let you “edit” string data. As you learn SQL, you’ll see how useful they prove. Some sql trim off unneeded spaces or characters; others tell you how long a string is. These functions give you a lot of opportunities to transform and work with strings, which makes your code more effective. They also make code easier to understand.

In this article, I’ll help you get started by explaining five common string functions in SQL.

1. SQL String Functions: CONCAT

CONCAT(first_char, second_char, ... n_char)


The CONCAT SQL string function combines two or more strings into one string. All entry_char inputs need to be CHAR, VARCHAR, or NCHAR data types.

I’ve written two simple examples that show how useful this command is:

SELECT CONCAT ('LearnSQL is good', ' and great', ' and fantastic!') 

FROM DUAL;

LearnSQL is good and great and fantastic!


As you can see, CONCAT has taken the three strings I’ve entered – 1) 'LearnSQL is good'; 2) 'and great'; 3) 'and fantastic!' – and combined them into a new SQL string. This technique is very useful when we want to present database information in a readable way.

Let’s assume we have a table called patient that stores patients’ ID numbers, names, admission dates, and illnesses. We want to display each patient’s data in the most understandable way. The best option is to create a sentence, as shown below:

SELECT CONCAT(name, ' was admitted to St. Ann's Hospital on ', date, ' with ', illness) 

FROM patient

WHERE patient_id = 447;


John Doe was admitted to St. Ann’s Hospital on 21-11-2016 with flu.


2. SQL String Functions: REPLACE

REPLACE(entry_char, string_searching, string_replace)

SQL string. It returns an entry_char where the value of string_searching is replaced with string_replace. If the string_replace value is null, then every value matching string_searching is deleted from the entry string.Let’s see two examples of REPLACE at work. Suppose we want to update part of a record:

SELECT REPLACE ('LearnSQL is good!', 'good', 'great!') 

FROM DUAL;

LearnSQL is great!

As you can see, REPLACE has changed the good value in LearnSQL is good!” to “great. The record now reads LearnSQL is great!

Now let’s try a more practical demonstration of manipulating strings with this function. Let’s say you have a table called registry that stores employee names. An employee named Rajat (the only Rajat in the table, for the purposes of this illustration) got married and changed his last name. The REPLACE function allows us to update her record very easily:

UPDATE registry

SET name = REPLACE(name, 'Punia', 'Singh')

WHERE name LIKE 'Rajat%'


Rajat Punia is now officially Rajat Singh, thanks to the REPLACE function.

3. SQL String Functions: SUBSTR

There are even more SQL functions used for manipulating strings. 

SUBSTR(char, position, length)


SUBSTR takes a portion (or substring) from a SQL string and returns it. Char defines what we want to use as the source of the substring; in the following example, it’s LearnSQL. The position is where the substring starts; 6 characters from the beginning, in this case. Finally, length defines how long the substring should be. Putting it all togetherwe get:

SELECT SUBSTR('LearnSQL',6,3) 

FROM DUAL;


SQL

This SQL string function is widely used in removing characters from a large string and for adding characters into a string.

4. SQL String Functions: ASCII and CHR

ASCII(single_character)


CHR(character_code)

ASCII and CHR are two totally opposite SQL functions. ASCII looks at a single character and returns its ASCII number code (e.g. “V” is 86). If a string of characters is entered, this SQL string function will return a value for the first character and ignore the rest. CHR, on the other hand, takes the ASCII code number and returns the appropriate character. Give it an 86, and it will return a “V”.

Let’s imagine that you need to find everyone whose last name starts with an A. You’ve decided to use the ASCII code number to do this. First of all, let’s find the ASCII equivalent of “A”.

SELECT ASCII('A')

FROM DUAL;


65


So 65 is our number. Now we can find all the needed records:

SELECT *

FROM Team

WHERE SUBSTR(second_name, 1, 1) = CHR(65);


first_name    second_name     age

---------    ------------     ------

Raja          Singh           26

Animesh       kumar           25


Diksha        Chaudhary       30


5. SQL String Functions: TRIM

TRIM( [ [ LEADING | TRAILING | BOTH ] character FROM ] edit_char )

TRIM’s main job is removing all specified characters from the beginning part (leading), ending part (trailing), or both parts (both) of a specific string (edit_char).

This instruction has a lot of parameters. First, you must choose the part of the string where you want to cut characters. If you don’t, TRIM will remove the defined characters from both the beginning and end of edit_char. Next, you must tell it what characters to remove. If this parameter is omitted, the function will remove only space characters. Finally, you define the string.

Let’s see how it looks in practice:

Remove leading and trailing spaces:

SELECT TRIM('    SQL2017    ')

FROM DUAL;


“SQL2017”


SELECT TRIM ('' FROM  '   SQL2017   ')

FROM DUAL;


"SQL2017"

Remove trailing ‘2017’ from the string:

SELECT TRIM (TRAILING '2017' FROM 'SQL2017')

FROM DUAL;


"SQL"

Remove both leading and trailing ‘20’ from the string:

SELECT TRIM (BOTH '20' FROM '2017LearnSQL20')

FROM DUAL;


"17LearnSQL"


Unfortunately, TRIM does not have the same syntax across databases. In SQL Server, TRIM takes only the edit_char parameter and deletes all spaces from the both ends of the string. LTRIM deletes leading spaces and RTRIM deletes trailing spaces.

Thank you!

To view or add a comment, sign in

More articles by Raja S.

  • SQL - Sub Queries

    A Subquery or Inner query or a Nested query is a query within another SQL query and embedded within the WHERE clause. A…

    1 Comment
  • SQL Aggregate functions with example

    In this tutorial, you will learn about the SQL Server aggregate functions and how to use them to calculate aggregates…

    1 Comment
  • Star Schema vs. Snowflake Schema

    The star schema and the snowflake schema are ways to organize data marts or entire data warehouses using relational…

    1 Comment
  • What elements of SQL do data scientists need to know?

    Sharing a few elements of SQL which are important to know for a Data Scientist. Providing you with a brief introduction…

  • Top 10 Python Libraries for Data Science

    People in Data Science definitely know about the Python libraries that can be used in Data Science but when asked in an…

    5 Comments
  • Four Reasons You Must Learn SQL in Data Science

    Data science is hot right now. What if you could predict the next market crash? Or contain the spread of Covid-19? Or…

    2 Comments
  • Why use Python for Machine Learning

    Machine learning is one the of the hottest topic in the tech world everyone is excited about learning more about it…

  • Machine Learning-Logistic Regression

    INTRODUCTION Logistic regression is a classification algorithm used to assign observations to a discrete set of…

Others also viewed

Explore content categories