I have a table with 50 columns. This table contains nulls in all the columns but in random. I want to update all the nulls with 'no data'. If there are nulls in 2 columns I can do it with
update tableName
set col1 = 'nodata'
where col1 is null
But, I have 50 columns like this, instead of writing an update command for all the columns, is there any other technique to complete it in a single line query.
You can use coalesce():
update tableName
set col1 = coalesce(col1, 'nodata'),
col2 = coalesce(col2, 'nodata'),
. . .;
If most rows have data in all columns, you can add a where clause:
where col1 is not null or col2 is not null or . . .
Note: This answers your question, but I don't think it is a good idea. NULL is a perfectly good way to represent "no data" in a SQL database. There is no need to update the values. In addition, this assumes that all columns are strings. This method will not work on other data types -- you will likely get a type conversion error.
Related
I have a column with codes. Now each code has been changed to something else. I am trying to update it. So I have used case statement in mysql. But the problem is, I have around 250,000 rows and 80,000 unique codes which need to be replaced. And the case statement is taking like 10 min to execute.
Any better approach to do this.
My query looks like this:
UPDATE test_table
SET code = CASE
WHEN code = "akdsfj" THEN "kadjsf"
WHEN code = "asdf" THEN "ndgs"
WHEN code = "hfgsd" THEN "gfdsd"
... (I am doing in batches of 1000 case statements at a time)
ELSE code
The case statement does add time, because it is searched.
The solution? Store the pairs in a temporary table . . . with an index. So:
create temporary table code_pairs (
old_code varchar(255) not null primary key,
new_code varchar(255)
);
insert into code_pairs(old_code, new_code)
values ('akdsfj', 'kadjsf'),
('asdf', 'ndgs'),
. . . ;
Then use update with join:
update test_table tt join
code_paris cp
on tt.code = cp.old_code
set tt.code = cp.new_code;
This saves you time because the matching code is found using the index, rather then searching one-by-one through a case statement. In addition, no update is attempted on rows that have no match. The 170,000 rows with no match are probably the slowest part of the query, because they need to go through the entire list of case values.
My database is in MySQL
I have a table, let's say of 4 columns.
I would like to know if it's possible, and how to implement the following: fill the 4th column according to the value of the column 2 and column 3
In Excel I have a formula, let's give an example: if column2 value is set to "grey" and column3 value is set to "car", then column 4 value should be set to "super"
I just say this as an example.
My real formula in Excel looks like this: =IF(K4=4;"Maximal";IF(K4>4;"Maximal";IF(K4=3;"Important";IF(K4>3;"Important";IF(K4=2;"Limited";IF(K4>2;"Limited";IF(K4=1;"Forgettable";IF(K4>1;"Forgettable";"error"))))))))
However I want to do it in SQL.
I was thinking of creating my table until the column 3, set column 4 to NULL or empty, then open a GUI written in Java and maybe there do a piece of code to automatically fill the column 4 according to what is in column 2 and column 3 (these values will be choosable via Choicelist).
But if there is a way to do it directly in SQL, I am interested
Thx a lot in advance for your help.
regards
Yes. you can easily update your NULL-values according to some requirements for the other values in other columns of a particular row with the Update statement
UPDATE <tablename>
SET <column> = 'value'
WHERE <condition>
The only drawback here might be that you have to create an update statement for each of the combinations of your values in column2 and column3. (however, it's not much work for your amount of conditions).
I created an example (demo):
Creating a table in SQL according to your example could look like this,I used a temporary one for the sake of an example:
CREATE GLOBAL TEMPORARY TABLE demoTable (
"Col1" VARCHAR2(50 BYTE) NOT NULL,
"Col2" VARCHAR2(50 BYTE) NOT NULL,
"Col3" VARCHAR2(50 BYTE) NOT NULL,
"Col4" VARCHAR2(50 BYTE) DEFAULT NULL
)
ON COMMIT PRESERVE ROWS
I also inserted some dummy data:
INSERT INTO demoTable VALUES ('Charles', 'grey', 'car', NULL);
INSERT INTO demoTable VALUES ('Alice', 'grey', 'bike', NULL);
INSERT INTO demoTable VALUES ('Bob', 'red', 'car', NULL);
The result:
Now, create the update statements like this, for example:
UPDATE demoTable dt
SET dt."Col4" = 'super'
WHERE dt."Col2" = 'grey' AND dt."Col3" = 'car';
The result
You can try like this;
select * from mytable
COL1 COL2
---- --------------------
0 -
1 -
2 -
3 -
4 -
4 record(s) selected.
update mytable Set Col2 =
Case
When Col1<1 Then 'error'
When Col1=1 Then 'Forget'
When Col1=2 Then 'Limited'
When Col1=3 Then 'Important'
When Col1=4 Then 'Maximal'
End"
select * from mytable"
COL1 COL2
---- --------------------
0 Error
1 Forget
2 Limited
3 Important
4 Maximal
4 record(s) selected.
You can create a sql function, lets say udfGetColumn4Value taking in the column2, column3 as parameters to it and return a value.
Now you can run a select column2, column3, udfGetColumn4Value(column2, column3) from table or a query as desired. Hope this helps.
You were not very precise regarding which DBMS you're using. And also about the exact logic behind using your two columns.
Still here comes a probable SQL-Server solution, where I have taken one statement using CASE WHEN with your example and concatenated your two columns col2 and col3 (you can apply your further logic of here) otherwise:
UPDATE TableName
SET Col4 = CASE WHEN col2 = 'red' AND col3 = 'car' THEN 'super' ELSE col2 + col3 END;
You should replace col2 + col3 with your further logic.
Seems that a simple UPDATE-Query could address your problem:
update things set result = "super" where thing = "car" and color = "grey";
The where-clause does what you desire to do by saying
fill the column 4 according to what is in column 2 and column 3
I created a test table here on turorialspoint, there you can check if it fits your needs.
I am running some SQL queries from command line as follows:
cat my_query.sql | mysql --defaults-file=my_conf.cnf
I need to print column names whether the query returns any data or not.
Currently when there is no data to return, i.e when query returns an empty result set this command does not print anything.
For example my query is:
-- id=-1 doesn't exist
SELECT col1, col2 FROM table WHERE id=-1
I need this query to return
col1 col2
Instead it returns nothing.
Is it possible to do that using purely mysql and standard unix commands?
Thanks.
Adding a UNION ALL to a SELECT with "dummy"/blank data might work:
SELECT col1, col2 FROM table WHERE id=-1
UNION ALL
SELECT '', '' -- OR 0, 0 whatever is appropriate
;
I don't run queries from the command line, so this is assuming it normally would give you the column names if you had at least one row in the results.
In my SQL tables there are rows where columnX has empty value (""). Now i want them i queried to select them and then delete them.
Query like:
tables has empty rows
Delete empty rows
How can i do this. Any idea
Depending on what exactly you mean by "empty" rows:
delete from yourTable where column1 is null
will delete where column1 has a null value. If you mean where multiple columns have nulls, it's just a matter of adding more conditions to the where clause:
delete from yourTable where column1 is null and column2 is null and column3 is null
If by empty you mean "has spaces in a text field or the field is empty" you can use some of the builtin functions to find them for example:
delete from yourTable where trim(column1)=''
which would find a row in the table where column1 only has white space in it and so on.
You might want to have a read of this article that I wrote on SQL, join and the like - it has got a fair bit in it about selecting the right rows from the table - and in your case, replace the select.... from where... with a delete from where...
Having said all that, I would really wonder why you are inserting data into your table that you don't want in it?
You can check each field for null or the empty string like this:
DELETE FROM table WHERE (column1 IS NULL OR column1 = '') AND (column2 IS NULL OR column2 = '')
Just add the rest of your columns to the WHERE clause.
Simple : delete from Test_table where c1 is null,....and cN is null
Ok Try this, i hope u'll find your solution
What you need is, first get empty rows
Select * From table_name Where column_name = "";
Then Delete the empty rows
Delete From table_name Where column_name = "";
or don't write the select query only write the delete query
I hope this solve your problem
I want to update multiple records at once using a similar method to this:
Multiple Updates in MySQL
but is there a MySQL command to ignore anything that isnt a duplicate? Something like
ON DUPLICATE UPDATE ON UNIQUE IGNORE
(ive just made this code up btw)
?
Why can't we use a single UPDATE command that can update MULTIPLE rows!
UPDATE mytable
SET Col2 = CASE
WHEN Col1 = 1 THEN 'new Value From someplace';
WHEN Col1 = 2 THEN 'War and Peace';
ELSE Col2
END
The ELSE Col2 is very important, otherwise you will overwrite the rest of the table with NULL.
You can add more CASE blocks to update more columns.
By doing this you can avoid the headache of INSERTING UNIQUE records.
Hope this helps.