Concatenating Strings in SQLite: Beyond the Missing CONCAT Function
Unlike many other database systems, SQLite doesn't have a built-in function named CONCAT for string concatenation. This can be surprising for programmers familiar with SQL in general.
Alternative: The Pipe Operator
Instead, SQLite uses the pipe symbol (||
) for string concatenation. Here's an example:
SELECT first_name || ' ' || last_name AS full_name
FROM customers;
This query would create a new column named "full_name" by concatenating the "first_name" and "last_name" columns with a space in between.
Other Points to Consider
- Column names: SQLite doesn't allow string concatenation within column names during table creation.
- NULL values: Be mindful of NULL values in your string columns. The pipe operator (
||
) treats NULL as an empty string, which can affect your results. You can use theIFNULL
function to handle NULL values before concatenation.
SELECT 'Hello' || ' World!' AS greeting;
This code will return "Hello World!" by concatenating the two literal strings.
Concatenating Table Columns:
SELECT first_name || ' ' || last_name AS full_name
FROM customers;
This code assumes a table named "customers" with columns "first_name" and "last_name". It creates a new column named "full_name" by combining the first and last names with a space in between.
Adding a separator between multiple strings:
SELECT product_name || ' (price: $' || price || ')' AS product_info
FROM products;
This code builds a product information string by concatenating the product name, a literal string "(price: $", the price column (assuming it's a numeric value), and a closing parenthesis.
Handling NULL values (optional):
SELECT IFNULL(first_name, '') || ' ' || IFNULL(last_name, '') AS full_name
FROM customers;
- Using printf-style formatting:
SQLite offers a function called printf
that allows you to format strings similarly to the printf
function in C. You can use it for string concatenation, but it can be less readable than the pipe operator for simple cases.
Here's an example:
SELECT printf("%s %s", first_name, last_name) AS full_name
FROM customers;
This code achieves the same result as the previous example using ||
, but with the printf
function and format specifiers (%s
for string).
Note: printf
is generally less performant than the pipe operator, so it's recommended for situations where you need more complex formatting options.
- Building the string with multiple concatenations:
Technically, you can chain multiple pipe operators together to build a string one piece at a time. However, this can become cumbersome for complex concatenations and might affect readability.
Here's an example (equivalent to the previous printf
approach):
SELECT first_name || ' ' || last_name AS full_name
FROM customers;
While this achieves the same outcome as the first example using ||
, it's not necessarily an alternate method as it relies on the same operator.
sql sqlite string