Does a regular INSERT INTO statement even work with TypeOrm? Tried formatting the string and quotes every which way, lost all patience.
await queryRunner.query('INSERT INTO "table"(column1,column2) VALUES ("Hi","Bye")');
Error: column "Hi" does not exist.
ie: it tries using the 1st value as the column lookup.
I also tried
await queryRunner.query('INSERT INTO "table"(column1,column2) VALUES ($1,$2) --PARAMETERS["Hi", "Bye"]');
Error: There is no parameter $1
Your problem come from the fact that you use double quotes for your string variable. As defined in the postgreSQL documentation, a string is an arbitrary sequence of characters bounded by single quotes ('). And farther in the documentation you can find that the double quotes (") are used to defined identifiers (such as table or column names)
Related
I am new to PostgresSQL.I tried
select * from employee where employee_name="elina";
But that results error as follows:
ERROR: column "elina" does not exist.
Then I tried by replacing double quotes with single quotes as follows:
select * from employee where employee_name='elina';
It result fine..So what is the difference between single quotes and double quotes in postgresql.If we can't use double quotes in postgres query,then if any other use for this double quotes in postgreSQL?
Double quotes are for names of tables or fields. Sometimes You can omit them. The single quotes are for string constants. This is the SQL standard. In the verbose form, your query looks like this:
select * from "employee" where "employee_name"='elina';
As explained in the PostgreSQL manual:
A string constant in SQL is an arbitrary sequence of characters bounded by single quotes ('), for example 'This is a string'. To include a single-quote character within a string constant, write two adjacent single quotes, e.g., 'Dianne''s horse'. Note that this is not the same as a double-quote character (").
Elsewhere on the same page:
There is a second kind of identifier: the delimited identifier or quoted identifier. It is formed by enclosing an arbitrary sequence of characters in double-quotes ("). A delimited identifier is always an identifier, never a key word. So "select" could be used to refer to a column or table named "select", whereas an unquoted select would be taken as a key word and would therefore provoke a parse error when used where a table or column name is expected.
TL;DR: Single quotes for string constants, double quotes for table/column names.
Well single quotes are used for string literals and double quotes are used for escaping DB objects like table name / column name etc.
Specifically, double quotes are used for escaping a column/table name if it's resemble to any reserve/key word. Though every RDBMS have their own way of escaping the same (like backtique in MySQL or square bracket in SQL Server) but using double quotes is ANSI standard.
I need to query an Excel file using ODBC.
A sheet, Sheet1 has a column that contains double quotes. For example, he"llo.
Querying the sheet without that column yields correct results, for instance:
SELECT "test" FROM "Sheet1$"
But when a column contains double quotes, I'm unable to query it. I've read somewhere you can escape those quotes by adding double quotes, but the following query SELECT "he""llo" FROM "Sheet1$" yields the following error:
Syntax error (missing operator) in query expression '[he][llo]'.
I have tried all sorts of ways to escape that character but to no avail.
Please note that changing the data source is not an option, or at least a last resort option.
Thanks in advance!
Found the solution.
When a column contains double quotes, you can change the quoted identifier to back ticks. You can even mix them with regular quoting for other columns such as:
SELECT "test", `he"llo` FROM "Sheet1$"
Hope this helps someone else as well!
This is very simple but somehow I'm doing something wrong with this query on my database.
I have this query below:
SELECT login FROM accounts WHERE login = "loginname";
When I execute this query the result I get is this:
column "loginname" does not exist
This is a no brainer, why is this query not working properly? I have a login column and I know that this user exists because I've found this person with the rails console. Why is the login criteria referring to itself as a column?
Try with single quotes '' if you are trying to match a string
SELECT login FROM accounts WHERE login = 'loginname';
Check the documentation
There is a second kind of identifier: the delimited identifier or
quoted identifier. It is formed by enclosing an arbitrary sequence of
characters in double-quotes ("). A delimited identifier is always an
identifier, never a key word. So "select" could be used to refer to a
column or table named "select", whereas an unquoted select would be
taken as a key word and would therefore provoke a parse error when
used where a table or column name is expected.
Double quotes (") are used to refer to object names, in a case sensitive way. In this case, "loginname" is interpreted as a column name, and the query fails, since there is no such column. In order to refer to a string literal, you should use single quotes ('):
SELECT login FROM accounts WHERE login = 'loginname';
-- Here ---------------------------------^---------^
It seems that the " " are the problem if you believe the documentation. Single quotes are required for string values.
From the PostgreSQL Documentation:
There is a second kind of identifier: the delimited identifier or quoted identifier. It is formed by enclosing an arbitrary sequence of characters in double-quotes ("). A delimited identifier is always an identifier, never a key word. So "select" could be used to refer to a column or table named "select", whereas an unquoted select would be taken as a key word and would therefore provoke a parse error when used where a table or column name is expected. The example can be written with quoted identifiers like this:
UPDATE "my_table" SET "a" = 5;
Quoted identifiers can contain any character, except the character with code zero. (To include a double quote, write two double quotes.) This allows constructing table or column names that would otherwise not be possible, such as ones containing spaces or ampersands. The length limitation still applies.
So in your query "loginname" is the same as having loginname without quotes - it's attempting to refer to a column with that name. To make it a literal string, use single-quotes instead.
In ActiveRecord (using Ruby on Rails), if i have #products variable where #products = Product.all, and I say:
#products.where("name = 'check123' "), it returns an array of objects matching that condition, if i however go #products.where('name="check123"') i get an error?
: SELECT "products".* FROM "products" WHERE (name = "check123")
Hirb Error: PG::UndefinedColumn: ERROR: column "check123" does not exist
LINE 1: SELECT "products".* FROM "products" WHERE (name = "check123"...
^
Why is this happening? It seems that I must always use double quotes around everything in the where clause and single quotes for any strings inside there ?
Shouldn't single quotes work here as well, or is there something Im not getting
Some other observations:
#products.where("cost = '23.0'") works, event though 23 has a datatype of integer and not string?
#products.where('cost = 23') works, so I know i can use single quotes inside the where clause
NOTE: I am aware of using the '?' syntax inside the where clause to avoid sql injections, I am purposefully trying to execute the query like this.
Double quotes are used for naming database objects (table names, columns names, user names, schema names...) whilst single quotes are intended to represent strings to be used as values.
so your UndefinedColumn: ERROR makes sense as when filtering with #products.where('name="check123"') the SQL produced will be .... where name = "check123". The db engine is trying to find a column with the name check123 and match its value to the value of column name. As the column check123 does not exist in your table, you get an "undefined column name" error.
For your other question:
When you filter an integer column by a string value what happens is that the db engine does an implicit conversion of the column values to string in order to perform the search.
Update
The general SQL standard is described by this question's answers. In summary most Db engines follow most of the ANSI standard, and the use of double quotes is usually reserved for database objects.
I have a string with value
'MAX DATE QUERY: SELECT iso_timestamp(MAX(time_stamp)) AS MAXTIME FROM observation WHERE offering_id = 'HOBART''
But on inserting into postgresql table i am getting error:
org.postgresql.util.PSQLException: ERROR: syntax error at or near "HOBART".
This is probably because my string contains single quotes. I don't know my string value. Every time it keeps changing and may contain special characters like \ or something since I am reading from a file and saving into postgres database.
Please give a general solution to escape such characters.
As per the SQL standard, quotes are delimited by doubling them, ie:
insert into table (column) values ('I''m OK')
If you replace every single quote in your text with two single quotes, it will work.
Normally, a backslash escapes the following character, but literal backslashes are similarly escaped by using two backslashes"
insert into table (column) values ('Look in C:\\Temp')
You can use double dollar quotation to escape the special characters in your string.
The above query as mentioned insert into table (column) values ('I'm OK')
changes to insert into table (column) values ($$I'm OK$$).
To make the identifier unique so that it doesn't mix with the values, you can add any characters between 2 dollars such as
insert into table (column) values ($aesc6$I'm OK$aesc6$).
here $aesc6$ is the unique string identifier so that even if $$ is part of the value, it will be treated as a value and not a identifier.
You appear to be using Java and JDBC. Please read the JDBC tutorial, which describes how to use paramaterized queries to safely insert data without risking SQL injection problems.
Please read the prepared statements section of the JDBC tutorial and these simple examples in various languages including Java.
Since you're having issues with backslashes, not just 'single quotes', I'd say you're running PostgreSQL 9.0 or older, which default to standard_conforming_strings = off. In newer versions backslashes are only special if you use the PostgreSQL extension E'escape strings'. (This is why you always include your PostgreSQL version in questions).
You might also want to examine:
Why you should use prepared statements.
The PostgreSQL documentation on the lexical structure of SQL queries.
While it is possible to explicitly quote values, doing so is error-prone, slow and inefficient. You should use parameterized queries (prepared statements) to safely insert data.
In future, please include a code snippet that you're having a problem with and details of the language you're using, the PostgreSQL version, etc.
If you really must manually escape strings, you'll need to make sure that standard_conforming_strings is on and double quotes, eg don''t manually escape text; or use PostgreSQL-specific E'escape strings where you \'backslash escape\' quotes'. But really, use prepared statements, it's way easier.
Some possible approaches are:
use prepared statements
convert all special characters to their equivalent html entities.
use base64 encoding while storing the string, and base64 decoding while reading the string from the db table.
Approach 1 (prepared statements) can be combined with approaches 2 and 3.
Approach 3 (base64 encoding) converts all characters to hexadecimal characters without loosing any info. But you may not be able to do full-text search using this approach.
Literals in SQLServer start with N like this:
update table set stringField = N'/;l;sldl;'''mess'