- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Can MySQL concatenate strings with ||?
Yes, you can concatenate strings with || in MySQL with the help of sql_mode. Set the sql_mode to PIPES_AS_CONCAT.
The syntax is as follows
set sql_mode=PIPES_AS_CONCAT;
The following is the syntax to concat with the help of ||.
SELECT ‘yourValue' || yourColumName AS anyAliasName FROM yourTableName;
To understand the above syntax, let us create a table. The query to create a table is as follows
mysql> create table PipeConcatDemo - > ( - > Name varchar(20) - > ); Query OK, 0 rows affected (0.93 sec)
Insert some records in the table using insert command.
The query is as follows
mysql> insert into PipeConcatDemo values('Larry'); Query OK, 1 row affected (0.18 sec) mysql> insert into PipeConcatDemo values('John'); Query OK, 1 row affected (0.15 sec) mysql> insert into PipeConcatDemo values('Maxwell'); Query OK, 1 row affected (0.23 sec) mysql> insert into PipeConcatDemo values('Bob'); Query OK, 1 row affected (0.17 sec)
Now you can display all records from the table using select statement.
The query is as follows
mysql> select *from PipeConcatDemo;
The following is the output
+---------+ | Name | +---------+ | Larry | | John | | Maxwell | | Bob | +---------+ 4 rows in set (0.00 sec)
Now before concatenation, run the following is the query to change the sql_mode to PIPES_AS_CONCAT
mysql> set sql_mode=PIPES_AS_CONCAT; Query OK, 0 rows affected (0.00 sec)
You can now use || for concatenation:
mysql> select 'Good Morning !!! ' || Name AS PipeConcatenationDemo from PipeConcatDemo;
The following is the output
+--------------------------+ | PipeConcatenationDemo | +--------------------------+ | Good Morning !!! Larry | | Good Morning !!! John | | Good Morning !!! Maxwell | | Good Morning !!! Bob | +--------------------------+ 4 rows in set (0.00 sec)
Advertisements