Monday, October 10, 2016

SQL Statement with Single or Double Quotes for PostgerSQL ?

SQL Statement with Single or Double Quotes for PostgerSQL ?

Single Quotes or Double Quotes? That is a Question!

Consider a sql statement:

SELECT model AS 'Model Name' FROM orders

We usually write it in the format below in Ruby on Rails:

query_string = "SELECT model AS 'Model Name' FROM orders"

It works fine for SQLite and MySQL, but fails for PostgreSQL!

The root cause is that PostgreSQL only accepts double-quoted key words!

Solution: use double-quotes instead of single-quotes:

SELECT model AS "Model Name" FROM orders

In Rails, it should be:

query_string = 'SELECT model AS "Model Name" FROM orders'

Note that it turns to be single quotes for wrapping the whole query string.

No comments:

Post a Comment