MYSQL if (string in ( 0) ) returns TRUE - mysql

The following mysql query result returns 'TRUE',
select if('testString' in ( 0 ), 'TRUE', 'FALSE') from sampleTable
Can someone explain why please ?

You can try using
select cast('testString' AS UNSIGNED) from dual ; // return 0
do the fact because the cast for 'testString' AS UNSIGNED is = 0
then
select if( 'testString' in ( 0 ), 'TRUE', 'FALSE') from DUAL ;
match for casted value the 0 in (0) and return TRUE

Related

How to parse a string and get the value after "=" character

So I have string that should contains "Object.Name" once in a row , if I see it ,I have to get the value after "=" character. If doesn't match it anywhere in the string i should move hardcoded value.
Here is example of the string:
Object.Name=ASDD||Product.Name=DSA
Product.Name=QWE||Object.Name=WSXS
Storage.Name=12345||Object.Name=WERR||Product.Name=QAZ
I know that I should use case for that but doesn't know how to proceed the string
case
when (match the string ) then (value after the "=")
else (hardcoded value)
end
In Oracle, you can use:
SELECT value,
CASE
WHEN start_pos = 0
THEN NULL
ELSE SUBSTR(
'||' || value || '||',
start_pos + LENGTH('||Object.Name='),
end_pos - start_pos - LENGTH('||Object.Name=')
)
END AS object_name
FROM (
SELECT value,
INSTR(
'||' || value || '||',
'||Object.Name='
) AS start_pos,
INSTR(
'||' || value || '||',
'||',
INSTR('||' || value || '||', '||Object.Name=')+LENGTH('||Object.Name=')
) AS end_pos
FROM table_name
)
Which, for the sample data:
CREATE TABLE table_name (value) AS
SELECT 'Object.Name=ASDD||Product.Name=DSA' FROM DUAL UNION ALL
SELECT 'Product.Name=QWE||Object.Name=WSXS' FROM DUAL UNION ALL
SELECT 'Storage.Name=12345||Object.Name=WERR||Product.Name=QAZ' FROM DUAL;
Outputs:
VALUE
OBJECT_NAME
Object.Name=ASDD||Product.Name=DSA
ASDD
Product.Name=QWE||Object.Name=WSXS
WSXS
Storage.Name=12345||Object.Name=WERR||Product.Name=QAZ
WERR
db<>fiddle here
Since you changed the tags, in MySQL:
SELECT value,
CASE
WHEN start_pos = 0
THEN NULL
ELSE SUBSTRING(
CONCAT('||', value, '||'),
start_pos + LENGTH('||Object.Name='),
end_pos - start_pos - LENGTH('||Object.Name=')
)
END AS object_name
FROM (
SELECT value,
LOCATE(
'||Object.Name=',
CONCAT('||', value, '||')
) AS start_pos,
LOCATE(
'||',
CONCAT('||', value, '||'),
LOCATE('||Object.Name=', CONCAT('||', value, '||'))
+ LENGTH('||Object.Name=')
) AS end_pos
FROM table_name
) t
db<>fiddle here

Count vowels and consonants in an array

