I have imported a CSV file that contains string values (eg.eating) and floating values (eg. 0.87) into a table in my phpMyAdmin database. After I get ride of all the string values and retain only the rows that have the decimal values, I need to convert such values from VARCHAR to DECIMAL/FLOAT so that I can perform a MAX() on this attribute.
How do I do this? Each time I try doing this through the GUI in phpMyAdmin, all my values are automatically rounded off to 0 and 1s.
Please help me!
Without Converting you can find Maximum using this query
select max(cast(stuff as decimal(5,2))) as mySum from test;
check this SQLfiddle
your demo table:
create table test (
name varchar(15),
stuff varchar(10)
);
insert into test (name, stuff) values ('one','32.43');
insert into test (name, stuff) values ('two','43.33');
insert into test (name, stuff) values ('three','23.22');
Your Query:
For SQL Server, you can use:
select max(cast(stuff as decimal(5,2))) as mySum from test;
Be aware that if you convert from VARCHAR to DECIMAL and do not specify a precicision and maximum number of digits (i.e. DECIMAL instead of DECIMAL(5,2)) MySQL will automatically round your decimals to integer values.
I think you need to try doing something like this on your MySQL if you have admin privilege on your MySQL.
ALTER TABLE tablename MODIFY columnname DECIMAL(M,D)
for the M,D variables, read this - http://dev.mysql.com/doc/refman/5.0/en/fixed-point-types.html
And MySQL should be able to automatically converting a text to a numeric. Just that the data type in MySQL might not be a decimal yet that's why you can't store any decimal.
Hope it may help someone
select convert( if( listPrice REGEXP '^[0-9]+$', listPrice, '0' ), DECIMAL(15, 3) ) from MyProduct WHERE 1
Related
0.0.0.1 saved in sql table column as 10001.
MY data base contains values as such above mentioned i wanted to sort it based on the values but if I sort is as it is it will give me wrong order so i need tp convert it to the above mentioned format(10001). i.e. Remove the dots(.)
Thank you.
(I guess you're actually using Oracle as a database, regarding the tool - Oracle SQL Developer - you've also tagged, which means that MySQL tag should be removed).
To me, it looks as if you'd want to a) remove dots, b) change datatype to number (so that it is correctly sorted):
order by to_number(replace(col, '.', ''))
It presumes that only characters allowed are digits and dots. If there's a value like 'A.0.0.1', it'll - of course - fail, as you can't convert letter A to a number.
Why are you storing the period '.' Character to begin with? If it's not needed you can remove it.
If you want to remove all non-alphanumeric characters you could use a regular expresion.
create table t (nm varchar2(20));
insert into t values ('.0.0.0.1');
insert into t values ('10.0.1.1.0');
commit;
select * from t;
NM
.0.0.0.1
10.0.1.1.0
update t
set nm = regexp_replace(
regexp_replace(nm, '[^A-Z0-9 ]', ''),
' {2,}', ' '
);
select * from t;
NM
0001
100110
You can use the translate command with a SELECT and the data will not be charged in the table.
See below
create table t (nm varchar2(20));
insert into t values ('.0.0.0.1');
insert into t values ('10.0.1.1.0');
commit;
SELECT translate(nm, '*.','*') from t
TRANSLATE(NM,'*.','*')
0001
100110
SELECT DISTINCT(column_name)
FROM Table_name
ORDER BY
TO_NUMBER (REGEXP_SUBSTR (column_name, '\d+',1,2)),
TO_NUMBER (REGEXP_SUBSTR (column_name,'\d+',1,3)) NULLS FIRST,
TO_NUMBER (REGEXP_SUBSTR (column_name,'\d+',1,4)) NULLS FIRST;
Im trying to pull bunch of records from MySQL with condition whether the column value contains 0. If I convert to string and check with contains (%0%), it takes more time to execute.. Is there any short way to check on Integer column? Thank you..
You can probably run a regex on the integer column. Something like below.
SELECT fieldname FROM tablename WHERE fieldname REGEX '[0]';
About the performance, I believe that LIKE is faster than REGEX. But since your LIKE involves string conversion, this would have some difference in execution time
#SriniK You can use either POSITION() or LOCATE() in conjunction with CONVERT() to convert the column value into a string and then find if the string "0" exists within the string. Both of these functions return a positive number greater than 0 indicating the index of the substring within your string and they return a 0 if the string isn't found.
Here's how to create a simple test table to illustrate:
CREATE TABLE `testTable` (`id` INTEGER NOT NULL AUTO_INCREMENT, `someNum` INTEGER, PRIMARY KEY(`id`));
INSERT INTO `testTable` (`someNum`)
VALUES
(1),
(10),
(11),
(100),
(111),
(222),
(210);
And here are two queries illustrating both POSITION() and LOCATE():
SELECT `id`,
`someNum`,
POSITION('0' IN CONVERT(`someNum`, CHAR))
FROM `testTable`
WHERE POSITION('0' IN CONVERT(`someNum`, CHAR)) > 0
;
SELECT `id`,
`someNum`,
LOCATE('0', CONVERT(`someNum`, CHAR))
FROM `testTable`
WHERE LOCATE('0', CONVERT(`someNum`, CHAR)) > 0
;
I have mocked this up on dbfiddle here so you can get a better look at it.
If this doesn't get you what you need or if you don't understand something please leave a comment with details and I'll do what I can to help further. Good luck.
Now i want to add a thousand separator to that column.
but when i add this query to that column
select REPLACE(CONVERT(VARCHAR,CONVERT(MONEY,POLICY_RATE_AMOUNT),1), '.00','') from table
i am getting this error
cannot convert a char value to money.
Please help
First of all: Always use appropriate types to store your values!
Secondly: Never use (n)char (same with (n)varchar) without a size! (Aaron Bertrand: Bad habits to kick)
Third: Never store information, which is just a formatting issue together with the value (the dollar symbol).
Now check this
SELECT CONVERT(MONEY,'$1234.56') --This works. The leading "$" is ignored.
SELECT CONVERT(MONEY,'1234.56$') --Breaks with your error message
As a repair fix you can use replace to get rid of the symbol:
select REPLACE(CONVERT(VARCHAR,CONVERT(MONEY,REPLACE(POLICY_RATE_AMOUNT,'$','')),1), '.00','') from xyz
If the $ is after the value, like 100$ then below query will help in converting.
create table #tmp (POLICY_RATE_AMOUNT varchar(10))
insert into #tmp values ('$100'),('-$150')
select REPLACE(CONVERT(MONEY,RIGHT(POLICY_RATE_AMOUNT,LEN(POLICY_RATE_AMOUNT)-1)), '.00','')
FROM #tmp
WHERE LEN(POLICY_RATE_AMOUNT)=LEN(REPLACE(POLICY_RATE_AMOUNT,'-',''))
UNION ALL
select REPLACE(CONVERT(MONEY,RIGHT(POLICY_RATE_AMOUNT,LEN(POLICY_RATE_AMOUNT)-1)), '.00','')
FROM #tmp
WHERE LEN(POLICY_RATE_AMOUNT)!=LEN(REPLACE(POLICY_RATE_AMOUNT,'-',''))
drop table #tmp
I am using MySQL database.
I have one table having column with datatype binary(16).
I need help with the insert statement for this table.
Example:
CREATE TABLE `assignedresource` (
`distid` binary(16) NOT NULL
)
insert into assignedresource values ('9fad5e9e-efdf-b449');
Error : Lookup Error - MySQL Database Error: Data too long for column 'distid' at row 1
How to resolve this issue?
You should remove the hyphens to make the value match the length of the field...
Example:
CREATE TABLE `assignedresource` (
`distid` binary(16) NOT NULL
)
insert into assignedresource values ('9fad5e9eefdfb449');
Also, MySQL standard is to use this notation to denote the string as binary... X'9fad5e9eefdfb449', i.e.
insert into assignedresource values (X'9fad5e9eefdfb449');
Well, assuming that you want to strictly insert a hexadecimal string, first you need to remove the dashes and then "unhex" your string before inserting it into a binary(16) data type column, the code would go like this:
INSERT INTO `assignedresource` VALUES(UNHEX(REPLACE('9fad5e9e-efdf-b449','-','')));
Also... the "usable" data you are inserting is actually 8 bytes after undashing it, so binary(8) would do fine if you plan on not storing the dashes.
You can strip the hyphens and perpend 0x to the value unquoted, like this:
insert into assignedresource values (0x9fad5e9eefdfb449);
As well as, as this (mentioned in other answers):
insert into assignedresource values (X'9fad5e9eefdfb449');
Both are valid notation for a hexadecimal literal.
Your string is 18 char long, change the database
CREATE TABLE `assignedresource` (
`distid` binary(18) NOT NULL
)
I need to store binary data, such as 1110000, in MySQL. When I select it, I need the return value to be the same 1110000 again.
What data type should I use? Can I use bit? Or would varbinary be better?
When you're dealing with binary numbers you can use a bit field, e.g.:
bit(64)
is a bit field with up to 64 significant bits (the maximum size allowed).
In order to insert constant values, you can use the b'value' notation like so:
insert into bits values (b'0001001101001');
You can convert a bit field to a number by just adding 0 or using cast(). There's also the handy bin(), hex(), and oct() function to print the value in a particular base.
If non-numeric, varbinary or blob would be the most efficient storage method, binary is also available (it will pad shorter values with nil bytes tho).
In case, you don't want to deal with the conversions, you can store the string in a varchar or char. It will only use up about 8 times the space of a compact varbinary.
To insert/read from your app, you'll need to convert your sequence into a packed byte array, then store the packed string in the varbinary column. In C# you might use BitConverter, for php you might use pack/unpack.
Hope, this code can help you:
for select:
select conv(column_name, from_base, to_base) from table_name
//example:
select conv(column1, 10, 2) from table1;
for insert:
insert into table_name(column1) values( B'binary_data') ;
//example :
insert into table1(column1) values( B'1110000');
for query:
select column1,column2 from table_name where column1 & B('binary_data');
//example:
select column1, column2 from table1 where column1 & B('1110000');