SQL Update statement truncated incorrect double value error - mysql

I'm trying to update my table column values into a string. My query goes like this
UPDATE tbl_testing
SET result= 'Hey'
WHERE (SELECT (colOne) + '-' + (colTwo) + '-' + (colThree)) = 'r-r-r'
which the columns 'colOne, colTwo and colThree' already contains 'r' but slqyog shows "Truncated incorrect DOUBLE value: 'r-r-r'"
and all of the other result column data became = 'Hey'. What should I do?

You have to decide it is either MySQL or MSSQL.
In MySQL the string concatenation is not + sign, but simply you enumerate the columns separated by comma and the statement is SELECT CONCAT("Field1", "Field2" etc) AS ConcatenatedString); - CONCAT() function.
Try reevaluate your DB engine and adapt the query.
In MSSQL the string concatenation is indeed + sign. Your query works ok in MSSQL and updates the result column with the value you have set.
DDL
CREATE TABLE [dbo].[tbl_testing](
[id] [int] NULL,
[result] [nvarchar](4000) NULL,
[colOne] [nvarchar](4000) NULL,
[colTwo] [nvarchar](4000) NULL,
[colThree] [nvarchar](4000) NULL
) ON [PRIMARY]
GO
INSERT INTO tbl_testing (id, colOne, colTwo, colThree)
VALUES (1, 'r', 'r', 'r')
Update statement
UPDATE tbl_testing
SET result='Hey. I am a concatenated string'
WHERE (SELECT (colOne)+'-'+(colTwo)+'-'+(colThree))='r-r-r'
Output
id result colOne colTwo colThree
1 Hey. I am a concatenated string r r r

Changing comment to answer:
You should avoid doing that statements in that way. By doing that, database use no indexes and also you are giving more computation tasks to database server (server needs to concatenate all values and after concatenations will compare with given string).
Better way is to replace yours where statement with something like:
`WHERE colOne = 'r' AND colTwo = 'r' AND ...`
that will work faster without additional computation need (to concatenate strings).
This solution works much much faster, and looks much much better.

Related

get 0 when emptyornull values else max(id) when column datatype is numeric in sql server

Hi I have one doubt in sql server
get 0 when emptyornull values else max(id) when column datatype i is numeric in sql server
Table : empid
CREATE TABLE [dbo].[empid](
[id] [numeric](11, 0) NULL
) ON [PRIMARY]
GO
INSERT [dbo].[empid] ([id]) VALUES (NULL)
GO
INSERT [dbo].[empid] ([id]) VALUES (CAST(6 AS Numeric(11, 0)))
GO
based on above data I want output like below
id
6
I tried like below
select case when isnull( max(id),'')='' then cast (0 as numeric) else max(id end test from )
[Test].[dbo].[empid]
but above query is getting error
Msg 8114, Level 16, State 5, Line 9
Error converting data type varchar to numeric.
suppose no records in table then maxid will get 0
please tell me how to write a query to achive this task in sql server
You should use the COALESCE function that gives you the ability to replace a potential NULL with whatever you wish (0 in your current case) as so:
select coalesce(id, 0) as id from [dbo].[empid];
Why use ''? Just use 0:
SELECT ISNULL(id,0) AS test
FROM dbo.empid;
ISNULL returns the datatype of the first parameter, and with the SQL you had, you were therefore implicitly trying to convert '' to a numeric, which was failing.
The better way to do this is to use COALESCE function provided by SQL
COALESCE(arg1, arg2[, argN])
what it does is it takes N arguments
arg1 is a column that can be null
arg2 is a column that can be null
argN is the value that you want to replace it with
Query could be
SELECT COALESCE(Id, 0) as Id FROM [dbo].[empid]

Why MySQL "WHERE" clause approximation: retrieves values even the condition is not met

I have a table which primary key is numeric and auto-incremented.
When I run a query such as:
SELECT * FROM my_table where id = '1a';
The query returns the row with the primary key set to "1".
I was not aware of this behavior, is it possible to prevent it?
I was expecting this WHERE clause to retrieve nothing since the id is "1" and not "1a". It is behaving like it was a LIKE clause.
MySQL implicitly converts a String literal to int while comparing with an int column.
You should really fix your application code (eg: PHP), and properly typecast to (int) before using them in a query. Ideally, your application should not have been inputting string values to compare against an integer field.
Now still, if you don't have control over input value, an approach can be to check if the value is numeric or not, and use it accordingly for comparison. Adapting a sargable approach from https://dba.stackexchange.com/q/89760/160363
SELECT * FROM my_table
WHERE id = CASE WHEN CONCAT('','1a'*1) = '1a' THEN '1a' ELSE NULL END;
mysql automatically converts strings to numbers, and just takes the leading characters that are digits. You could instead explicitly cast the ID to a string:
SELECT * FROM my_table where CAST(id AS CHAR) = '1a';

MySQL regular expression to select the last integer in the string

