To concatenate two strings in SQL, the approach slightly varies depending on the database system, but the concept remains the same β combining two or more strings into a single result.
In most SQL databases like SQL Server, I use the + operator. For example:
SELECT FirstName + ' ' + LastName AS FullName
FROM Employees;
This merges the first and last names with a space in between. Itβs a clean and readable way to build full names, addresses, or custom labels.
In other databases like MySQL or PostgreSQL, the preferred way is to use the CONCAT() function:
SELECT CONCAT(FirstName, ' ', LastName) AS FullName
FROM Employees;
This method is safer because it automatically handles NULL values β in SQL Server, if either string is NULL, the entire result becomes NULL, whereas CONCAT() treats NULL as an empty string.
For example:
- In SQL Server:
'Aswini' + NULLβNULL - In MySQL:
CONCAT('Aswini', NULL)β'Aswini'
In one project, I used string concatenation to dynamically generate email IDs for employees based on their names and company domain:
SELECT CONCAT(LOWER(FirstName), '.', LOWER(LastName), '@company.com') AS EmailID
FROM Employees;
This was particularly useful during onboarding automation to pre-fill default email fields.
A challenge Iβve faced was dealing with NULL values, which would break concatenation in SQL Server. To handle that, I used the ISNULL() or COALESCE() function to replace NULL with an empty string, like:
SELECT ISNULL(FirstName, '') + ' ' + ISNULL(LastName, '') AS FullName
FROM Employees;
In summary, string concatenation in SQL is straightforward but slightly syntax-dependent:
+β SQL Server||β Oracle, PostgreSQLCONCAT()β MySQL, PostgreSQL (portable and safer)
I prefer CONCAT() for better null handling and cross-database compatibility.
