cast from varchar to long - mysql

i need to cast from varchar(100) to bigint that way:
select max(cast(referencia_factura as bigint))from ventas;
but i get a syntax error. ¿how can i solve it?
I need to get the maximum value of the "referencia_factura" field but I need to cast it to bigint.

A simple method is to use implicit conversion:
select max(referencia_factura + 0)
from ventas
Unfortunately, MySQL does not support direct conversion to bigint.

As it is explained in Cast Functions and Operators, casting to BIGINT is not supported by MySql.
I guess that referencia_factura's values are too long so they can't be converted to UNSIGNED and also an implicit conversion like referencia_factura + 0 would fail.
In this case what you can do is left pad the column values with 0s up to the max length of the column which is 100 and compare them as strings to find the maximum and then trim all the leading 0s:
SELECT TRIM(LEADING '0' FROM MAX(LPAD(referencia_factura, 100, '0')))
FROM ventas;
See the demo.

Related

SQL ignoring string in where condition

Why if I run a query with gibberish at the end of the where condition it incorrectly returns a result.
Example:
SELECT * FROM contractor_table WHERE contractorID = '97sd'
I am getting the row with the ID 97, when I should get no result.
What is happening here is that you are comparing the contractorID column, which is integer or some other numeric type, against a string literal 97sd. This doesn't make any sense, so MySQL, based on its casting rules, attempts to first cast 97sd to an integer. Consider the result of the following query:
SELECT CAST('97sd' AS unsigned);
In fact, this outputs just 97, the integer. So, in practice this means that the "gibberish" at the end of your string literal, which begins with an integer, will be ignored by MySQL.
But best practice here is to always compare columns against the correct literal types. So use the following version always, for best results:
SELECT * FROM contractor_table WHERE contractorID = 97;
This happends when you have column type int or other numeric if you convert it into varchar than it will retun no output

MySQL MAX returns incorrect result

I have a table where the 'text' column (using the text datatype) has numeric values between 0-2000.
When I execute the following MySQL function below, the query results a value of 990 instead of 2000. Could anybody think why this might be?
Thanks in advance:
SELECT max(text) FROM table
Convert the text field to unsigned int first.
select MAX(cast(`text`as unsigned)) from `table`;
You will have to convert the type of text to a number prior to passing it into max().
For example: select max(cast(text as integer)) from table
This may fail if not all the values in text are numeric.
It's definitely not an "incorrect" result. Per the documentation:
MAX() may take a string argument; in such cases, it returns the
maximum string value.
And "990" definitely comes after "2000" when they're strings.
you have set the column in text type,so they are compared in text type(990 is bigger than 2000).you should compare them in numeric type,you can do it like SELECT max(text*1) FROM table

MySQL automatic string to integer casting in where clause?

I am not new to MySQL but a strange situation happened in my code today coincidently which got me surprised. Can someone explain why this gives me identical results?
SELECT * FROM `products` WHERE id = 12
and
SELECT * FROM `products` WHERE id = '12ABC'
In both cases I get the same result with the same record being selected. I would expect that second one would return me nothing?! My ID field is int(11) unsigned with auto_increment flag turned on.
From MySQL docs:
When an operator is used with operands of different types, type conversion occurs to make the operands compatible
Documentation
So basically, '12ABC' is cast to 12.
MySQL has to make a conversion to make a compare betwen 2 different types. It tries to make the string to an int and get the digits from the string starting from the beginning.
It you had for instance
'ABC12'
the result of the string conversion to int would be 0

SQL statement convert varchar to integer

I was having some problem when trying to convert varchar field in MySQL to integer using SQL statement:
SELECT mrtpopTime, CONVERT(INT,mrtpopAmt)
FROM tm_mrtpop
WHERE mrtpopName = ''
ORDER BY CONVERT(INT, mrtpopAmt) DESC
I am trying to get the top 3 records when mrtpopAmt was arranged in a way where it is in reverse order. However, I am getting error message at the INT and the error message is:
Syntax error, Unecpected INT_SYM
I wonder why is it so? Thanks in advance.
This is because MySQL doesn't use CONVERT() for casting. It uses the CAST function. In your case you would use:
CAST(mrtpopAmt AS SIGNED) -- This can also be UNSIGNED if it will always be a positive integer

MySQL loose comparison, WHERE on varchar field with integer value yields unexpected result

I recently discovered an interesting bug in a program, which selects data for a specific customer using their private key. Consider the following:
SELECT `id` FROM (`customers`) WHERE `authenticationKey` = '#09209!ko2A-' LIMIT 1
The key is provided at request-time, and properly sanitized before put to query. However, failing to providing a key (which should be caught before; ignore that), would yield a query similar to the following:
SELECT `id` FROM (`customers`) WHERE `authenticationKey` = 0 LIMIT 1
Which would return a row from the customers-table - despite it having a proper, string, key stored, such as in the first example.
The authenticationKey-field is of the type VARCHAR(1024).
My guess is that this has something to do with loose comparasion. What is causing this problem, and how can it properly be avoided?
MySQL will try and coerce data to a comparable type. I this case it will try and convert strings to numbers. Any strings that it can't make sense of default to 0.
Do
select 0 = 'banana'
to see this in action.
Making your query compare to '0' instead of 0 would fix it.
Example SQLFiddle
MySQL implicitly converts the leading chars of authenticationKey to int until it finds a char that's not a valid number. I guess all rows that start with a non-numeric char are treated as 0.
For instance, this yields 'b', since the coerced int value is 1:
select (case when '1abc' = 0 then 'a' else 'b' end);
But this yields 'a', since the leading char isn't a valid number, so the coerced int value is 0:
select (case when '#1abc' = 0 then 'a' else 'b' end);
This should be avoided by the application. Why you query with 0 when no key is given, after all?