SQL: Structured Query LanguageSQL FundamentalsScalar Functions
What does the CONCAT function do?
Question 28 of 30 · Updated
On this page
CONCAT() joins two or more values into a single text string. Use it to combine names, build order references or create readable labels directly in a SQL query. It does not change the original column values when used in SELECT.
Practical example: display a customer's full name#
Suppose your application stores first and last names separately. You can combine them for display without storing another column. In PostgreSQL, this example uses two sample rows so you can run it without creating a table.
SQLWITH people(id, first_name, last_name) AS ( VALUES (1, 'Asha', 'Rao'), (2, 'Ravi', NULL::text) ) SELECT id, CONCAT(first_name, ' ', last_name) AS full_name, CONCAT_WS(' ', first_name, last_name) AS clean_name FROM people ORDER BY id;
Output:
| id | full_name | clean_name |
|---|---|---|
| 1 | Asha Rao | Asha Rao |
| 2 | Ravi (trailing space) | Ravi |
CONCAT does not automatically insert spaces. Here, the string ' ' supplies a separator explicitly. In PostgreSQL, CONCAT ignores NULL arguments but retains the supplied space. CONCAT_WS (concatenate with separator) places the separator between non-NULL values, which is useful when name components are optional. It does not skip empty strings.
What happens with numbers and NULL?#
SQLSELECT CONCAT('ORD-', 42) AS order_code, CONCAT('A', NULL::text, 'B') AS concat_result, ('A' || NULL::text || 'B') AS operator_result, CONCAT_WS('-', 'A', NULL::text, 'B') AS separated;
| order_code | concat_result | operator_result | separated |
|---|---|---|---|
| ORD-42 | AB | NULL | A-B |
PostgreSQL converts the integer argument to text. Notice that its || string concatenation operator returns NULL when a text operand is NULL, unlike CONCAT. MySQL CONCAT returns NULL if an argument is NULL; do not assume PostgreSQL's behavior is universal.
Remember for interviews#
CONCAT combines values into one string per evaluation; it does not combine multiple rows into one result. Use CONCAT_WS when a consistent separator is required between optional values. Common mistakes are forgetting spaces, expecting numeric addition, and assuming the same NULL behavior in every database.
Validation: Both SQL examples were executed successfully on PostgreSQL with synthetic data. No diagram is needed because the input/output tables directly demonstrate the transformation. Supabase's Full Text Search documentation was consulted for the concatenation-operator example; the external manual reference below was not live fetched under the offline research exception.
References: PostgreSQL string functions and operators · Supabase Full Text Search
References
- 1.PostgreSQL — String Functions and Operatorspostgresql.org
- 2.Supabase — Full Text Searchsupabase.com
Related questions
Explore other topics:Forward Deployed EngineeringPythonAI System DesignMachine Learning