2

How can I write the following MySQL query in PostgreSQL syntax:

SELECT CONCAT(REPEAT("   ", (COUNT(parent.name) - 1)), cat.name) AS name

Thanks in advance!

1
  • use concatenation signs || Commented Jun 10, 2015 at 11:59

2 Answers 2

4

The error here is that PostgreSQL doesn't allow double quotes " for literal strings (as per the SQL standard). You'll need to use single quotes '.

You also need to cast (COUNT(parent.name) - 1) to an integer, either using ::int (specific to Postgre) or CAST(... AS int).
Note that this may raise an integer out of range error if (COUNT(parent.name) - 1) is superior to 2147483647.

SELECT CONCAT(REPEAT('   ', (COUNT(parent.name) - 1)::int), cat.name) AS name

Note that you can also use || for string concatenation :

SELECT REPEAT('   ', (COUNT(parent.name) - 1)::int) || cat.name AS name
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for the useful answer, but I have another issue: it throws me an error: function repeat(unknown, bigint) does not exist.
I am using PostgreSQL. The error says: No function matches the given name and argument types. You might need to add explicit type casts. I tried to add CAST to the function arguments, but the error remains.
@ГеоргиБанков : updated my answer, you need to cast to int (you can see here that REPEAT takes 2 arguments : a string and an integer (not a bigint)).
Ahh, I tried casting to numeric, instead of int and that was causing the error. Still pretty new new to PostgreSQL. Thanks and +1
plus 1 for casting to int
1
SELECT REPEAT("   ", (COUNT(parent.name) - 1)) || cat.name AS name

SQLFIDDLE

Comments

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.