SQL WHERE Expression in CASE clause - sql

I want to fetch data from a table Item that has the two fields name and nullable_name, the second one can be empty.
Now I want to add a filter string, so that only results will get fetched that contain that string (in the name field if nullable_name is null, and in the nullable_name field if it is present). So I want one of two WHERE expressions to take place, depending on the situation.
What I tried but didn't work:
SELECT * FROM Item
WHERE
CASE
WHEN Item.nullable_name IS NULL THEN (Item.name LIKE '%filter%')
ELSE (Item.nullable_name LIKE '%filter%')
END

You seem to want coalesce():
where coalesce(item.nullable_name, item.name) like '%filter%'
coalesce() is a function that returns the first non-NULL value.

Try
Where isnull(item.nullable_name, item.name) like '%filter%'

Related

Adding column to table based on whether another column = a specific string

I want to add a column called "Sweep" that contains bools based on whether the "Result" was a sweep or not. So I want the value in the "Sweep" column to be True if the "Result" is '4-0' or '0-4' and False if it isn't.
This is a part of the table:
I tried this:
ALTER TABLE "NBA_finals_1950-2018"
ADD "Sweep" BOOL;
UPDATE "NBA_finals_1950-2018"
SET "Sweep" = ("Result" = '4-0' OR "Result" = '0-4');
But for some reason, when I run this code...:
SELECT *
FROM "NBA_finals_1950-2018"
ORDER BY "Year";
...only one of the rows (last row) has the value True even though there are other rows where the result is a sweep ('4-0' or '0-4') as shown in the picture below.
I don't know why this is happening but I guess there is something wrong with the UPDATE...SET code. Please help.
Thanks in advance.
NOTE: I am using PostgreSQL 13
This would occur if the strings are not really what they look like -- this is often due to spaces at the beginning or end. Or perhaps to hyphens being different, or other look-alike characters.
You just need to find the right pattern. So so with a select. This returns no values:
select *
from "NBA_finals_1950-2018"
where "Result" in ('4-0', '0-4');
You can try:
where "Result" like '%0-4%' or
"Result" like '%4-0%'
But, this should do what you want:
where "Result" like '%4%' and
"Result" like '%0%'
because the numbers are all single digits.
You can incorporate this into the update statement.
Note: double quotes are a bad idea. I would recommend creating tables and columns without escaping the names.

Replace empty date values with a matching value from the same column?

