How to Concatenate in SQLite
-
Method 1: Concat String Using
||
in SQLite -
Method 2: Concat String Using the
printf()
Method in SQLite
Sometimes we need to show our database output in our own defined format. For this purpose, we need to concatenate multiple data from multiple fields.
For example, if we have three kinds of data like Id
, Firstname
, and Lastname
, you may wish to visualize data by the following format, id-firstname-lastname
.
In this article, we will see how we can concatenate multiple strings in SQLite. Also, we will look at some examples to make the topic easier.
We are going to discuss two different methods here.
Method 1: Concat String Using ||
in SQLite
In our example below, we will see how we can concatenate string using the ||
. The general syntax for this purpose is String1 || String2
.
Have a look at the below example.
SELECT id || '-' || name FROM demo;
In the query above, we concatenate the data from the field id
and name
.
Method 2: Concat String Using the printf()
Method in SQLite
In our example below, we will illustrate how we can concatenate multiple data as strings using the method printf()
. The general syntax for this method is printf('%s-%s', string1, string2)
.
Let’s take a look at the below example.
SELECT printf('%s-%s', id, name) from demo;
In the query above, we concatenate the data from the field id
and name
.
In both examples, we take the data from fields as strings, and both will provide you with the same result as the one below.
1-Alex
2-Stefen
3-Boris
We have discussed two different methods to concatenate multiple data (string). As they provide the same result, you can choose any of them based on your project needs.
Please note that the queries we provided in this article are written for SQLite.
Aminul Is an Expert Technical Writer and Full-Stack Developer. He has hands-on working experience on numerous Developer Platforms and SAAS startups. He is highly skilled in numerous Programming languages and Frameworks. He can write professional technical articles like Reviews, Programming, Documentation, SOP, User manual, Whitepaper, etc.
LinkedIn