How to select only numeric values - sql

Table1
id
01
wire
02
steve
ram123
03
....
from the table1 i want to select only numeric values,
It should not display alphanumeric values like (ram123)
Expected Output
01
02
03
....
How to make a query for this condition

Try ISNUMERIC
SELECT *
FROM Table1
WHERE ISNUMERIC([ID]) = 1
SQLFiddle Demo

SELECT * FROM #Table
WHERE Col NOT LIKE '%[^0-9]%'

Just want to note that IsNumeric() has some limitations. For example all of the below will return 1.
SELECT ISNUMERIC(' - ')
SELECT ISNUMERIC(' , ')
SELECT ISNUMERIC('$')
SELECT ISNUMERIC('10.5e-1')
SELECT ISNUMERIC('$12.09')
So if you only looking to select numbers ONLY, then something like this could work:
create function [dbo].[IsNumbersOnly](#strSrc as varchar(255))
returns tinyint
as
begin
return isnumeric(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(
#strSrc, '\', 'x'), '-', 'x'), ',', 'x'), '+', 'x'), '$', 'x'), '.', 'x'), 'e', 'x'), 'E', 'x'),
char(9), 'x'), char(0), 'x'))
end

SELECT column1 FROM table where ISNUMERIC(column1) = 1

You can use translate and replace function together. first translate the numbers to 0 then replace them with null and return only null values can solve the problem.
select column from table where replace(translate(column,'0123456789','0000000000'),'0','') is null

I tried the code above (ISNUMERIC()) and it somehow doesn't work in Oracle SQL.
But I found a working solution for Oracle SQL:
SELECT column1
FROM Table
WHERE regexp_like( column1, '^[[:digit:]]*$');
From: https://community.oracle.com/thread/2394572

Related

How to find values that contains only 0's and any other digit for example 000000001 or 0000010001 or 010101 or 0002 or 02020 or 0090 etc.?

I want to find 'default type values' in SQL that is entered when something like an ID number of company registration number is entered. Some of the values I see is a combination of 0's and another digit from 1-9. Examples I have seen is 00000001, 0000100, 000000002, 000001111, 0000090009, etc. The values vary in length also. Is there a way to find these values without hard coding? The value should contain at least one 0 and one or more of any other digit.
You want all strings that consist of only zero and one other digit. I.e. you want to find '0101', but not '0102'.
In order to do this, remove all zeros first. From the remaining string remove all digits equaling to its first character. This will result in an empty string or a string consisting of additional digits or characters. Only select those resulting in an empty string.
select *
from mytable
where replace(replace(value, '0', ''), substring(replace(value, '0', ''), 1, 1), '') = '';
Demo: https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=c307bbbf21ceeae619a966e995c3a567
You can use ISNUMERIC() function
SELECT ISNUMERIC(0000004);
This will return 1
SELECT ISNUMERIC('A');
This will return 0
So if you want to select all columns that are numeric only you can use this logic:
select *
from test
where ISNUMERIC(colA) = 1
Here is a small demo
Or you can use TRY_CAST() function:
select *
from test
where try_cast(colA as int) is not null
Alternative solution:
SELECT value
FROM mytable
CROSS JOIN (
SELECT '1' AS num
UNION ALL
SELECT '2'
UNION ALL
SELECT '3'
UNION ALL
SELECT '4'
UNION ALL
SELECT '5'
UNION ALL
SELECT '6'
UNION ALL
SELECT '7'
UNION ALL
SELECT '8'
UNION ALL
SELECT '9'
) n
WHERE REPLACE(REPLACE(value, '0', ''), num, '') = ''
AND REPLACE(value, '0', '') <> ''
AND value LIKE '%0%'

Is there a way to select a value from a column that has commas?

I was wondering if there was a way to select from a column that has comma separated values.
For example, the column has this data: ('16', '20', '27', '2', '3')
Is it possible to do something like this:
-- get value 16 from table:-
select from table where value = '16'
or maybe use in?
select from table where value in '16'
If the column value contains data with single quotes like this:
'16', '20', '27', '2', '3'
then you can use the operator like:
select * from table where value like '%''16''%'
If there are no single quotes and the data is like:
16, 20, 27, 2, 3
then:
select * from table
where ',' || replace(value, ' ', '') || ',' like '%,16,%'
If there are not any spaces between the comma separated values then you can don't need replace():
select * from table where ',' || value || ',' like '%,16,%'
Possibly the database schema violates the first normal form
Kindly use the below if the value column has single quotes sql fiddle here
select * from tt where REGEXP_LIKE(value1,'(''16'',)[^,]+');
if it doesn't have single quotes use the below sql fiddle here
select * from tt where REGEXP_LIKE(value1,'(16,)[^,]+');

How to efficiently concatenate fields that may be null?