I have a small query that looks like this:
SELECT
CS.ID,
CS.Import_Date,
CS.Secondary_Date
FROM
Center_Summary CS
ORDER BY CS.Import_Date
Which returns values like this:
And I want to replace these "empty" values which are pulling as 01/01/1900 with the value of 05/01/2019. In this case, it's because the ID and Import_Date match, so the Secondary_Date should match as well. I've thought to use REPLACE() (REPLACE(CS.Secondary_Date, '01/01/1900', ???), but I'm not sure how to write logic to pull in a matching value from the column Secondary_Date based on ID and Import_Date - what function should I be looking to use here?
How it's currently pulling (the dates in red I want to replace):
What my expected result is:
Why not just use a UPDATE with a WHERE?
UPDATE dbo.YourTable
SET SecondaryDate = ImportDate
WHERE SecondaryDate = '19000101';
"Empty" values are best represented by NULL. I would recommend converting them to NULL:
nullif(secondary_date, '1900-01-01')
If you really want another value, then you can use coalesce() or a case expression:
coalesce(nullif(secondary_date, '1900-01-01'), '2019-05-01')
However, I'm not generally a fan of such magic values in the code.

How to add one more column in the select using Laravel Eloquent

I am trying to use Laravel Eloquent to make a query. I would like to group the results by the level column, count the results in a total alias, and finally, bring me the id of each result. What am I doing wrong?
$fodas = Foda::groupBy('level')
->select('level', DB::raw('count (*) as total'))
->get();
The result is a collection that only brings me the level and total fields.
You'll see this pattern with many laravel facades. If you are handling 'one of something', in this case a column, you pass a string and if you are handling many of something, you pass an array.
That's why * and level are both valid. Because * is recognized a column and is expanded inside mysql to match every column.
And that's also why it doesn't work when you try to query for 'level, column2, column3' because this string is not a valid column name, so you have to pass an array with all the columns you want to use.
$fodas = Foda::groupBy('level')
->select(['level','other','column'], DB::raw('count (*) as total'))
->get();
As I said before, this applies to many laravel facades:
Facade::function('one_thing');
//or
Facade::function(['thing1','thing2','thing3']);
//or even this, for some cases
Facade::function('thing1','thing2','thing3');

How to Filter a row

I created a view for report. I imported data to the report. In columns null values are also present. If i filter one row using filter in vb.net the null values of row cannot be displayed.
For example, column names are ID, Name, Number, Place. In this some of the places number has null values I include filter ID, Name ,Number,Place. If I filter using ID the null values of number cannot be displayed.
This is the code I tried but not filter
IN FORM TextBox1.Text=""
TABLE1BindingSource.Filter = "YOUR FIELDNAME LIKE '" + TextBox1.Text.Equals (String.Empty) + "'")
Expected Result
Table
YOUR FIELDNAME
value1
value2
NULL
value3
NULL
NULL
value4
That filter doesn't make sense. This part:
TextBox1.Text.Equals(String.Empty)
is going to evaluate to Boolean, i.e. True if the TextBox is empty and False if it's not. That means that your filter ends up being:
YOUR FIELDNAME LIKE 'False'
or the like. What you should actually be doing is something like this:
Dim columnName As String
Dim fieldValue As String
'...
TABLE1BindingSource.Filter = String.Format("{0} LIKE '{1}%'", columnName, fieldValue)
Note a number of things there. Firstly, the use of String.Format to make this sort of code more readable. Secondly, the use of the actual value entered by the user and not a Boolean indicating whether that value was empty or not. Thirdly, the use of a wildcard because using LIKE without a wildcard makes no sense.
It should also be noted that that code is only going to work with text fields, because they are the only ones that get delimited by single quotes and the only ones that you can use LIKE with. If you want to filter on a numeric field or some other data type then you'll have to write your code to create the filter differently.

Problem with MySQL Select query with "IN" condition

I found a weird problem with MySQL select statement having "IN" in where clause:
I am trying this query:
SELECT ads.*
FROM advertisement_urls ads
WHERE ad_pool_id = 5
AND status = 1
AND ads.id = 23
AND 3 NOT IN (hide_from_publishers)
ORDER BY rank desc
In above SQL hide_from_publishers is a column of advertisement_urls table, with values as comma separated integers, e.g. 4,2 or 2,7,3 etc.
As a result, if hide_from_publishers contains same above two values, it should return only record for "4,2" but it returns both records
Now, if I change the value of hide_for_columns for second set to 3,2,7 and run the query again, it will return single record which is correct output.
Instead of hide_from_publishers if I use direct values there, i.e. (2,7,3) it does recognize and returns single record.
Any thoughts about this strange problem or am I doing something wrong?
There is a difference between the tuple (1, 2, 3) and the string "1, 2, 3". The former is three values, the latter is a single string value that just happens to look like three values to human eyes. As far as the DBMS is concerned, it's still a single value.
If you want more than one value associated with a record, you shouldn't be storing it as a comma-separated value within a single field, you should store it in another table and join it. That way the data remains structured and you can use it as part of a query.
You need to treat the comma-delimited hide_from_publishers column as a string. You can use the LOCATE function to determine if your value exists in the string.
Note that I've added leading and trailing commas to both strings so that a search for "3" doesn't accidentally match "13".
select ads.*
from advertisement_urls ads
where ad_pool_id = 5
and status = 1
and ads.id = 23
and locate(',3,', ','+hide_from_publishers+',') = 0
order by rank desc
You need to split the string of values into separate values. See this SO question...
Can Mysql Split a column?
As well as the supplied example...
http://blog.fedecarg.com/2009/02/22/mysql-split-string-function/
Here is another SO question:
MySQL query finding values in a comma separated string
And the suggested solution:
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_find-in-set