In SQL, is there something like: WHERE x = ANY_VALUE? - mysql

In a SQL query like this:
SELECT *
FROM MyTable
WHERE x = 5;
is it possible to modify the WHERE condition so that SELECT looks for every value of x? Something like (wrong syntax):
SELECT *
FROM MyTable
WHERE x = ANY_VALUE;
The reason behind this question is that I have to parse and modify some SQL queries through some C++ code I am writing. I know in this case I could just remove or comment the whole WHERE condition, but this is a simplification.
Thank you.

In cases like this, you normally would do something like this:
SELECT *
FROM MyTable
WHERE x = SOME_VALUE OR 1 = 1;
SOME_VALUE is arbitrary, it can be anything matching the type of the column, because the WHERE clause will always be true because of the second part.

You could just omit WHERE clause. :)

While I think it's really the wrong way to go about it (just make the effort to remove the Where), how about where x = x? It won't work if X is null (you'd have to use "x is null or x = x") but don't bother if you know x won't be null.

You can try that:
SELECT *
FROM MyTable
WHERE x = x OR x IS NULL;

You could make your query like this
DECLARE #VALUE as (type of x)
--SET #VALUE = ''
SELECT *
FROM MyTable
WHERE (#VALUE IS NULL OR x = #VALUE);
and your parse would only have to replace
the: --SET #VALUE = '' line for one with the value you want, minus the comment, like: SET #VALUE = 'abc'
hope this helps

Related

Where condition is not working

I have a SQL query. But that contains a where condition, and the OR in that where is not working.
Query
SELECT `st_student`.`st_id`, `ab_date`, `as_date` `st_status`
FROM (`st_student`)
WHERE `st_status` = 1
OR `st_status` = 2
AND `ab_date` BETWEEN '08/01/2015' AND '08/31/2015'
OR `as_date` BETWEEN '08/01/2015' AND '08/31/2015'
AND `aca_no` = 2
GROUP BY `st_student`.`st_id`
This condition is not working:
OR `as_date` BETWEEN '08/01/2015' AND '08/31/2015'
Is there any mistake in that?
One possible error concerns the use of the AND and OR operators, since AND has priority over OR, and your query can be interpreted in the wrong way. So you should use the parentheses, and write something like this:
SELECT `st_student`.`st_id`, `ab_date`, `as_date` `st_status`
FROM `st_student`
WHERE (`st_status` = 1 OR `st_status` = 2)
AND (`ab_date` BETWEEN '08/01/2015' AND '08/31/2015'
OR `as_date` BETWEEN '08/01/2015' AND '08/31/2015')
AND `aca_no` = 2
GROUP BY `st_student`.`st_id`
In case that your columns are declared as a varchar datatype you will need to use str_to_date function. Varchar cannot be compared as a date unless you convert it to one. Try this and let me know. Best of luck.
SELECT `st_student`.`st_id`, `ab_date`, `as_date` `st_status`
FROM `st_student`
WHERE (`st_status` = 1 OR `st_status` = 2)
AND STR_TO_DATE(`ab_date`,'%d/%m/%Y')
BETWEEN
STR_TO_DATE('01/08/2015','%d/%m/%Y')
AND
STR_TO_DATE('31/08/2015','%d/%m/%Y')
OR
STR_TO_DATE(`as_date`,'%d/%m/%Y')
BETWEEN
STR_TO_DATE('01/08/2015','%d/%m/%Y')
AND
STR_TO_DATE('31/08/2015','%d/%m/%Y')
AND `aca_no` = 2
GROUP BY `st_student`.`st_id`

MySql Remove All Substrings that Match Table Values

I have a VARCHAR variable and I would like to remove all substrings that match a column in a table. So far I have built a query that will return all rows that are a substring of my variable, using the following query:
SET #myval = '%For Her, Shoes,, Sizes 14-24%';
SELECT strReplace
FROM tbl_StringsToReplace
WHERE #myval LIKE CONCAT('%', strReplace, '%');
But I am having trouble writing a REPLACE query that will replace multiple values. I am trying to write something like the following:
SET #myval = REPLACE((SELECT strReplace
FROM tbl_StringsToReplace
WHERE #myval LIKE CONCAT('%', strReplace, '%')), '', #myval);
But I am getting the error:
Error Code: 1242. Subquery returns more than 1 row
I would love to achieve this in pure SQL. Euther way, any advice would be greatly appreciated. Thanks
Try:
SET #myval = '%For Her, Shoes,, Sizes 14-24%';
select val into #myval
from (
SELECT #myval := replace(#myval, strReplace, '') val
FROM tbl_StringsToReplace
) r
order by length(val)
limit 1;
select #myval;

Round up a value to the nearest power of 2 in MySQL query

I would like to round up a value to the next nearest power of 2 in a mysql query, so
select RoundUpToNearestPowerOfTwo(700) -- Should give 1024
I need this solution as part of a much larger query to generate and read some bitmask. Using custom stored functions is not an option, since I cannot use those in our production environment, so I'm looking for a smart way to do this inline in the query.
[Edit]
One possible way I can think of, is creating some enumerator, use a power in that, and choose the smallest value larger than my value:
select
min(BOUND)
from
(select 700 as VALUE) v
inner join
(select
POW(2, #pow := #pow + 1) as BOUND
from
(select #pow := 0) x,
MY_RANDOM_TABLE t
) x on x.BOUND > v.VALUE
But as you can tell, it's pretty verbose, so a leaner solution would be welcome.
Try this.
FLOOR(POW(2,CEIL(LOG2(1025))))
The CEIL and FLOOR cope with the boundary conditions correctly.
Try this:
select power(2, 1 + floor(log2(XXX)))
MySQL conveniently has the log2() function, which does most of the work.
EDIT:
I think this may be what you want:
select (case when floor(log2(XXX)) <> log2(XXX)
then power(2, 1 + floor(log2(XXX)))
else power(2, floor(log2(XXX)))
end)
Or something like:
select power(2, 1 + floor(log2(XXX*0.999999)))
There is a boundary condition on actual powers of 2.
If you are using SQL Server then you can try this...just change value in variable #value for any value to get the next nearest power of 2
declare #count int = 1
declare #value int = 700
while (#value <> 1)
BEGIN
set #value = #value / 2
set #count = #count + 1
END
select power(2, #count)

IF condition in mysql

I have a contact table I wish to query when a certain condition exists. I tried the query below but am getting a syntax error.
SELECT *
FROM contact_details
WHERE contactDeleted` =0
AND IF ( contactVisibility = "private"
, SELECT * FROM contact_details
WHERE contactUserId = 1
, IF( contactVisibility = "group"
, SELECT * FROM contact_details
WHERE contactGroup = 3
)
)
If I'm understanding your question correctly (which is difficult with the lack of info you've provided. Sample datasets and expected outcomes are typically helpful), then I don't believe you need IFs at all for what you want. The following will return contacts that are not deleted and who either have (visibility = "private" and userId = 1) OR (visibility = "group" and group = 3)
SELECT *
FROM contact_details
WHERE contactDeleted = 0
AND (
(contactVisibility = "public")
OR
(contactVisibility = "private" AND contactUserId = 1)
OR
(contactVisibility = "group" AND contactGroup = 3)
)
I am assuming you want to use the IF() function and not the statement which is for stored functions..
Refer to this link for more information on that.
Notice that you have put 2 select statements in there, where the custom return values are supposed to be. So you are returning a SELECT *... now notice that in your upper level sql statement you have an AND.. so you basically writing AND SELECT *.. which will give you the syntax error.
Try using .. AND x IN (SELECT *) .. to find if x is in the returned values.
Let me also list this link to make use of an existing and well written answer which may also applicable to your question.

SQL Join only on condition?

I have about 10 different sql statements that update different tables. They look similar to this:
Update Y
SET x = n
Where something = #somevar
Now I need to Update only certain rows when the #hasRows var is set. I could simply do this:
if not #hasRows is null
begin
Update Y
SET x = n
from Y inner join #items on y.Item = #items.Item
Where something = #somevar
end
else
begin
Update Y
SET x = n
Where something = #somevar
end
Is there a way to avoid the if/else and do the update in one statement?
I am using SQL2005.
Perhaps something like this: (copypasta your example)
UPDATE Y
SET x = n
FROM Y
WHERE something = #somevar
AND (
(#Items IS NULL)
OR (y.Item = #Item)
)
The JOIN isn't used but it's always proceeding if #items is NULL, or using the intended condition.
Problem here is that your example seems to include a TVP #ITEMS but TVPs don't exist in SQLServer2k5? So whatever the value is should be placed in the parameter.
Alternatively, if #Table exists but has no rows you can do this:
UPDATE Y
SET x = n
FROM Y
JOIN #Items ON (#HasRows = 0) OR (#Items.Item = Y.Item)
WHERE something = #somevar
If you don't know whether or not #Items IS NULL then your condition is your option because declared variables are resolved before the statement is executed.