Ways to escape single quotes in SQL 'LIKE' command - sql

What are the various ways to ESCAPE single quotes(') in the SQL LIKE command?
One way is to put two single quotes whenever you have to escape a single quote.
Can you people suggest something?
Databases: SQL Server 2005 and Oracle 10g

You already have the answer. You have to use two single quotes:
select * from table where field like '%''something''%'

Two single quotes is the best solution.
Alternatively, you can use a CHAR(39) to represent a single quote character.
UPDATE Employee SET LastName = 'O' + CHAR(39) + 'Brien'
WHERE ID=1;

The best way is to bind the parameter with ADO or ADO.NET.
Like (example in C# with ADO.NET):
SqlCommand x = new SqlCommand(sqlConnection, #"select * from table where col like '%'+#para1+'%'");
x.parameters.add(new SqlParameter("#para1",sqltype.varchar,100)).value = "this is a' test";
In SQL Server 2005 you escape a single quote (') with a double single quote ('') if you do not want to bind:
select * from table where col like '%this is a'' test%'

If you want to search the value Allen O'Dea following is the query.
SELECT * FROM [TABLE] WHERE [COLUMN] LIKE '%Allen O''Dea%'
This query works perfectly.

There is also the "Q-quote" method:
select * from mytable where text like q'#%Here's some text%#';
This is available since Oracle 10.2.
I used a '#' character as the quote delimiter, but you can use pretty much any character that won't appear in the string (there are a few exceptions, such as the space character).
In a simple example like that above I probably wouldn't do this. I'd just double up the single quotes, but it does come in handy when building large dynamic SQL statements that include lots of string literals.

Related

SQL Searching for results with apostrophes

I am trying to automate a problem at work and have an SQL question. I am getting a list from one of our vendors strips all of the apostrophes out of the info.
So when I search for "oneil" and my database has "o'neil"
select * from db where name = "oneil"
I know how to fix that by hand, but how would I make it work when I don't know where the apostrophe is at?
I hope I explained that right.
You could first strip the apostrophes from the name before doing the comparison:
SELECT *
FROM db
WHERE REPLACE(name, '''', '') = 'oneil';
Demo
Note that in most versions of SQL, a literal apostrophe is represented inside a string literal using two apostrophes doubled-up ''.
For SQL Server, use a temp table with apostrophes replaced:
select *,
derived_name = REPLACE(t.name,'''','')
into #temp
from table t
Then you can do: select * from #temp where derived_name='oneil'
Note that the apostrophe is also the escape character in sql server.

How do I deal with SQL tablenames with hyphen (-) when writing raw queries? i.e project-users

I have a table called project-users and want to write a SQL query like SELECT * FROM project-users I get this error ERROR: syntax error at or near "-".
I cannot change the table name at this point.
According to http://www.postgresql.org/docs/9.0/static/sql-syntax-lexical.html, you should use double quotes.
In your case, for PostgreSQL the query should be:
SELECT * FROM "project-users";
It is good practice to avoid the use of characters that need escaping or that contain spaces in identifiers.

Querying Postgres database

I want to query a database where a column matches a string & this string is having a single quote character '. I am unable to run the following query
SELECT *
from <table>
where <column>='robocopy'w (ithout)backup.pcap';
The reason being that single quotes is used to search the column;
I tried double quotes but no help.
I can by pass this if I add a extra single quote just before the single in a string.
SELECT *
from <table>
where <column>='robocopy''w (ithout)backup.pcap';
But I need a better solution as it is not practical to add a single quote every time,specially if they are long and have many single quotes.
You need to escape your query string before sending it to the database. I can't show you how because you didn't post the code, but if you are running this query directly in the psql console, you can escape the quotes by putting all constraint inside $$ and $$, as cited in the documentation[1]. Example:
SELECT * from <table> where <column> = $$robocopy'w (ithout)backup.pcap$$;
[1] http://www.postgresql.org/docs/current/interactive/sql-syntax-lexical.html#SQL-SYNTAX-DOLLAR-QUOTING

how to retrieve sql column includes special characters and alphabets

How to retrieve a column containing special characters including alphabets in SQL Query. i have a column like this 'abc%def'. i want to retrieve '%' based columns from that table.
Please help me in this regard.
Is abc%def the column name? or column value? Not sure what you are asking but if you mean your column name contains special character then you can escape them which would be different based on specific RDBMS you are using
SQL Server use []
select [abc%def] from tab
MySQL use backquote
select `abc%def` from tab
EDIT:
Try like below to fetch column value containing % character (Checked, it works in Ingres as well)
select * from tab where col like '%%%'
Others suggest that like '%%%' works in Ingres. So this is something special in Ingres. It does not work in other dbms.
In standard SQL you would have to declare an escape character. I think this should work in Ingres, too.
select * from mytable where str like '%!%%' escape '!';

How do I search for names with apostrophe in SQL Server?

SELECT *
FROM Header
WHERE (userID LIKE [%'%])
Double them to escape;
SELECT *
FROM Header
WHERE userID LIKE '%''%'
SELECT *
FROM Header WHERE (userID LIKE '%''%')
SELECT * FROM Header WHERE userID LIKE '%' + CHAR(39) + '%'
SELECT * FROM TableName WHERE CHARINDEX('''',ColumnName) > 0
When you have column with large amount of nvarchar data and millions of records, general 'LIKE' kind of search using percentage symbol will degrade the performance of the SQL operation.
While CHARINDEX inbuilt TSQL function is much more faster and there won't be any performance loss.
Reference SO post for comparative view.
That's:
SELECT * FROM Header
WHERE (userID LIKE '%''%')
select * from Header where userID like '%''%'
Hope this helps.
First of all my Search query value is from a user's input.
I have tried all the answers on this one and all the results Google have given me, 90% of the answers says put '%''%' and the other 10% says a more complicated answers.
For some reason all of those did not work for me.
How ever I remembered that in MySQL (phpmyadmin) there is this built in search function so I tried it just to see how MySQL handles a search with an apostrophe, turns out MySQL just escaping apostrophe with a backslash LIKE '%\'%'
so why just I replace apostrophe with a \' in every user's query.
This is what I come up with:
if(!empty($user_search)) {
$r_user_search = str_ireplace("'","\'","$user_search");
$find_it = "SELECT * FROM table WHERE column LIKE '%$r_user_search%'";
$results = $pdo->prepare($find_it);
$results->execute();
This solves my problem.
Also please correct me if this is still has security issues.
Brackets are used around identifiers, so your code will look for the field %'% in the Header table. You want to use a string insteaed. To put an apostrophe in a string literal you use double apostrophes.
SELECT *
FROM Header WHERE userID LIKE '%''%'
Compare Names containing apostrophe in DB through Java code
String sql="select lastname from employee where FirstName like '%"+firstName.trim().toLowerCase().replaceAll("'", "''")+"%'"
statement = conn.createStatement();
rs=statement.executeQuery(Sql);
iterate the results.