0

Under what circumstances is it better to use CONCAT with + over CONCAT_WS when analyzing data?

4
  • 2
    Which SQL you are using? Commented Jun 12, 2022 at 1:26
  • Thanks so much for your response Muhammad. I am taking a Google Analytics course and one of my assignments was to ask a question here. I am using the BigQuery platform for SQL data analysis. Commented Jun 12, 2022 at 1:30
  • You can simply use the Concatenation operator || or CONCAT function as explained in the documentation. Commented Jun 12, 2022 at 1:43
  • The function often will convert nulls to empty strings. Otherwise adding null should return null. Big Query is a platform I am less familiar with but a quick search said that I was as wrong. Commented Jun 13, 2022 at 3:28

3 Answers 3

1

First of all, BigQuery doesn't support CONCAT_WS. As I know, most closest syntax is below:

SELECT ARRAY_TO_STRING(['aaa', 'bbb', 'ccc'], ',') AS concat_str;

output:

aaa,bbb,ccc

And regarding when you have to use CONCAT() or ARRAY_TO_STRING() in BigQuery (as an alternative of CONCAT_WS), it highly depends on the logic your query tries to implement.

My opinion is that ARRAY_TO_STRING() seems to be suited for CSV-styled string and CONCAT would be preferred where strings are concatenated without a repetitive delimiter.

Sign up to request clarification or add additional context in comments.

Comments

0

SQL dialects vary quite a lot in the way they handle text-string data, both in storage and in the functions (CONCAT among others) used to manipulate that text. So a hard-core StackOverflow answer would insist you put the SQL variant in your question tags.

But your situation is not quite that.

So, let's say, for example, that you wish to use SQL concatenation to write www.example.com. You could do

CONCAT('www', '.', 'example', '.', 'com')

or

CONCAT_WS('.', 'www', 'example', 'com')

As you can see, for that example CONCAT_WS is a little more concise. And, if your app logic is built to handle that dot-separated style of names, it respects that logic.

On the other hand an expression like

CONCAT('surname:', user_surname)

is easier to express with CONCAT.

So, the answer: the choice depends on the application's data organization.

Performance-wise, the difference between CONCAT and CONCAT_WS is too small to measure, and far smaller than many other parts of satisfying a typical SQL query.

Comments

0

Let say you want to combine both First_name and Last_name you could say

CONCAT(First_name,' ',Last_name) AS full_name

1 Comment

Learn to use markdown to format your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.