In PostgreSQL, we can use the quote_ident()
function to quote identifiers in a SQL statement string.
Quotes are only added if necessary. Any embedded quotes are doubled.
Examples
Here’s an example to demonstrate:
SELECT quote_ident('User Logins');
Result:
"User Logins"
Here are more examples:
\x
SELECT
quote_ident('user') AS "user",
quote_ident('users') AS "users",
quote_ident('user_logins') AS "user_logins",
quote_ident('users_logins') AS "users_logins",
quote_ident('users'' logins') AS "users'' logins",
quote_ident(E'users\' logins') AS "users\' logins",
quote_ident('users "logins"') AS "users ""logins""",
quote_ident(' ') AS " ",
quote_ident('100') AS "100";
Result:
user | "user"
users | users
user_logins | user_logins
users_logins | users_logins
users'' logins | "users' logins"
users\' logins | "users' logins"
users "logins" | "users ""logins"""
| " "
100 | "100"
Passing a Null Value
Passing a null value results in null
being returned:
SELECT quote_ident(null);
Result:
null