I have a MySQL database table that contains column run that is an integer and another column filename that is a varchar with typical values like RUN0001.FTS or 3DS0231.FTS or 3RUN0010.FTS
I need to check the values in the run and filename columns. The prescription is I extract the last integer (without leading zeroes) before the dot character (.) in the filename column, and compare it to the value of the run column. How do I write a select statement to do this comparison to return the rows that will not have the matching integers?
For example, a regular expression I am trying to build would extract 1 from RUN0001.FTS, or 231 from 3DS0231.FTS, or 10 from 3RUN0010.FTS and then compare it to the value in the run column, and return the primary key if the two don't match.
In Python I would manipulate the variable filename = '3RUN0010.FTS' like so:
import re
filename = '3RUN0010.FTS'
fileRunNumber = re.findall('\d+', filename)
runNumber = int(fileRunNumber[-1])
print "The integer I want is", runNumber
How do I do this in as a MySQL statement?
Thanks,
Aina.
You can try the following query:
SELECT CAST(SUBSTRING(col, INSTR(col, '.') - 4, 4) AS UNSIGNED) AS theNumber
FROM yourTable
Data:
CREATE TABLE yourTable (col varchar(55));
INSERT INTO yourTable (col)
VALUES
('RUN0001.FTS'),
('3DS0231.FTS'),
('3RUN0010.FTS');
Output:
Demo here:
Rextester

MySQL 5.7 date field trouble

I have installed recently MySQL 5.7 . Something weird is happening with a date column.
If I execute a SELECT query using that field in a WHERE section, I have a resultset, but when I use the same WHERE condition to UPDATE a row I get an Invalid date format error message.
Here is the SELECT sentence:
SELECT *
FROM
FDpoCargTran
WHERE FDpoCargTran.Banco = '001'
AND (FDpoCargTran.Conciliacion = '' OR FDpoCargTran.Conciliacion IS NULL)
AND FDpoCargTran.Fecha = '2016-09-27'
This sentence returns 2 rows resultset, that's ok.
Now, Here's the UPDATE sentence:
UPDATE
FDpoCargTran
SET
Edo = 'C'
WHERE FDpoCargTran.Banco = '001'
AND (FDpoCargTran.Conciliacion = '' OR FDpoCargTran.Conciliacion IS NULL)
AND FDpoCargTran.Fecha = '2016-09-27'
AND Deposito = 1041
And I get this error message:
Data truncation: Incorrect date value: '' for column 'Conciliacion'
The Conciliacion columns is defined as:
`Conciliacion` date DEFAULT NULL,
If I remove the Conciliacion = '' condition, everything works fine.
Why empty string is not valid to evaluate the column in an UPDATE sentence and not in a SELECT?
Please, an idea!!!
Basically, for date datatype, you cannot store something like White
Spaces or ' ' strings. You need to make the column to accept NULL
values and insert an actual NULL into it. This is not a problem in MySQL 5.7, its how date is set in databases.
Update is a DML statement, when you actually want to write something into table, or check for a condition, MySQL is unable to understand what ' ' is for the date column type.
So, you cannot have ' ', instead you can have NULL set. Thats how MySQL can check the condition and make appropriate changes!!
I would suggest, change it to NULL.
Alter your datetime column to varchar.
Import whatever table/database.
Update FDpoCargTran set Conciliacion=NULL where Conciliacion='';
Alter column back to datetime.

how to frame a sql query to check if the value of the column is all spaces

I have only spaces as values of rows in a column of length 121 chars.
I want to write a query in oracle to check whether the column string is only spaces.
for e.g. if say for column address. a row contains only spaces(all 121 chars are spaces).
i want a query that will check if the row contains only spaces.
select * from table where address <> ' ';
but this isnt working it only checks for 1 space. i want the query to check for all 121 spaces.
You could just run a TRIM on the column. Depending on your DBMS, the Null string is treated as either a NULL or as an empty string ''. But for Oracle where the empty string is treated as a NULL, you should be able to do:
select * from table where LTRIM(RTRIM(address)) IS NOT NULL
Note that TRIM removes all whitespace, not just the space character.
If you're checking for 121 spaces as a learning exercise then that's OK, but if you're storing 121 spaces in a column for a production application you may have a bad design.
If the column type is CHAR it should probably be changed to VARCHAR (or VARCHAR2 in Oracle). If it already is VARCHAR/VARCHAR2 you should store an empty string as, well, an empty string.
If you need the value padded to 121 spaces, take care of that when you query it:
Oracle: SELECT RPAD(NVL(address, ' '), 121) FROM myTable
MySQL: SELECT RPAD(address, 121, ' ') FROM myTable
If you want to find out if the value is empty, remember that Oracle treats an empty string as NULL. MySQL treats it as an empty string:
Oracle: SELECT * FROM myTable WHERE address IS NULL
MySQL: SELECT * FROM myTable WHERE address = ''
use REPLACE() function and compare it's result to null
SELECT * FROM table WHERE REPLACE(address,' ') IS NULL;
Fiddle