I have a front-end field in which the user should see the values of several fields, concatenated with commas. Which is easy enough if the fields are always populated, but that is not the case. In order to avoid extra commas and spaces I came up with:
concat(
[field_one],
case when [field_one] is not null and [field_two] is not null then ', ' end,
[field_two],
case when ([field_two] is not null or [field_one] is not null) and [field_three] is not null then ', ' end,
[field_three]
) as [list_field]
Which works well enough for three fields. But the specs have changed and more fields will be added. The case statements will quickly get out of hand since they're referencing all previous fields. Is there an efficient way to do something like this?
Here is one method:
select stuff( coalesce(', ' + field_one, '') +
coalesce(', ' + field_two, '') +
coalesce(', ' + field_three, ''), 1, 2, '')
The three expressions add a ', ' before each non-null field. The stuff() removes the first one.
The NullIf() is to trap empty/non-null values. Optional if you only have nulls and values.
Example
Declare #YourTable table (field_one varchar(50),field_two varchar(50),field_three varchar(50))
Insert Into #YourTable values
('a','b','c')
,('a',null,'c')
,('a',null,null)
,('a','b',null)
,(null,'b',null)
Select *
,list_field = stuff( concat(
', '+nullif([field_one],'')
,', '+nullif([field_two],'')
,', '+nullif([field_three],'')
)
,1,2,'')
From #YourTable
Returns
field_one field_two field_three list_field
a b c a, b, c
a NULL c a, c
a NULL NULL a
a b NULL a, b
NULL b NULL b
You can actually take advantage of the fact that NULL + anything = NULL and the CONCAT function's NULL handling ability. It makes for a cleaner syntax without all of the COALESCE / ISNULL gunk...
IF OBJECT_ID('tempdb..#TestData', 'U') IS NOT NULL
DROP TABLE #TestData;
CREATE TABLE #TestData (
Col_1 VARCHAR(20) NULL,
Col_2 VARCHAR(20) NULL,
Col_3 VARCHAR(20) NULL
);
INSERT #TestData (Col_1, Col_2, Col_3) VALUES
('Bob', 'A.', 'Jones'),
('123 Some St.', NULL, 'Jacksonville'),
(NULL, 'R.', 'Smith'),
('Roy', 'Finch', NULL),
(NULL, NULL, 'Prince'),
(NULL, NULL, NULL),
('Arnold', NULL, NULL);
SELECT
ConcatString = CONCAT(td.Col_1 + ' ', td.Col_2 + ' ', td.Col_3)
FROM
#TestData td;
Output...
ConcatString
--------------------------------------------------------------
Bob A. Jones
123 Some St. Jacksonville
R. Smith
Roy Finch
Prince
Arnold
I have not tested it, but I believe that this will work on any ANSI compliant database. This probably presumes that the fields are CHAR type or that you will convert them with something like CONVERT() in SQL Server or TO_CHAR() in Oracle.
SELECT
CONCAT(
COALESCE(field_one, '')
,',',COALESCE(field_two, '')
,',',COALESCE(field_three, '')
)
FROM ...
Here is a question about STUFF(). Oracle equivalent to SQL Server STUFF function?

Script to concatenate columns and remove leading/trailing delimiter

I have a table like this and I want to return concatenated strings where the column values are in ('01', '02', '03', '04', '99'). Plus the values will be delimited by a ';'. So row 1 will be 01;04, row 3 will be 01;02;03;04 and row 5 will simply be 01. All leading/trailing ; should be removed. What script would do this successfully?
R_NOT_CUR R_NOT_CUR_2 R_NOT_CUR_3 R_NOT_CUR_4
01 NULL 04 NULL
98 56 45 22
01 02 03 04
NULL NULL NULL NULL
01 NULL NULL NULL
You can accomplish this using COALESCE / ISNULL and STUFF. Something like this.
SELECT STUFF(
COALESCE(';'+R_NOT_CUR,'')
+ COALESCE(';'+R_NOT_CUR_2,'')
+ COALESCE(';'+R_NOT_CUR_3,'')
+ COALESCE(';'+R_NOT_CUR_4,''),1,1,'')
FROM YourTable
Stuff will remove the first occurrence of ;
It's not recommended to store integer values in strings but here this should work. Try it out and let me know:
DECLARE #yourTable TABLE (R_NOT_CUR VARCHAR(10),R_NOT_CUR_2 VARCHAR(10),R_NOT_CUR_3 VARCHAR(10),R_NOT_CUR_4 VARCHAR(10));
INSERT INTO #yourTable
VALUES ('01',NULL,'04',NULL),
('98','56','45','22'),
('01','02','03','04'),
(NULL,NULL,NULL,NULL),
('01',NULL,NULL,NULL);
WITH CTE_row_id
AS
(
SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) row_id, --identifies each row
R_NOT_CUR,
R_NOT_CUR_2,
R_NOT_CUR_3,
R_NOT_CUR_4
FROM #yourTable
),
CTE_unpivot --puts all values in one column so your can apply your where logic
AS
(
SELECT *
FROM CTE_row_id
UNPIVOT
(
val FOR col IN (R_NOT_CUR,R_NOT_CUR_2,R_NOT_CUR_3,R_NOT_CUR_4)
) unpvt
WHERE val IN ('01','02','03','04','99')
)
SELECT STUFF(
COALESCE(';'+R_NOT_CUR,'') +
COALESCE(';'+R_NOT_CUR_2,'') +
COALESCE(';'+R_NOT_CUR_3,'') +
COALESCE(';'+R_NOT_CUR_4,'')
,1,1,'')
AS concat_columns
FROM CTE_unpivot
PIVOT
(
MAX(val) FOR col IN(R_NOT_CUR,R_NOT_CUR_2,R_NOT_CUR_3,R_NOT_CUR_4)
) pvt
Results:
concat_columns
--------------------------------------------
01;04
01;02;03;04
01
If you use a SUBSTRING there already is a parameter that allow you to remove character
SUBSTRING((SELECT CONCAT('/',p.YourValue)
FROM YourTable p
Where p.value2 = YourCondition
AND pc1.ProfilID = p.ProfilID
FOR XML PATH ('')),
2, 1000) [ColonneTitle],
Where the value '2' is the position of the beggining of the display, so you can choose the char position where the display will start.
(Sorry for my bad english, hope it help someone :) )

