Make column values in a table have equal number of characters - sql

I have a table DomainDetail having a column fieldID.
It has values like A1,B22,A567,D7779,B86759 .. i.e. from two characters to max six characters.
I want these values have equal number of characters
A000001,B000022,A000567,D07779 and B86759 .
This is how I think I should proceed
Estimate size of field value = LEN(fieldID)
Insert number of zeros equal to (6 - number of characters) .
How can I insert 0's sandwiched inside original value . How can do in SQL ?

like this
select
left(fieldID, 1) +
right('000000' + right(fieldID, len(fieldID) - 1), 5)
from DomainDetail
take a look at SQL FIDDLE example

It sounds like a problem better solved by business logic, i.e. the layer of code above your database. Whenever you insert, do the padding in that code - then always use that code/layer to insert into the table.
It seems to be a business logic requirement anyway - "ID must have a maximum 6 characters". Because a database wouldn't impose such a limit.
(unless you are using stored procedures as your business logic layer? in which case, PadLeft function in T-SQL)

select
stuff(fieldId,2,0,
LEFT('0000000000000000000000000',
(select max(LEN(FieldID)) from DomainDetail)
-LEN(fieldId)))
from DomainDetail
If you need a fixed output length just replace inner select (select max(LEN(FieldID)) from DomainDetail) with for example 6
Here is a SQLFiddle demo

If you want to UPDATE, then use this
UPDATE DomainDetail
SET fieldId=
SUBSTRING(fieldId,1,1)+
REPLICATE('0',6-LEN(id))+
SUBSTRING(fieldId,2,LEN(id)-1)
If you want to just SELECT without altering the values in the table, then this should work
SELECT SUBSTRING(id,1,1)+
REPLICATE('0',6-LEN(id))+
SUBSTRING(id,2,LEN(id)-1)
FROM DomainDetail
Hope this helps,
Raj

select stuff(fieldid, 2, 0, replicate('0', 6-len(fieldid)))
from DomainDetail

Related

Count all elements in an array

I have a table that I save some data include list of numbers.
like this:
numbers
(null)
،42593
،42593،42594،36725،42592،36725،42592
،42593،42594،36725،42592
،31046،36725،42592
I would like to count the number elements in every row in SQL Server
count
0
1
6
4
3
You could use a replacement trick here:
SELECT numbers,
COALESCE(LEN(numbers) - LEN(REPLACE(numbers, ',', '')), 0) AS num_elements
FROM yourTable;
The above trick works by counting the number of commas (assuming your data really has commas as separators). For example, your last sample data point was:
,31046,36725,42592 => length is 18
310463672542592 => length is 15
Hence the difference in lengths correctly yields the right number of elements.
Another idea is to useSTRING_SPLIT:
SELECT y.numbers,
(SELECT COUNT(Value) - 1
FROM string_split(COALESCE(y.numbers,''),',')) AS num_elements
FROM yourtable AS y;
I know this looks a bit unhandy on first glance due to this strange -1 in the second line and the COALESCE in the third line. So why do I talk about this option?
Well, the strange thing in your case which causes these difficulties in my query is that your rows always start with a comma.
This is quite weird and it would be much easier without this first comma in every row.
Let's assume you remove this comma in future. Then this will become really easy and good readable:
SELECT y.numbers,
(SELECT COUNT(Value)
FROM string_split(y.numbers,',')) AS num_elements
FROM yourtable AS y;
Try out: db<>fiddle
your data
CREATE TABLE yourtable(
numbers VARCHAR(max)
);
INSERT INTO yourtable
(numbers) VALUES
(null),
('،42593'),
('،42593،42594،36725،42592،36725،42592'),
('،42593،42594،36725،42592'),
('،31046،36725،42592');
you need ISNULL and len
select
ISNULL(len(numbers) - len(replace(numbers,'،','')) ,0) count
from yourtable
the other way is by using IIF and string_split as follows
SELECT IIF(count < 0, 0, count) count
FROM   (SELECT (SELECT Count(*) - 1
                FROM   STRING_SPLIT (Replace(Replace(numbers, 'R', ''), '،',
                                     'R'), 'R'
                       )) AS
               'count'
        FROM   yourtable) A
dbfiddle

SQL Query to compare the first X characters of 2 fields in a table

Say I have a table named 'Parts'. I am looking to create a SQL query that compares the first X characters of two of the fields, let's call them 'PartNum1' and 'PartNum2'. For example, I would like to return all records from 'Parts' where the first 6 characters of 'PartNum1' equals the first 6 characters of 'PartNum2'.
Parts
PartNum1
PartNum2
12345678
12345600
12388888
12345000
12000000
14500000
the query would only return row 1 since the first 6 characters match. MS SQL Server 2017 in case that makes a difference.
If they are strings, use left():
left(partnum1, 6) = left(partnum2, 6)
This would be appropriate in a where, on, or case expression. Note that using left() would generally prevent the use of indexes. If this is for a join and you care about performance, you might want to include a computed column with the first six characters.
you can try something like this. I am assuming datatype as integer. You can set size of varchar based on length of fields.
select *
from Parts
WHERE SUBSTRING(CAST(PartNum1 AS VARCHAR(max)), 1,6) = SUBSTRING(CAST(PartNum2 AS VARCHAR(max)), 1,6)
You can go for simple division to see if the numerator matches for those partnumbers.
DECLARE #table table(partnum int, partnum2 int)
insert into #table values
(12345678, 12345600)
,(12388888, 12345000)
,(12000000, 14500000);
select * from #table where partnum/100 = partnum2/100
partnum
partnum2
12345678
12345600

Can I combine like and equal to get data?