I am trying to write a function which will return number of vowels
and consonants. Using the IF statement function will successfully
compile, however when I call it in the select it shows the message :
"Conversion failed when converting the varchar value 'MAMAMIA' to
data type int."`
I tried with the CASE statement, but there are too many syntax
errors and i think it is not the best method of solving the problem
using CASE ...
CREATE FUNCTION VOW_CONS(#ARRAY VARCHAR(20))
RETURNS INT
BEGIN
DECLARE #COUNTT INT;
DECLARE #COUNTT1 INT;
SET #COUNTT=0;
SET #COUNTT1=0;
WHILE (#ARRAY!=0)
BEGIN
IF(#ARRAY LIKE '[aeiouAEIOU]%')
SET #COUNTT=#COUNTT+1
ELSE SET #COUNTT1=#COUNTT1+1
/*
DECLARE #C INT;
SET #C=(CASE #SIR WHEN 'A' THEN #COUNTT=#COUNTT+1;
WHEN 'E' THEN #COUNTT=#COUNTT+1
WHEN 'I' THEN #COUNTT=#COUNTT+1
WHEN 'O' THEN #COUNTT=#COUNTT+1
WHEN 'U' THEN #COUNTT=#COUNTT+1
WHEN 'A' THEN #COUNTT=#COUNTT+1
WHEN ' ' THEN ' '
ELSE #COUNTT1=#COUNTT1+1
END)
*/
END
RETURN #COUNTT;
END
SELECT DBO.VOW_CONS('MAMAMIA')
Without knowing what version of SQL Server you are using, I am going to assume you are using the latest version, meaning you have access to TRANSLATE. Also I'm going to assume you do need access to both the number of vowels and consonants, so a table-value function seems the better method here. As such, you could do something like this:
CREATE FUNCTION dbo.CountVowelsAndConsonants (#String varchar(20))
RETURNS table
AS RETURN
SELECT DATALENGTH(#String) - DATALENGTH(REPLACE(TRANSLATE(#String,'aeiou','|||||'),'|','')) AS Vowels, --Pipe is a character that can't be in your string
DATALENGTH(#String) - DATALENGTH(REPLACE(TRANSLATE(#String,'bcdfghjklmnpqrstvwxyz','|||||||||||||||||||||'),'|','')) AS Consonants --Pipe is a character that can't be in your string
GO
And then you can use the function like so:
SELECT *
FROM (VALUES('MAMAMIA'),('Knowledge is power'))V(YourString)
CROSS APPLY dbo.CountVowelsAndConsonents(V.YourString);
Another option would be to split the string into its individual letters using a tally table, join that to a table of vowels/consonants and then get your counts.
Here is a working example, you'll have to update/change for your specific needs but should give you an idea on how it works.
DECLARE #string NVARCHAR(100)
SET #string = 'Knowledge is power';
--Here we build a table of all the letters setting a flag on which ones are vowels
DECLARE #VowelConsonants TABLE
(
[Letter] CHAR(1)
, [IsVowel] BIT
);
--We load it with the data
INSERT INTO #VowelConsonants (
[Letter]
, [IsVowel]
)
VALUES ( 'a', 1 ) , ( 'b', 0 ) , ( 'c', 0 ) , ( 'd', 0 ) , ( 'e', 1 ) , ( 'f', 0 ) , ( 'g', 0 ) , ( 'h', 0 ) , ( 'i', 1 ) , ( 'j', 0 ) , ( 'k', 0 ) , ( 'l', 0 ) , ( 'm', 0 ) , ( 'n', 0 ) , ( 'o', 1 ) , ( 'p', 0 ) , ( 'q', 0 ) , ( 'r', 0 ) , ( 's', 0 ) , ( 't', 0 ) , ( 'u', 1 ) , ( 'v', 0 ) , ( 'w', 0 ) , ( 'x', 0 ) , ( 'y', 0 ) , ( 'z', 0 );
--This tally table example gives 10,000 numbers
WITH
E1(N) AS (select 1 from (values (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))dt(n)),
E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
cteTally(N) AS
(
SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
)
SELECT SUM( CASE WHEN [vc].[IsVowel] = 1 THEN 1
ELSE 0
END
) AS [VowelCount]
, SUM( CASE WHEN [vc].[IsVowel] = 0 THEN 1
ELSE 0
END
) AS [ConsonantCount]
FROM [cteTally] [t] --Select from tally cte
INNER JOIN #VowelConsonants [vc] --Join to VowelConsonants table on the letter.
ON LOWER([vc].[Letter]) = LOWER(SUBSTRING(#string, [t].[N], 1)) --Using the number from the tally table we can easily split out each letter using substring
WHERE [t].[N] <= LEN(#string);
Giving you results of:
VowelCount ConsonantCount
----------- --------------
6 10

SQL Convert a char to boolean

I have in my table one row with a char value. When the value is NULL then a false should be outputted. If the value is not NULL then a true should be outputted.
So when I try to set user_group.tUser to 0 or 1 then I'm getting this error:
Invalid column name 'false'.
Invalid column name 'true'.
SELECT COALESCE((SELECT name
FROM v_company
WHERE companyId = userView.companyId), ' ') AS company,
userView.value AS companyUser,
userView.display AS displayedUser,
CASE
WHEN user_group.tUser IS NULL THEN 0
ELSE 1
END AS userIsMemberOfGroup
FROM v_user userView
LEFT OUTER JOIN cr_user_group user_group
ON ( user_group.group = 'Administrators'
AND user_group.tUser = userView.value )
ORDER BY company ASC,
displayedUser ASC
I think this is the logic you want:
SELECT COALESCE(v.name, ' ') as company,
u.value as companyUser, u.display as displayedUser,
(EXISTS (SELECT 1
FROM cr_user_group ug
WHERE ug.group = 'Administrators' AND
ug.tUser = uv.value
)
) as userIsMemberOfGroup
FROM v_user u LEFT JOIN
v_company c
ON c.companyId = v.companyId
ORDER BY company ASC, displayedUser ASC ;
In general, MySQL is very flexible about going between booleans and numbers, with 0 for false and 1 for true.
You can use MySQL IF function to return 'false' when name IS NULL, else 'true':
SELECT IF(name IS NULL, 'false', 'true')
FROM table;
A simple CASE expression would work here:
SELECT
name,
CASE WHEN name IS NOT NULL THEN true ELSE false END AS name_out
FROM yourTable;
We could also shorten the above a bit using IF:
IF(name IS NOT NULL, true, false)
SELECT
CASE
WHEN name IS NULL THEN 'false'
ELSE 'true'
END
FROM
table1;

return a SUM zero(0) instead of null

SELECT SUM( IF( userId = '123456', amount, 0 ) ) AS 'amount'
FROM `amountInfo`
userId 123456 is not present in table amountInfo, in that case it is returning null i want 0(numerical)
Use IFNULL:
SELECT IFNULL(SUM(IF(userId = '123456', amount, 0)), 0) AS amount
You can use coalesce for this
UPDATE : I was missing the argument to set 0 instead of NULL, pointed by #Barmar
coalesce( SUM( IF( userId = '123456', amount, 0 ) ),0 )
Select COALESCE(sum(amount),0) as amount from amountInfo where userId='123456'
You can read on http://www.w3schools.com/sql/sql_isnull.asp

Is it possible to make that instead of NULL will be displayed 0?

Code:
SELECT
count(*) as count,
sum(Status = 'test1') as count_test1,
sum(Status = 'test2') as count_test2
FROM Table
WHERE Type = 'test'
in result i see:
count count_test1 count_test2
0 NULL NULL
Tell me please is it possible to make that instead of NULL will be displayed 0?
P.S.: That results was:
count count_test1 count_test2
0 0 0
you can use COALESCE
COALESCE(sum(Status = 'test1'), 0)
or IFNULL
IFNULL(sum(Status = 'test1'), 0)
SELECT
count(*) as count,
IFNULL(sum(Status = 'test1'), 0) as count_test1,
IFNULL(sum(Status = 'test2'), 0) as count_test2
FROM Table
WHERE Type = 'test'
You can use the COALESCE function which take an array and return the first element not null
SELECT
count(*) as count,
COALESCE(sum(Status = 'test1'), 0) as count_test1,
COALESCE(sum(Status = 'test2'), 0) as count_test2
FROM Table
WHERE Type = 'test'