sql query complex

I have table where in a table called test which have 4 fields.one field named as listing, I have 1,2,3,4,5,6 multiple values separated by comma, I need to check whether in that table and in that particular field an id say 4 is there or not.. by a sql query.
You database design is wrong, that's why you have problems querying the data. You should have the values in a separate table, so that teach value is in it's own field. Then it would be easy to find the records:
select t.testId
from test t
inner join listing l on l.testId = t.testId
where l.id = 4
Now you have to use some ugly string comparison to find the records:
select testId
from test
where ','+listing+',' like '%,4,%'
You can try
SELECT *
FROM YourTable
WHERE REPLACE(Col, ' ', '') LIKE '4,%' --Starts with
OR REPLACE(Col, ' ', '') LIKE '%,4' --Ends with
OR REPLACE(Col, ' ', '') LIKE '%,4,%' --Contains
OR REPLACE(Col, ' ', '') = '4' --Equals
Just as a matter of interest, have a look at this
DECLARE #delimiter NVARCHAR(5),
#Val INT
SELECT #Val = 40
SELECT #delimiter = ','
DECLARE #YourTable TABLE(
ID INT,
Vals VARCHAR(50)
)
INSERT INTO #YourTable (ID,Vals) SELECT 1, '1,2,3,4,5,6,7,8'
DECLARE #TempTable TABLE(
ID INT,
Vals XML
)
INSERT INTO #TempTable
SELECT ID,
CAST('<d>' + REPLACE(Vals, #delimiter, '</d><d>') + '</d>' AS XML)
FROM #YourTable
SELECT *
FROM #TempTable tt
WHERE EXISTS(
SELECT T.split.value('.', 'nvarchar(max)') AS data
FROM tt.Vals.nodes('/d') T(split)
WHERE T.split.value('.', 'nvarchar(max)') = #Val
)
The common approach is to parse the list into a table variable or table-valued function, then either join against the table, or use an EXISTS sub-query.
There are lots of examples on how to do this:
http://www.bing.com/search?setmkt=en-US&q=SQL+parse+list+into+table
You could use an instring function in the where clause and in the select clause:
Oracle:
select substr(column, instr(column, '1', 1), 1)
where instr(column, '1', 1) > 0
works if you want a single value. Alternatively you can use a combination of case or decode statements to create a single column for each possible value:
select
decode(instr(column, '1', 1), 0, substr(column, instr(column, '1', 1), 1), null) c1,
decode(instr(column, '2', 1), 0, substr(column, instr(column, '2', 1), 1), null) c2,
decode(instr(column, '3', 1), 0, substr(column, instr(column, '3', 1), 1), null) c3
The beauty of this approach for such a poorly normalised set of data is you can save this as a view and then run SQL on that, so if you save the above you could use:
select c1, c2 from view where c1 is not null or c2 is not null
NB. In other dbms you might have to use different syntax, possibly the case rather decode statement
If you need to find 4 and only 4 (ie not 14 or 24 or 40 etc) you should use
SELECT * FROM foo WHERE col LIKE '%, 4,%'
or
SELECT * FROM foo WHERE col LIKE '%,4,%'
if there are no spaces between the commas and numbers
How about this?
Select * From Foo Where Col like '%4%'