SQL READING THE COLUMN VALUES? - mysql

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;

Related

SQL - Want to output the ones with the same first name but different last name. Full name in the same column

How do i go on about on a query for where i wanna extract the same first name but the last name is different?
NAME
------
Chris Stutter
Chris Lamb
Alfred Dark
Kristine Light
output:
Chris Stutter
Chris Lamb
I've made a script for you for this specific condition. Based on the info you shared, I've created the test scripts below. You can test this script and see the result really quickly at https://onecompiler.com/mysql/
-- create
CREATE TABLE YOUR_TABLE (
Name TEXT NOT NULL
);
-- insert
INSERT INTO YOUR_TABLE VALUES ('Chris Stutter');
INSERT INTO YOUR_TABLE VALUES ('Chris Stutter');
INSERT INTO YOUR_TABLE VALUES ('Chris Stutter');
INSERT INTO YOUR_TABLE VALUES ('Chris Lamb');
INSERT INTO YOUR_TABLE VALUES ('Alfred Dark');
INSERT INTO YOUR_TABLE VALUES ('Alfred Dark');
INSERT INTO YOUR_TABLE VALUES ('Kristine Light');
-- fetch
SELECT DISTINCT *
FROM YOUR_TABLE
WHERE SUBSTRING_INDEX(Name, ' ', 1) IN (
SELECT *
FROM (
SELECT SUBSTRING_INDEX(Name, ' ', 1) as firstName
FROM YOUR_TABLE
GROUP BY firstName
HAVING COUNT(DISTINCT Name) > 1
) AS DuplicatedFirstNames
);
You should be able to utilize this fetch script as a reference and modify it accordingly for your own purpose now.
You want to work with first name and last name in your database, but your table doesn't provide that information. It only has a column for the full name. This means that your database design is not appropriate for the task. The information you seek is not stored atomic, but in a concatenated form and thus violates the first normal form. (This also shows that database normalization sometimes depends on how you want to work with the data.) The best way to deal with this problem is hence to change your database and make first and last name separate columns.
If you cannot change the database design, the first task is to find out in which formats the names are stored. So far you have shown "first name - one blank - last name". If this is the only format, then it is rather easy to split the two. If, however, you also have to deal with 'Smith, John' or 'Arthur Conan Doyle', it gets more complex. Let's say all names are in the same format. So, split first name and last name and work with these.
Once you have separate first and last name, the task becomes easy. You are looking for names for which exists another last name with the same first name, i.e. use EXISTS.
WITH names AS
(
SELECT
SUBSTRING_INDEX(name, ' ', 1) AS first_name,
SUBSTRING_INDEX(name, ' ', -1) AS last_name
FROM mytable
)
SELECT first_name, last_name
FROM names
WHERE EXISTS
(
SELECT NULL
FROM names other
WHERE other.first_name = names.first_name
AND other.last_name <> names.last_name
)
ORDER BY first_name, last_name;

I have a column "POLICY_RATE_AMOUNT" WHICH IS IN VARCHAR DATATYPE AND IT HOLDS THE DOLLAR VALUE

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

Avoid row was cut by GROUP_CONCAT error on insert without changing group_concat_max_len

I have an insert that uses a GROUP_CONCAT. In certain scenarios, the insert fails with Row XX was cut by GROUP_CONCAT. I understand why it fails but I'm looking for a way to have it not error out since the insert column is already smaller than the group_concat_max_len. I don't want to increase group_concat_max_len.
drop table if exists a;
create table a (x varchar(10), c int);
drop table if exists b;
create table b (x varchar(10));
insert into b values ('abcdefgh');
insert into b values ('ijklmnop');
-- contrived example to show that insert column size varchar(10) < 15
set session group_concat_max_len = 15;
insert into a select group_concat(x separator ', '), count(*) from b;
This insert produces the error Row 2 was cut by GROUP_CONCAT().
I'll try to provide a few clarifications -
The data in table b is unknown. There is no way to say set group_concat_max_len to a value greater than 18.
I do know the insert column size.
Why group_concat 4 GB of data when you want the first x characters?
When the concatenated string is longer than 10 chars, it should insert the first 10 characters.
Thanks.
Your example GROUP_CONCAT is probably cooking up this value:
abcdefgh, ijklmnop
That is 18 characters long, including the separator.
Can you try something like this?
set session group_concat_max_len = 4096;
insert into a
select left(group_concat(x separator ', '),10),
count(*)
from b;
This will trim the GROUP_CONCAT result for you.
You temporarily can set the group_concat_max_len if you need to, then set it back.
I don't know MySQL very well, nor if there is a good reason to do this in the first place, but you could create a running total length, and limit the GROUP_CONCAT() to where that length is under a certain max, you'll still need to set your group_concat_max_len high enough to handle the longest single value (or utilize CASE logic to substring them to be under the max length you desire.
Something like this:
SELECT SUBSTRING(GROUP_CONCAT(col1 separator ', '),1,10)
FROM (SELECT *
FROM (SELECT col1
,#lentot := COALESCE(#lentot,0) + CHAR_LENGTH(col1) AS lentot
FROM Table1
)sub
WHERE lentot < 25
)sub2
Demo: SQL Fiddle
I don't know if it's SQL Fiddle being quirky or if there's a problem with the logic, but sometimes when running I get no output. Not big on MySQL so could definitely be me missing something. It doesn't seem like it should require 2 subqueries but filtering didn't work as expected unless it was nested like that.
Actually, a better way is to use DISTINCT.
I had a situation to add new two fields into existing stored procedure, in a way that a value for that new fields had been obtained by a LEFT JOIN, and because it may have contained a NULL value, a single "concat" value was multiplicated for some cases more than a 100 times.
Because, a group with that new field value contained many NULL values, GROUP_CONCAT exceeded maximum value (in my case 16384).

Converting VARCHAR to DECIMAL values in MySql

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

Remove a single character from a varchar field SQL Server 2008

I have a table with several varchar columns that are almost identical to primary keys I have in another table, with the exception of a period (.). I've looked at the replace function in T-SQL but the first argument isn't an expression. How can I remove all occurrences of a particular character with SQL? It seems like the correct answer might be to replace with a zero length string. Is that close?
To whomever felt the question didn't exhibit research effort it was mainly due to a misunderstanding of the documentation itself.
You can update the table directly using REPLACE on the column values:
UPDATE myTable
SET myColumn = REPLACE(myColumn, '.', '')
Do you want to remove all instances of the . from the string? If so, you were right about REPLACE:
DECLARE #Example TABLE
(
Value VARCHAR(100)
)
INSERT #Example (Value)
VALUES ('Test.Value'), ('An.otherT.est')
SELECT
REPLACE(Value, '.', '')
FROM
#Example
-- Replace only the first '.'
SELECT
STUFF(Value, CHARINDEX('.', Value, 0), 1, '')
FROM
#Example
Edit, making the example a little more useful since I played around with it anyway, I might as well post the example. :)
update your_table
set some_column = replace(some_column, '.', '')