How to DELETE in SQL with multiple conditions - sql

I have a table with one column called name_of, I have a lot of duplicates in this table, I have some python code, that takes all the duplicates and then concat them into the SQL query. But I have tried for some time with no luck.
TableName = users_from_group
Column = name_of
i have tried the following sql query:
DELETE FROM users_from_group
WHERE name_of = ('AskeMeyer'), ('testuser'), ('AskeMeyer'), ('testuser'), ('testuser'), ('AskeMeyer')
and I don't understand why this is not working, as this is the format of data for querying adding into the table?

the best way to do this is:
DELETE FROM users_from_group
WHERE name_of IN ('AskeMeyer', 'testuser', 'AskeMeyer', 'testuser', 'testuser', 'AskeMeyer')
If this is useful for you, I would appreciate to mark as resolved.
Cheers

As #jarlh mentioned, you probably don't want to delete ALL of the records with these name_of's. I'm guessing you want to keep exactly 1 of each?
The best practice for this scenario is to do your work all in SQL, following a "Delete Duplicate Rows" pattern. There are a couple ways to do this, and it can matter which version of SQL you are using, but this question is a starting point.
Also, just a couple S/O tips:
Include which SQL server you are using in your questions in the future
Include the error message that you receive

Related

Join query giving empty result SQL

SQL learner here, trying to make a join, but it seems to not work.
I have the following 2 tables:
#device_combined_players
#final_results2
The goal is to have a new table replacing the player_store_id from #final_results with the pseudo_name from #device_combined_players.
I have tried with:
SELECT #final_results2.player_store_id,
#device_combined_players.pseudo_name, #final_results2.genre FROM #device_combined_players INNER JOIN #final_results2 ON #final_results2.player_store_id = #device_combined_players.store_id
but I can't make it work, my output is simply an empty table.
Could you guys, please, give me some light? Thank you!
My expected result would be: as #final_results2 (image 2), but replacing player_store_id column by pseudo_name from #device_combined_players table.
EDIT: a screenshot with more details:
https://i.stack.imgur.com/lSyLb.png
And, I am answering myself, since I had 2 different issues here. Both are rookie mistakes, but I will leave them here so it helps somebody else in the future:
Take a look at the data type of your columns. They can cause conflicts if they are not the same as the columns you are referencing in a JOIN.
Check if your data doesn't have spaces. You can use TRIM and LEN to help you out answering this.
I sorted my problem like that.

Search and replace part of string in database - what are the pitfalls?

I need to replace all occurrences "google.com" that are met in the SQL db table Column1 with "newurl". It can be a full cell value, a part of it (substring of varchar()), can be met even several times in a cell.
Based on SO answer search-and-replace-part-of-string-in-database
this is what I need:
UPDATE
MyTable
SET
Column1 = Replace(Column, 'google.com', 'newurl')
WHERE
xxx
However, in that answer it is mentioned that
You will want to be extremely careful when doing this! I highly recommend doing a backup first.
What are the pitfalls of doing this query? Looks like it does the same what any texteditor would do by clicking on Replace All button. I don't think it is possible in my case to check the errors even with reserve copy as I would like to know possible errors in advance.
Any reasons to be careful with this query?
Again, I expect it replaces all occurences of google.com with 'newurl' in the Column1 of MyTable table in the SQL db.
Thank you.
Just create a test table, as a replica of your original source table, complete the update on there and check results.
You would want to do this as good SQL programming practice to ensure you don't mess up columns that should not be updated.
Another thing you can do is get a count of the records before hand that fit the criteria using a SELECT statement.
Run your update statement and if it's a 1-1 match on count, you should be good to go.
The only thing i can think of that would happen negatively in this respect is that additional columns get updated. Your WHERE clause is not specific for us to see, so there's no way to validate that what you're doing will do what you expect it to.
I think the person posting the answer is just being cautious - This will modify the value in Column1 for every row in MyTable, so make sure you mean it when you execute. Another way to be cautious would be to wrap it in a transaction so you could roll it back if you don't like the results.

What happens if I SELECT something AS a name then something else AS the same name?