I have data like this
1234500010
1234500020
1234500021
12345600010
12345600011
123456700010
123456700020
123456710010
The pattern is
1-data(varian 3-7 digit number) + 2-data(any 3 digit number) + 3-data (any 2 digit number)
I want to create SQL to get 1-data only.
For example I want to get data 12345
I want the result only
1234500010
1234500020
1234500021
If I using "like",
select *
FROM data
where ID like '12345%' `
I will get all the data with 12345, 123456 and 1234567
If I using equal, I will only get one specific data.
Can I combine like and equal together to get result like what I want?
select * FROM data where data = '12345 + any 2-data(3 digit) + any 3-data(2 digit)'
Anyone can help?
Addition : Sorry if I didn't mention the data type and make some miss communication. The data type is in char. #Gordon answers and the others not wrong. It works for number and varchar. but not works for char type. Here I post some pic for char data type. Oracle specification for char data type is a fixed lenght. So if I input less than lenght the remain of it will be change into a space.
Thank you very much. Hope someone can help for this
Since your datatype is CHAR, Gordon's answer is not working for you. CHAR adds trailing spaces for the strings less than maximum limit. You could use TRIM to fix this as shown. But, you should preferably store numbers in the NUMBER type and not CHAR or VARCHAR2, which will create other problems sooner or later.
select *
from data
where trim(ID) like '12345_____';
I think you want:
select *
from data
where ID like '12345_____' -- exactly 5 _
Here is a rextester demonstrating the answer.
You really can't combine equality and LIKE. But you can use a regular expression to do this kind of searching, with the REGEXP_LIKE function:
SELECT *
FROM DATA
WHERE REGEXP_LIKE(ID, '^12345[0-9]{3}[0-9]{2}');
But if I understand correctly, for your 1-data you really want a 3 to 7 digit number:
SELECT *
FROM DATA
WHERE REGEXP_LIKE(ID, '^[0-9]{3,7}[0-9]{3}[0-9]{2}');
Oracle regular expression docs here
SQLFiddle here
Best of luck.
I think this gives you the solution you want,
create table data(ID number(15));
insert into data values(1234500010);
insert into data values(1234500020);
insert into data values(1234500021);
insert into data values(12345600010);
insert into data values(12345600011);
insert into data values(123456700010);
insert into data values(123456700020);
insert into data values(123456710010);
select * from data where ID like '12345_____'
// After 5_ underscore are exactly 5 , any 3 digits from 2-data(3 underscores) and 2 digits from 3-data(2 underscores)
You'll be getting(OUTPUT) :
ID
1234500010
1234500020
1234500021
3 rows returned in 0.00 seconds

How to find values with certain number of decimal places using SQL?

I'm trying to figure out a way, using SQL, to query for values that go out to, say, 5 or more decimal places. In other words, I want to see only results that have 5+ decimal places (e.g. 45.324754) - the numbers before the decimal are irrelevant, however, I still need to see the full number. Is this possible? Any help if appreciated.
Assuming your DBMS supports FLOOR and your datatype conversion model supports this multiplication, you can do this:
SELECT *
FROM Table
WHERE FLOOR(Num*100000)!=Num*100000
This has the advantage of not requiring a conversion to a string datatype.
On SQL Server, you can specify:
SELECT *
FROM Table
WHERE Value <> ROUND(Value,4,1);
For an ANSI method, you can use:
SELECT *
FROM Table
WHERE Value <> CAST(Value*100000.0 AS INT) / 100000.0;
Although this method might cause an overflow if you're working with large numbers.
I imagine most DBMSs have a round function
SELECT *
FROM YourTable
WHERE YourCol <> ROUND(YourCol,4)
This worked for me in SQL Server:
SELECT *
FROM YourTable
WHERE YourValue LIKE '%._____%';
select val
from tablename
where length(substr(val,instr(val, '.')+1)) > 5
This is a way to do it in oracle using substr and instr
You can use below decode statement to identify maximum decimal present in database table
SELECT max(decode(INSTR(val,'.'), 0, 0, LENGTH(SUBSTR(val,INSTR(val,'.')+1)))) max_decimal
FROM tablename A;

How can I use LEFT & RIGHT Functions in SQL to get last 3 characters?

I have a Char(15) field, in this field I have the data below:
94342KMR
947JCP
7048MYC
I need to break down this, I need to get the last RIGHT 3 characters and I need to get whatever is to the LEFT. My issue is that the code on the LEFT is not always the same length as you can see.
How can I accomplish this in SQL?
Thank you
SELECT RIGHT(RTRIM(column), 3),
LEFT(column, LEN(column) - 3)
FROM table
Use RIGHT w/ RTRIM (to avoid complications with a fixed-length column), and LEFT coupled with LEN (to only grab what you need, exempt of the last 3 characters).
if there's ever a situation where the length is <= 3, then you're probably going to have to use a CASE statement so the LEFT call doesn't get greedy.
You can use RTRIM or cast your value to VARCHAR:
SELECT RIGHT(RTRIM(Field),3), LEFT(Field,LEN(Field)-3)
Or
SELECT RIGHT(CAST(Field AS VARCHAR(15)),3), LEFT(Field,LEN(Field)-3)
Here an alternative using SUBSTRING
SELECT
SUBSTRING([Field], LEN([Field]) - 2, 3) [Right3],
SUBSTRING([Field], 0, LEN([Field]) - 2) [TheRest]
FROM
[Fields]
with fiddle
select right(rtrim('94342KMR'),3)
This will fetch the last 3 right string.
select substring(rtrim('94342KMR'),1,len('94342KMR')-3)
This will fetch the remaining Characters.