1

Let a table 'Example' has columns id, value.

| id | value |
|--- | ----- |
|1   | randm |

Now I want to write something like this

SELECT id, 'x is 'value'' as result
FROM Example
WHERE id = 1;

which prints

| id | result |
| -- | ------ |
| 1  | x is 'randm' |

How can I do this? In python, if we use {} in the middle of a string, we could pass variables, which is similar to what I want in SQL.

JNevill
  • 46,980
  • 4
  • 38
  • 63

2 Answers2

1

The operator || will concatenate strings in Postgres, so it's just:

 SELECT id, 'x is ''' || value || '''' AS result
 FROM Example
 WHERE id = 1;
JNevill
  • 46,980
  • 4
  • 38
  • 63
0
SELECT id, format('x is %L', value) as result
FROM Example
WHERE id = 1;

SELECT id, format('x is %s', quote_literal(value)) as result
FROM Example
WHERE id = 1;

SELECT id, format('x is ''%s''', value) as result
FROM Example
WHERE id = 1;

SELECT id, format($$x is '%s'$$, value) as result
FROM Example
WHERE id = 1;

https://www.postgresql.org/docs/current/functions-string.html#FUNCTIONS-STRING-FORMAT

https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-DOLLAR-QUOTING

Abelisto
  • 14,826
  • 2
  • 33
  • 41