MySQL query enclosing numbers in strings - mysql

Suppose I have a query
SELECT * FROM table WHERE x > y;
where "y" is a user-input value. I'd like to enclose y in quotes. So far as I've tested, the query works properly when the quotes are added. Is the behaviour defined? Is it known to result in an efficiency drop?
Note that the query is an example fabricated for simplicity. Also, this is not an attempt to deal with SQL injection.

If the field that you are trying to compare with is a numeric field ie int, then all the possible combinations must work in mysql
select * from users where id = 20;
select * from users where id = "20";
select * from users where id = '20';
Refer the MySQL DOC for more depth

The conversion behavior of MySQL when comparing different types is well-defined. When a string and a number are compared, both are converted to floats. It's outlined in the manual, ยง 11.2.

IMO, you can try :-
cast( "-10" as signed )
This is casting in mysql (the function name is cast, obvious?).

Related

Match Numeric value after comma separated, concatenated by underscore values using MYSQL/MariaDB & REGEXP_SUBSTR

I have field column values stored like:
texta_123,textb_456
My SQL:
SELECT *
FROM mytable
WHERE 456 = REGEXP_SUBSTR(mytable.concatenated_csv_values, 'textb_(?<number>[0-9]+)')
NOTE: I'm aware there are multiple ways of doing this, but for the purposes of example I simplified my query substantially; the part I need to work is REGEXP_SUBSTR()
Effectively, I want to: "query results where an id equals the numeric value extracted after an underscore in a column with comma-separated values"
When I test my Regex, it seems to work fine.
However, in MySQL (technically, I'm using MariaDB 10.4.19), when I run the query I get a warning: "Warning: #1292 Truncated incorrect INTEGER value:textb_456"
You should seriously consider fixing your database design to not store unnormalized CSV data like this. As a temporary workaround, we can use REGEXP_REPLACE along with FIND_IN_SET:
SELECT *
FROM mytable
WHERE FIND_IN_SET(
'456',
REGEXP_REPLACE(concatenated_csv_values, '^.*_', '')) > 0;
The regex trick used here would convert a CSV input of texta_123,textb_456 to just 123,456. Then, we can easily search for a given ID using FIND_IN_SET.

mysql : avoid automatic cast of string in integer in where clause

In my application, I use a generic where clause to search in different fields.
My request is like this :
SELECT * FROM command WHERE id = :search OR name LIKE %:search%;
I am searching the text "2SAV".
this request return some records where name contains "2SAV" (what I want) but also the record where id=2.
If I do more tests, I notice that :
SELECT CAST("2SAV" AS SIGNED); //2
SELECT 2="2SAV"; //1
If the string start with an integer, this part of string is kept.
Have you got an option or workaround to avoid this comportment?
Thanks in advance,
In the MySQL documentation( https://dev.mysql.com/doc/refman/5.7/en/type-conversion.html) is stated:
In all other cases, the arguments are compared as floating-point (real) numbers.
I think you could cast in the query:
SELECT * FROM command WHERE id = cast(:search as char) OR name LIKE %:search%;

difference between UNHEX and X (MySQL)

What really is the difference between MySQL UNHEX and X when dealing with hexadecimal values in a database?
Eg.
SELECT * FROM test WHERE guidCol IN (UNHEX('hexadecimalstring'));
SELECT * FROM test WHERE guidCol IN (X'hexadecimalstring');
Both gives me exact result set. So is there any difference? Performance implications?
Edit: the underlying type of guidCol is binary of course
UNHEX() is a function, therefore you can do something like
SET #var = '41';
SELECT UNHEX(#var);
SELECT UNHEX(hex_column) FROM my_table;
X, on the other hand, is the syntax for a hexadecimal litteral. You cannot do this:
SET #var = '41';
SELECT X#var; -- error (string litteral expected)
SELECT X'#var'; -- error (`#` is not a hexadecimal digit)
SELECT X(#var); -- returns NULL, not too sure about the reason... [edit: but this is probably why you are inserting NULL values]
SELECT X(hex_column) FROM my_table; -- returns NULL as well
This explains why you always get better performance with X: you are using a language construct instead of a function call. X does not need to evaluate a variable, since it expects a litteral string.
Note that even in MySQL 5.6, the X'' notation has a length limit in the reference mysql client and UNHEX() does not (appear to). I do not know what the limit is for X'', as it is not officially documented but I have encountered it when trying to INSERT a BLOB. With X'' literal, mysql client threw a syntax error with a sufficiently long hex sequence while UNHEX() of the same sequence did not. Obviously, length is not an issue when it comes to an actual GUID, but I figured this is useful for anyone else using this question to answer mysql insertion of binary data in the general case.

mysql float data not selecting in where clause

This maybe an easy one but i couldn't get answer.
I need to select float value from table
example table :-
value
10.2
4.5
4.6
4.06
my query
SELECT * FROM table where value = '4.6'
returns empty result set
how can i solve this !
Generally, you should never check equality with floats (unless, potentially, you have the same object). Internally, it is represented with more precision, even if it isn't showing it to you by the time it outputs to the screen. This basic tenet holds true for computing in general.
There are a dozens of schemes for doing this, but here is a simple one, which should make sense:
SELECT * FROM table where value BETWEEN 4.599 AND 4.601
Use decimal instead of float.
A decimal(10,2) will have 2 and only 2 decimal places and can be compared in the same manner as integers.
Especially for monetairy values you should always use decimal, but anywhere where rounding errors are unwanted, decimal is a good choice.
See: http://dev.mysql.com/doc/refman/5.1/en/precision-math-decimal-changes.html
Or
MySQL DECIMAL Data Type Characteristics
Today, I also came across the same situation and get resolved just by using FORMAT function of MySQL, It will return the results that exactly match your WHERE clause.
SELECT * FROM yourtable WHERE FORMAT(`col`,2) = FORMAT(value,2)
Explanation:
FORMAT('col name',precision of floating point number)
Hope it helps.
You can also try query
SELECT * FROM table WHERE value LIKE 4.6;
you write:
SELECT * FROM table where round(value, 1) = 4.6

how to query a blob data

I have a table like :
------------------------------
Test_Id Test_data
(String) (blob)
------------------------------
I want a query to retrieve all the Test_Id's for a matching Test_data.
To achieve something like : select * from test_table where Test_data = blobObject;
How can we do above ??
First: there's no such thing as a string in MySQL. Only char/varchar/text.
Well you could cast it as char for comparison like this:
select * from test_table where Test_data = CAST( blobObject AS CHAR );
what's probably better is to convert your string to a binary string, but this might not give you the right comparison if you expect string comparison behaviour... well best you have a look at the char functions here:
http://dev.mysql.com/doc/refman/5.0/en/cast-functions.html
You can use a hash function such as MD5
SELECT * FROM example_table WHERE MD5(blob_column) = 'a6a7c0ce5a93f77cf3be0980da5f7da3';
MySQL has data types which can store binary data. Not only char/varchar/text, but also BINARY/VARBINARY/BLOB.
See http://dev.mysql.com/doc/refman/5.5/en/blob.html
And it's usage is as simple as normal string type. But, escaping is required. and query length is must specified because binary data may contain NULL character in their contents.
Before MySQL 3.23 (I guess), There were only mysql_query(), mysql_escape_string(). Those function has no capability specifying query length. after BLOB has been introduced in MySQL, mysql_real_query() and mysql_real_escape_string() supported.
I found some examples for you. May this links help you!
http://zetcode.com/db/mysqlc/
http://bytes.com/topic/c/answers/558973-c-client-load-binary-data-mysql