Skip to main content
0 reactions

How to Write a String in PostgreSQL

Featured card for How to Write a String in PostgreSQL, with a terminal window listing ‘Hello, world’, ‘It’’s raining’, an empty string and a note that double quotes mark a name.
How to write a string in PostgreSQL.

In PostgreSQL, you write a piece of text, a string, between single quotes: 'Hello, world'. To put a single quote inside the text, type it twice. Double quotes mean something else: they’re for the names of tables and columns.

Every command and output on this page is real, from PostgreSQL 19 on macOS.

Syntax

SyntaxSQL
'text'
'It''s'
  • ' and ': a string starts and ends with a single quote.
  • '' inside a string: one single quote, so 'It''s' is the text It’s.
  • '' on its own: an empty string, text with no characters.

See String Constants (opens in a new tab) in the PostgreSQL documentation.

The Example

Three short strings, shown with SELECT, which returns whatever value you give it.

Step 1: Connect

Open Terminal and connect to your PostgreSQL server with psql as the postgres user:

TerminalBash
psql -U postgres

Type the user’s password when psql asks for it. psql connects you to the postgres database, and its prompt is postgres=#.

Step 2: Write a String

postgres=#SQL
SELECT 'Hello, world';
OutputPlain text
   ?column?
--------------
 Hello, world
(1 row)

?column? is the name PostgreSQL gives a result column that has no name of its own.

Step 3: Put a Single Quote Inside

postgres=#SQL
SELECT 'It''s raining';
OutputPlain text
   ?column?
--------------
 It's raining
(1 row)

The two single quotes in the middle came out as one.

Step 4: Write an Empty String

postgres=#SQL
SELECT '';
OutputPlain text
 ?column?
----------

(1 row)

The result is one row with nothing in it.

Common Mistakes

MistakeWhat happensDo this instead
Double quotes around text: SELECT "Hello, world";ERROR: column "Hello, world" does not existUse single quotes for text. Double quotes are for names.

FAQ

Can a string hold any character?

Yes, any text, including letters such as é and emoji. Only the single quote needs doubling.

Why does PostgreSQL say column when I used double quotes?

Because double quotes mark a name. PostgreSQL looked for a column called Hello, world.

Conclusion

Write text between single quotes, double any single quote inside it, and keep double quotes for the names of tables and columns.

Additional Resources

Postgres, PostgreSQL and the Slonik Logo are trademarks or registered trademarks of the PostgreSQL Community Association of Canada, and used with their permission.

0 comments