SQL String Functions are powerful tools that allow us to manipulate, format, and extract specific parts of text data in our database. These functions are essential for tasks like cleaning up data, comparing strings, and combining text fields. Whether we are working with names, addresses, or any form of textual data, mastering SQL string functions is crucial for efficient data handling and analysis.
Common SQL String Functions
String functions are used to perform an operation on input string and return an output string. Below are some of the most commonly used SQL string functions:
1. CONCAT(): Concatenate Strings
The CONCAT() function is used to concatenate (combine) two or more strings into one string. It is useful when we want to merge fields like first and last names into a full name.
Query:
SELECT CONCAT('John', ' ', 'Doe') AS FullName;Output:
John Doe
2. CHAR_LENGTH() / CHARACTER_LENGTH(): Find String Length
The CHAR_LENGTH() or LENGTH() function returns the length of a string in characters. It’s essential for validating or manipulating text data, especially when you need to know how many characters a string contains.
Query:
SELECT CHAR_LENGTH('Hello') AS StringLength;Output:
5
3. UPPER() and LOWER(): Convert Text Case
These functions convert the text to uppercase or lowercase, respectively. They are useful for normalizing the case of text in a database.
Query:
SELECT UPPER('hello') AS UpperCase;
SELECT LOWER('HELLO') AS LowerCase;Output:
HELLO
hello
4. LENGTH(): Length of String in Bytes
LENGTH() returns the length of a string in bytes. This can be useful for working with multi-byte character sets.
Query:
SELECT LENGTH('Hello') AS LengthInBytes;Output:
5
5. REPLACE(): Replace Substring in String
The REPLACE() function replaces occurrences of a substring within a string with another substring. This is useful for cleaning up data, such as replacing invalid characters or formatting errors.
Query:
SELECT REPLACE('Hello World', 'World', 'SQL') AS UpdatedString;Output:
Hello SQL
The SUBSTRING() (or SUBSTR()) function is used to extract a substring from a string, starting from a specified position. It is especially useful when we need to extract a specific part of a string, like extracting the domain from an email address.
Query:
SELECT SUBSTRING('Hello World', 1, 5) AS SubStringExample;Output:
Hello
7. LEFT() and RIGHT(): Extract Substring from Left or Right
The LEFT() and RIGHT() functions allow you to extract a specified number of characters from the left or right side of a string, respectively. It is used for truncating strings for display.
Query:
SELECT LEFT('Hello World', 5) AS LeftString;
SELECT RIGHT('Hello World', 5) AS RightString;Output:
Hello
World
8. INSTR(): Find Position of Substring
The INSTR() function is used to find the position of the first occurrence of a substring within a string. It returns the position (1-based index) of the substring. If the substring is not found, it returns 0. This function is particularly useful for locating specific characters or substrings in text data.
Query:
SELECT INSTR('Hello World', 'World') AS SubstringPosition;Output:
7
9. TRIM(): Remove Leading and Trailing Spaces
The TRIM() function removes leading and trailing spaces (or other specified characters) from a string. By default, it trims spaces but can also remove specific characters using TRIM(character FROM string). This is helpful for cleaning text data, such as user inputs or database records.
Query:
SELECT TRIM(' ' FROM ' Hello World ') AS TrimmedString;Output:
Hello World
10. REVERSE(): Reverse the String
The REVERSE() function reverses the characters in a string. It’s useful in situations where we need to process data backward, such as for password validation or certain pattern matching.
Query:
SELECT REVERSE('Hello') AS ReversedString;Output:
olleH
Other String Functions
In SQL, beyond the basic string functions, there are several advanced string functions that can help you manipulate and process string data more effectively. These are the some additional SQL Functions.
11. ASCII(): Get the ASCII Value of a Character
The ASCII() function returns the ASCII value of a single character. This is helpful when we need to find the numeric code corresponding to a character, often used in encoding and decoding text.
Syntax:
SELECT ascii('t');Output:
116
12. CONCAT_WS(): Concatenate Strings with a Separator
CONCAT_WS() stands for "Concatenate With Separator." It allows us to join multiple strings with a specific separator between them. This is ideal when we need to merge columns like first name and last name with a custom separator.
Syntax:
SELECT CONCAT_WS('_', 'geeks', 'for', 'geeks');Output:
geeks_for_geeks
13. FIND_IN_SET(): Find Position of a Value in a Comma-Separated List
The FIND_IN_SET() function returns the position of a value within a comma-separated list. This is especially useful for finding out where an element exists in a string of values (e.g., tags, categories).
Syntax:
SELECT FIND_IN_SET('b', 'a, b, c, d, e, f');Output:
2
The FORMAT() function is used to format a number as a string in a specific way, often with commas for thousands or with a specific number of decimal places. It is handy when you need to display numbers in a user-friendly format.
Syntax:
SELECT FORMAT(0.981 * 100, 'N2') + '%' AS PercentageOutput;
Output:
‘98.10%’
15. INSTR(): Find the Position of a Substring
The INSTR() function returns the position of the first occurrence of a substring within a string. If the substring is not found, it returns 0. It is useful for finding where specific text appears in a larger string.
Syntax:
SELECT INSTR('geeks for geeks', 'e');Output:
2
16. LCASE(): Convert String to Lowercase
The LCASE() function converts all characters in a string to lowercase. It helps standardize text data, especially when comparing strings in a case-insensitive way.
Syntax:
SELECT LCASE ("GeeksFor Geeks To Learn");Output:
geeksforgeeks to learn
17. LOCATE(): Find the nth Position of a Substring
LOCATE() allows you to find the nth occurrence of a substring in a string. This is especially useful when you need to locate a specific substring based on its position.
Syntax:
SELECT LOCATE('for', 'geeksforgeeks', 1);
Output:
6
18. LPAD(): Pad the Left Side of a String
LPAD() is used to pad a string to a certain length by adding characters to the left side of the original string. It is useful when you need to format data to a fixed length.
Syntax:
SELECT LPAD('geeks', 8, '0');Output:
000geeks
MID() extracts a substring starting from a given position in a string and for a specified length. It is useful when you want to extract a specific portion of a string.
Syntax:
SELECT Mid ("geeksforgeeks", 6, 2);Output:
for
20. POSITION(): Find the Position of a Character in a String
The POSITION() function finds the position of the first occurrence of a specified character in a string.
Syntax:
SELECT POSITION('e' IN 'geeksforgeeks');
Output:
2
21. REPEAT(): Repeat a String Multiple Times
The REPEAT() function repeats a string a specified number of times. It's useful when you need to duplicate a string or pattern for certain operations.
Syntax:
SELECT REPEAT('geeks', 2);Output:
geeksgeeks
22. REPLACE(): Replace a Substring in a String
REPLACE() is used to replace all occurrences of a substring with another substring. It's useful for replacing or cleaning up certain text in your data.
Syntax:
REPLACE('123geeks123', '123');Output:
geeks
23. RPAD(): Pad the Right Side of a String
RPAD() pads the right side of a string with specified characters to a fixed length. This is often used to format text or numbers to a desired size.
Syntax:
RPAD('geeks', 8, '0');
Output:
‘geeks000’
24. RTRIM(): Remove Trailing Characters
RTRIM() removes trailing characters from the right side of a string. By default, it removes spaces, but you can specify other characters as well.
Syntax:
RTRIM('geeksxyxzyyy', 'xyz');
Output:
‘geeks’
25. SPACE(): Generate a String of Spaces
The SPACE() function generates a string consisting of a specified number of spaces. This is useful when you need to format output or create padding in your queries.
Syntax:
SELECT SPACE(7);
Output:
‘ ‘
26. STRCMP(): Compare Two Strings
STRCMP() compares two strings and returns an integer value based on their lexicographical comparison. This is useful for sorting or checking equality between two strings. STRCMP(string1, string2) returns:
- 0 if both strings are equal.
- A negative value if string1 is less than string2.
- A positive value if string1 is greater than string2.
Syntax
SELECT STRCMP('google.com', 'geeksforgeeks.com');
Output:
1
Summary of String Functions
Below is a table summarizing these functions, their purposes, and examples.
| Function | Description | Example Query | Output |
|---|
| ASCII() | Find ASCII value of a character. | SELECT ASCII('A'); | 65 |
| CONCAT_WS() | Concatenate with a delimiter. | SELECT CONCAT_WS('_', 'A', 'B'); | A_B |
| FIND_IN_SET() | Find position in a set. | SELECT FIND_IN_SET('b', 'a,b,c'); | 2 |
| LOCATE() | Find nth occurrence. | SELECT LOCATE('e', 'geeksforgeeks', 1); | 2 |
| LPAD() | Pad string from the left. | SELECT LPAD('geeks', 8, '0'); | 000geeks |
| POSITION() | Find character position. | SELECT POSITION('e' IN 'geeks'); | 2 |
| REPEAT() | Repeat a string. | SELECT REPEAT('SQL', 3); | SQLSQLSQL |
| RTRIM() | Remove trailing characters. | SELECT RTRIM('SQLXYZ', 'XYZ'); | SQL |
Similar Reads
SQL Tutorial Structured Query Language (SQL) is the standard language used to interact with relational databases. Mainly used to manage data. Whether you want to create, delete, update or read data, SQL provides commands to perform these operations. Widely supported across various database systems like MySQL, Or
7 min read
Basics
What is SQL?Structured Query Language (SQL) is the standard language used to interact with relational databases. It allows users to store, retrieve, update and manage data efficiently through simple commands. It is known for its user-friendly syntax and powerful capabilities, SQL is widely used across industrie
6 min read
SQL Data TypesIn SQL, each column must be assigned a data type that defines the kind of data it can store, such as integers, dates, text, or binary values. Choosing the correct data type is crucial for data integrity, query performance and efficient indexing.Benefits of using the right data type:Memory-efficient
3 min read
SQL OperatorsSQL operators are symbols or keywords used to perform operations on data in SQL queries. Perform operations like calculations, comparisons, and logical checks.Enable filtering, calculating, and updating data in databases.Essential for query optimization and accurate data management.Types of SQL Oper
5 min read
SQL Commands | DDL, DQL, DML, DCL and TCL CommandsSQL commands are fundamental building blocks for communicating with a database management system (DBMS) used to interact with database with some operations. It is also used to perform specific tasks, functions and queries of data. SQL can perform various tasks like creating a table, adding data to t
5 min read
SQL Database OperationsSQL databases or relational databases are widely used for storing, managing and organizing structured data in a tabular format. These databases store data in tables consisting of rows and columns. SQL is the standard programming language used to interact with these databases. It enables users to cre
3 min read
SQL CREATE TABLECreating a table is one of the first and most important steps in building a database. The CREATE TABLE command in SQL defines how your data will be stored, including the table name, column names, data types, and rules (constraints) such as NOT NULL, PRIMARY KEY, and CHECK.Defines a new table in the
3 min read
Queries & Operations
SQL SELECT QuerySQL SELECT is used to retrieve data from one or more tables, either all records or specific results based on conditions. It returns output in a tabular format of rows and columns.Extracts data from tables.Targets specific or all columns (*).Supports filtering, sorting, grouping, and joins.Results ar
2 min read
SQL INSERT INTO StatementINSERT INTO statement is used to add new rows to an existing table. It can insert values into all columns, specific columns, or even copy data from another table. This command is essential for populating databases with meaningful records such as customers, employees or students.Letâs explore differe
4 min read
SQL UPDATE StatementThe UPDATE statement in SQL is used to modify existing records in a table without deleting them. It allows updating one or multiple columns, with or without conditions, to keep data accurate and consistent.Change specific column values in selected rowsApply targeted updates using WHEREUpdate single
3 min read
SQL DELETE StatementThe SQL DELETE statement is used to remove specific rows from a table while keeping the table structure intact. It is different from DROP, which deletes the entire table.Removes rows based on conditions.Retains table schema, constraints, and indexes.Can delete a single row or all rows.Useful for cle
3 min read
SQL - WHERE ClauseIn SQL, the WHERE clause is used to filter rows based on specific conditions. Whether you are retrieving, updating, or deleting data, WHERE ensures that only relevant records are affected. Without it, your query applies to every row in the table! The WHERE clause helps you:Filter rows that meet cert
3 min read
SQL | AliasesIn SQL, aliases are temporary names given to columns or tables to make queries easier to read and write. They donât change the actual names in the database and exist only for the duration of that query.Make long or complex names readableSimplify joins and subqueriesImprove clarity in result setsAvoi
3 min read
SQL Joins & Functions
SQL Joins (Inner, Left, Right and Full Join)SQL joins are fundamental tools for combining data from multiple tables in relational databases. For example, consider two tables where one table (say Student) has student information with id as a key and other table (say Marks) has information about marks of every student id. Now to display the mar
4 min read
SQL CROSS JOINCROSS JOIN in SQL generates the Cartesian product of two tables, meaning each row from the first table is paired with every row from the second. This is useful when you want all possible combinations of records. Since result grows as rows_in_table1 Ã rows_in_table2, it can get very large, so itâs be
2 min read
SQL | Date FunctionsSQL Date Functions are built-in tools used to manage and manipulate date and time values in a database. They are essential for performing operations like retrieving current dates, calculating differences and formatting resultsCalculate date and time differences (e.g., days between orders).Retrieve t
4 min read
SQL | String functionsSQL String Functions are powerful tools that allow us to manipulate, format, and extract specific parts of text data in our database. These functions are essential for tasks like cleaning up data, comparing strings, and combining text fields. Whether we are working with names, addresses, or any form
7 min read
Data Constraints & Aggregate Functions
SQL NOT NULL ConstraintIn SQL, constraints are used to enforce rules on data, ensuring the accuracy, consistency, and integrity of the data stored in a database. One of the most commonly used constraints is the NOT NULL constraint, which ensures that a column cannot have NULL values. This is important for maintaining data
3 min read
SQL PRIMARY KEY ConstraintThe PRIMARY KEY constraint in SQL is one of the most important constraints used to ensure data integrity in a database table. A primary key uniquely identifies each record in a table, preventing duplicate or NULL values in the specified column(s). Understanding how to properly implement and use the
5 min read
SQL Count() FunctionIn the world of SQL, data analysis often requires us to get counts of rows or unique values. The COUNT() function is a powerful tool that helps us perform this task. Whether we are counting all rows in a table, counting rows based on a specific condition, or even counting unique values, the COUNT()
7 min read
SQL SUM() FunctionThe SUM() function in SQL is one of the most commonly used aggregate functions. It allows us to calculate the total sum of a numeric column, making it essential for reporting and data analysis tasks. Whether we're working with sales data, financial figures, or any other numeric information, the SUM(
5 min read
SQL MAX() FunctionThe MAX() function in SQL is a powerful aggregate function used to retrieve the maximum (highest) value from a specified column in a table. It is commonly employed for analyzing data to identify the largest numeric value, the latest date, or other maximum values in various datasets. The MAX() functi
4 min read
AVG() Function in SQLSQL is an RDBMS system in which SQL functions become very essential to provide us with primary data insights. One of the most important functions is called AVG() and is particularly useful for the calculation of averages within datasets. In this, we will learn about the AVG() function, and its synta
4 min read
Advanced SQL Topics
SQL SubqueryA subquery in SQL is a query nested inside another SQL query. It allows complex filtering, aggregation, and data manipulation by using the result of one query inside another. They are an essential tool when we need to perform operations like:Filtering: selecting rows based on conditions from another
4 min read
Window Functions in SQLSQL window functions are essential for advanced data analysis and database management. It is a type of function that allows us to perform calculations across a specific set of rows related to the current row. These calculations happen within a defined window of data and they are particularly useful
6 min read
SQL Stored ProceduresStored procedures are precompiled SQL statements that are stored in the database and can be executed as a single unit. SQL Stored Procedures are a powerful feature in database management systems (DBMS) that allow developers to encapsulate SQL code and business logic. When executed, they can accept i
7 min read
SQL TriggersA trigger is a stored procedure in adatabase that automatically invokes whenever a special event in the database occurs. By using SQL triggers, developers can automate tasks, ensure data consistency, and keep accurate records of database activities. For example, a trigger can be invoked when a row i
7 min read
SQL Performance TuningSQL performance tuning is an essential aspect of database management that helps improve the efficiency of SQL queries and ensures that database systems run smoothly. Properly tuned queries execute faster, reducing response times and minimizing the load on the serverIn this article, we'll discuss var
8 min read
SQL TRANSACTIONSSQL transactions are essential for ensuring data integrity and consistency in relational databases. Transactions allow for a group of SQL operations to be executed as a single unit, ensuring that either all the operations succeed or none of them do. Transactions allow us to group SQL operations into
8 min read
Database Design & Security
Introduction of ER ModelThe Entity-Relationship Model (ER Model) is a conceptual model for designing a databases. This model represents the logical structure of a database, including entities, their attributes and relationships between them. Entity: An objects that is stored as data such as Student, Course or Company.Attri
10 min read
Introduction to Database NormalizationNormalization is an important process in database design that helps improve the database's efficiency, consistency, and accuracy. It makes it easier to manage and maintain the data and ensures that the database is adaptable to changing business needs.Database normalization is the process of organizi
6 min read
SQL InjectionSQL Injection is a security flaw in web applications where attackers insert harmful SQL code through user inputs. This can allow them to access sensitive data, change database contents or even take control of the system. It's important to know about SQL Injection to keep web applications secure.In t
7 min read
SQL Data EncryptionIn todayâs digital era, data security is more critical than ever, especially for organizations storing the personal details of their customers in their database. SQL Data Encryption aims to safeguard unauthorized access to data, ensuring that even if a breach occurs, the information remains unreadab
5 min read
SQL BackupIn SQL Server, a backup, or data backup is a copy of computer data that is created and stored in a different location so that it can be used to recover the original in the event of a data loss. To create a full database backup, the below methods could be used : 1. Using the SQL Server Management Stu
4 min read
What is Object-Relational Mapping (ORM) in DBMS?Object-relational mapping (ORM) is a key concept in the field of Database Management Systems (DBMS), addressing the bridge between the object-oriented programming approach and relational databases. ORM is critical in data interaction simplification, code optimization, and smooth blending of applicat
7 min read