I've already answered my question but didn't see it on here, so here we go. Please feel free to link to the question if it has been asked exactly.
I simplified my question to the following code:
SELECT 'a' AS col1, 'b' AS col1
Will this give a same column name error?
Will the last value always be returned or is there a chance col1 could be 'a'?
I'm not sure why you would ever want this, but I tried it in Oracle (10g) and it worked fine, returning both columns. I realize you've asked about SQL Server specifically, but I found it interesting that this worked at all.
Edit: It also works on MySQL.
It works in the final query:
However when you do it in a subselect and refer to the ambiguous column aliases in an outer query you get an error:
In SQL 2008 r2 it is valid as a stand alone query. Under certain circumstances it will produce errors (incomplete list):
Inline views
Common Table Entries
Stored Procedures when the output is used by reporting services and presumably similarly integrated tools
It's hard to imagine a case where you would want duplicate row names, and it's easy to think of ways in which writing queries with repeats now could turn sour in the future.

How you get a list of updated columns in SQL server trigger?

I want to know what columns where updated during update operation on a triger on first scaaning books online it looks like COLUMNS_UPDATED is the perfect solution but this function actualy don't check if values has changed , it check only what columns where selected in update clause, any one has other suggestions ?
The only way you can check if the values have changed is to compare the values in the DELETED and INSERTED virtual tables within the trigger. SQL doesn't check the existing value before updating to the new one, it will happily write a new identical value over the top - in other words, it takes your word for the update and tracks the update rather than actual changes.
We can use Update function to find if a particular column is updated:
IF UPDATE(ColumnName)
Refer to this link for details: http://msdn.microsoft.com/en-us/library/ms187326.aspx
As the others have posted, you'll need to interrogate INSERTED and DELETED. The only other useful bit of advice might be that you can get only the rows that have changed values (and discard the rows that didn't change) by using the EXCEPT operator - like this:
SELECT * FROM Inserted
EXCEPT
SELECT * FROM Deleted
The only way I can think of is that you can compare the values in DELETED and INSERTED to see which columns have changed.
Doesn't seem a particularly elegant solution though.
I asked this same question!
The previous posters are correct -- without directly comparing the values, you can't tell for sure whether the data has actually changed or not. However, there are several ways to do this type of checking, depending on what else you're trying to do in the trigger. My question has some good advice in the answers about those different mechanisms and their tradeoffs.

SQL Super Search

Does anyone have a good method for searching an entire database for a given value?
I have a specific string I'm looking for, it's in TableA, and it's also a FK to some other table, TableB, except I don't know which table/column that is.
Assuming there's a jillion tables and I don't want to look through them all, and maybe will have to do this in several different cases, what would be the best way?
Since I didn't want a Code-SQL bridge, my only all-SQL idea was:
select tablename and column_name from INFORMATION_SCHEMA.COLUMNS
...then use a cursor to flip through all the columns, and for all the datatypes of nvarchar I would execute dynamic SQL like:
SELECT * from #table where #column = #myvalue
Needless to say, this is slow AND a memory hog.
Anyone got any ideas?
Dump the database and grep?
I guess a more focused question might be: if you don't know how the schema works, what are you going to do with the answer you get anyway?
Here are a couple of links talking about how to do this:
http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/the-ten-most-asked-sql-server-questions--1#2
http://vyaskn.tripod.com/search_all_columns_in_all_tables.htm
Both of them use the approach you were hoping to avoid. Refine them so that they only searched columns that were foreign keys should improve their performance by eliminating the searching of unnecessary tables.
Here's a solution I wrote several years ago:
http://www.users.drew.edu/skass/sql/SearchAllTables.sql.txt
Just make SP that searches in all relevant columns using OR.
Why don't you know which columns to search on?
If the list of columns is ever-shifting, then you just need to make sure that whatever process results in changing the schema would result in the change in this stored procedure.
If the list of the columns is just too dang big for you to type up inot the SP, use some elementary perl/grep/whatnot to do it in 1 line, e.g for SYBASE.
my_dump_table_schema.pl|egrep "( CHAR| VARCHAR)"|awk '{$1}'|tr "\012" " "|perl -pe '{s/ / = \#SEARCH_VALUE OR /g}'; echo ' = #SEARCH_VALUE'
The last echo is needed to add the value to last column
to dump your data, read up on the bcp Utility