How to UPDATE from a Select in sql? - sql

A little personal project i'm doing, kinda new in sql.
Lets say i have a table with multiples columns, but i want to work with 2 for this request: CODE and VALUE
Basically, the codes are like this : 1_A, 1_B, 1_C, 2_A, 2_B, 2_C, 3_A, 3_B, 3_C, etc... They are already created.
What i want to do is replace the VALUE from the C codes with the A codes: 1_A -> 1_C, 2_A->2_C, and so on. Without touching the other colmuns
What i thougt so far is :
update TABLE set Value = (select value from TABLE from CODE like '%A%') where CODE like '%C%'
But how do make sure that the Value associated with the code X_A gets copied into X_C specifically ? Like, so 1_A gets copied into 1_C and not 2_C. Maybe it has to do with JOIN, but honestly i don't get how those work yet
Edit : it's on oracle

If you're looking to copy all the A values to C values, you should use an insert statement, not an update statement. This can be with the insert-select construct:
INSERT INTO mytbale (value)
SELECT REPLACE(value, 'A', 'C')
FROM mytable
WHERE value LIKE '%A'

Related

INSERT INTO and insert NULL in PostgreSQL

Update:
This question has no value and can be deleted. The syntax shown in the question actually works well and is likely the best approach.
I'd like to insert NULL into one column as part of a "select into". In the example below, I try to copy columns a and b from table_1 to table_2, and in the same query, insert NULL into table_2.c
I've tried this:
INSERT INTO table_2 (a, b, c)
SELECT a, b, NULL
FROM table_1
But I get ERROR 42601 (syntax_error) syntax error at or near "NULL".
Appreciate any guidance on this.
Nonsense. Your statement is syntactically correct.
None of the suggestions here are necessary. The error you report should not occur.
Also, SELECT INTO (like you wrote in error) is an unrelated command - the use of which is discouraged in favor of CREATE TABLE AS.
Typically, you can just omit columns that shall be NULL from the target list - unless a different default value is set for the column. But it's typically bad style to omit the target column list altogether (exceptions apply).
INSERT INTO table_2 (a, b)
SELECT a, b
FROM table_1;
If column table_2.c has no different DEFAULT value in the table definition, it defaults to NULL. To be precise:
How to use default value of data type as column default?
Shorter; but there is nothing wrong with your original query. In fact, it's the best way.

assigning IS NULL to a string before querying DB

I have an excel spreadsheet with 15 or so fields. Wat I'm doing is, i open it, grab a row of data, then check each row for a value. Then using a few criteria I go look up to see if this Client value is already in the DB. As Example
Some of the fields mind be empty. Basically after checking some of the fields, I use them to check if that record exists already in DB. the problem arises when some fields are empty in which case when I query sql server it looks something like...
Select * from TblA where Company='Apple' and CompanyAdd ='Cupertino' and City=''
Because City = '' - it doesnt not find anything in SQL. The only thing that works is
and City is NULL
How am I able to programmatically assign that to a variable like CITY?
it is a string and the field in SQL is varchar
EDIT:
I want to be able to do something like this..... (as example)
if city = "" then
'I need this here to be so that....
city IS NULL
End if
So that when I query db it looks something like...
Select count(*) from TblA where City is Null
Is somethng like that possible?
You can use COALESCE for this purpose.
SELECT *
FROM TblA
WHERE COALESCE(Company, '')='Apple'
AND COALESCE(CompanyAdd, '') = 'Cupertino'
AND COALESCE(City, '') = ''
Keep in mind that the performance of this query will most likely not be stellar.

Sql Server - Any special way to insert so that in one column the value was the same, while in the other varied?

I need to insert into a simple table with two columns.
The first column has to contain the same value from row to row, while the second has to hold the various values from a source table. So it all should look like this:
Question is - is there a way to make a set-based insert in this case? The way I do it now is simply iterate through the rows of the source table. Or it's also possible to use cursors, only I'm not sure which is best.
But still this is iteration.
Any means to get around this?
Thanks in advance!
If you know your static value ahead of time, you could do something like this:
INSERT INTO targetTable(Col1, Col2)
SELECT 1, yourColumn
FROM sourceTable
WHERE <condition>
This is assuming that 1 is your static value. It can be replaced with the real value, or a variable, depending on the specifics of your query.
insert into dest_tab(col1, col2)
select 1, col2
from src_table
where ....

COUNT() Function in conjunction with NOT IN clause not working properly with varchar field (T-SQL)

I came across a weird situation when trying to count the number of rows that DO NOT have varchar values specified by a select statement. Ok, that sounds confusing even to me, so let me give you an example:
Let's say I have a field "MyField" in "SomeTable" and I want to count in how many rows MyField values do not belong to a domain defined by the values of "MyOtherField" in "SomeOtherTable".
In other words, suppose that I have MyOtherField = {1, 2, 3}, I wanna count in how many rows MyField value are not 1, 2 or 3. For that, I'd use the following query:
SELECT COUNT(*) FROM SomeTable
WHERE ([MyField] NOT IN (SELECT MyOtherField FROM SomeOtherTable))
And it works like a charm. Notice however that MyField and MyOtherField are int typed. If I try to run the exact same query, except for varchar typed fields, its returning value is 0 even though I know that there are wrong values, I put them there! And if I, however, try to count the opposite (how many rows ARE in the domain opposed to what I want that is how many rows are not) simply by supressing the "NOT" clause in the query above... Well, THAT works! ¬¬
Yeah, there must be tons of workarounds to this but I'd like to know why it doesn't work the way it should. Furthermore, I can't simply alter the whole query as most of it is built inside a C# code and basically the only part I have freedom to change that won't have an impact in any other part of the software is the select statement that corresponds to the domain (whatever comes in the NOT IN clause). I hope I made myself clear and someone out there could help me out.
Thanks in advance.
For NOT IN, it is always false if the subquery returns a NULL value. The accepted answer to this question elegantly describes why.
The NULLability of a column value is independent of the datatype used too: most likely your varchar columns has NULL values
Do deal with this, use NOT EXISTS. For non-null values, it works the same as NOT IN so is compatible
SELECT COUNT(*) FROM SomeTable S1
WHERE NOT EXISTS (SELECT * FROm SomeOtherTable S2 WHERE S1.[MyField] = S2.MyOtherField)
gbn has a more complete answer, but I can't be bothered to remember all that. Instead I have the religious habit of filtering nulls out of my IN clauses:
SELECT COUNT(*)
FROM SomeTable
WHERE [MyField] NOT IN (
SELECT MyOtherField FROM SomeOtherTable
WHERE MyOtherField is not null
)

MySQL question about "reverse LIKEs"

Well given I have a value I want to check for potential matches in a database (in one varchar field) so I write something like:
SELECT * FROM table WHERE column LIKE "%value%"
Which will work if the value is something like "test" and the column has a value of "this is a test" however if it is reversed then I will not get a match I have tried things along the lines of:
SELECT * FROM table WHERE CONCAT("%",column,"%") LIKE "value"
but don't know exactly how to phrase this to Google to get a response I need, please help!
You can reverse a like statement. Just using the same syntax as a regular like query:
select
*
from
table
where
'value' like concat('%', column, '%')
Of course, if you felt wild and crazy, you could also use instr:
select * from table where instr('value', column) > 0
I don't know which one is faster, since I don't have a MySQL instance to test against, but it's worth trying both to see which wins.
SELECT *
FROM table
WHERE 'value' LIKE CONCAT('%', column, '%')