SQL Replace entire row with value - sql

So I have a row in a table which contains 300 randomly generated hashes. I would like to replace all of them with one specific hash. How could I write a query that replaces every value in said table with my specific hash? Right now my query looks like:
SELECT TOP 1000 [Hash]
FROM [x].[y].[z]
X/Y/Z are different in my query obviously. However I do not know how I can then replace every value in the top 1000 Hashes with my specific hash.

UPDATE [x].[y].[z]
SET Hash = 'OneHashToRuleThemAll'
No WHERE condition will update the entire table. Make sure this is what you want.

Use self inner join to update just the top 1000, like below. Note that I replaced TOP with LIMIT since we are talking about MySQL
UPDATE [x].[y].[z] XYZ
INNER JOIN
(
select SOME_KEY_FROM_XYZ from [x].[y].[z] LIMIT 1000
) ZYX ON XYZ.SOME_KEY_FROM_XYZ = ZYX.SOME_KEY_FROM_XYZ
SET Hash = 'OneSpecificHash'

Related

PostgreSQL can't update a column with content of another column

checked several threads and some did help but now I'm getting an error:
ERROR: more than one row returned by a subquery used as an expression
SQL state: 21000
Not sure what's the exact issue even though read some explanations. Would appreciate if someone could explain with using my code bellow.
I have a table / view called vw_inv_stock_art_global, and it has a column "stock" with a number.
Then also I have a table dis_orderoutdetails with a column "onstock" which needs to copy the "stock" cells based on article_id both tables have in common.
UPDATE dis_orderoutdetails
SET onstock = (SELECT stock
FROM vw_inv_stock_art_global
WHERE vw_inv_stock_art_global.article_id = dis_orderoutdetails.article_id)
WHERE onstock is NULL
AND EXISTS(SELECT stock
FROM vw_inv_stoc_art_global
WHERE vw_inv_stock_art_global.article_id = dis_orderoutdetails.article_id);
Additional help if you can be bothered:
I was wondering if there's a possibility to change background colour of a cell just in SQL? Wanted to make an if...else and change colours of a cell depending on the result.
The problem is with this part of the statement:
SET onstock = (SELECT stock
FROM vw_inv_stock_art_global
WHERE vw_inv_stock_art_global.article_id = dis_orderoutdetails.article_id)
The SELECT query returns more than one row => there are more than one row in the vw_inv_stock_art_global view that has this article_id. If the result of a SELECT is to be used as a value there may only be one matching row.
Not sure about Postgres SQL syntax but it seems you would use LIMIT 1 to solve this.
SET onstock = (SELECT stock
FROM vw_inv_stock_art_global
WHERE vw_inv_stock_art_global.article_id = dis_orderoutdetails.article_id LIMIT 1)
However when you use LIMIT you probably need to use an ORDER BY clause as well to make sure that you use the most relevant row, not just any single row that matches the criterion. The most relevant row is most of the times the latest, so if there is some date column that specifies the entry of the row it is a good bet to be the column you need to order on. This is something you need to review according to your needs.
The ORDER BY would be inserted like this:
(Place holder needs to be replaced)
SET onstock = (SELECT stock
FROM vw_inv_stock_art_global
WHERE vw_inv_stock_art_global.article_id = dis_orderoutdetails.article_id
ORDER BY <some column>
LIMIT 1)
You can refactor your SQL without using subqueries, like:
UPDATE dis_orderoutdetails
SET onstock = g.stock
FROM vw_inv_stock_art_global
WHERE vw_inv_stock_art_global.article_id = dis_orderoutdetails.article_id
and onstock is NULL;
But be aware that the correctness of this SQL depends on the relationship between dis_orderoutdetails(article_id) and vw_inv_stock_art_global(article_id): article_id isn't a unique column in vw_inv_stock_art_global, this UPDATE won't be predictable, as each dis_orderoutdetails could be updated more than once, with different stock values.

Compare tables and Find the missing records

I am trying to compare a table T1 and a view v1 and find the missing records from the table T1 and display the results in a excel when a button is clicked. I am trying the wrap up the situation into a stored procedure and call it from vba code. I am not sure on how to start this.. The field names are different in both the tables, although it has same data. Any help will be much appreciated. I have tried many code samples , but I didn't achieve what I want..
Table T1
alpha.FileID
Master Policy Number
Insurance Name
View V1
FileID
PolNO
InsName
These are the few columns. Though, they have different field names, the data are the same. Some times the records are missing in the table v1, and I need to compare the two tables and find the missing records of the table v2.
SELECT View_v1.[Insured Name]
FROM View_v1
WHERE View_v1.alpha.FileID NOT IN
(
SELECT Table_t1.FileID
FROM Table_t1
)
An except clause is the easiest way to do this:
SELECT FileID, PolNO, InsName
FROM View V1
EXCEPT
SELECT FileID, MasterPolicyNumber, InsuranceName
FROM Table T1
This will give you the rows in the first select that do not exist in the second select (depending on your desired results you might flip the top and bottom selects). As long as the data types and number of columns are the same, the name of each field doesn't matter. Your result set will show the field names of the first select.
Also since you didn't specify your dbms, "MINUS" is used instead of "EXCEPT" for some dbms's like Oracle.
I believe this is what you're looking for based on your description.
I'm comparing every field, not just FileID as your example appears to be attempting. So, if you truly want to look only for missing FileIDs, just remove the other join on conditions.
SELECT View_v1.FileID, View_v1.PolNO, View_v1.InsName
FROM View_v1
LEFT JOIN Table_t1
on View_v1.FileID = Table_t1.FileID
and View_v1.PolNO = Table_t1.[Master Policy Number]
and View_v1.InsName = Table_t1.[Insurance Name]
WHERE Table_t1.FileID is null

Compare comma separated list with individual row in table

I have to compare comma separated values with a column in the table and find out which values are not in database. [kind of master data validation]. Please have a look at the sample data below:
table data in database:
id name
1 abc
2 def
3 ghi
SQL part :
Here i am getting comma separated list like ('abc','def','ghi','xyz').
now xyz is invalid value, so i want to take that value and return it as output saying "invalid value".
It is possible if i split those value, take it in temp table, loop through each value and compare one by one.
but is there any other optimal way to do this ??
I'm sure if I got the question right, however, I would personally be trying to get to something like this:
SELECT
D.id,
CASE
WHEN B.Name IS NULL THEN D.name
ELSE "invalid value"
END
FROM
data AS D
INNER JOIN badNames B ON b.Name = d.Name
--as SQL is case insensitive, equal sign should work
There is one table with bad names or invalid values if You prefer. This can a temporary table as well - depending on usage (a black-listed words should be a table, ad hoc invalid values provided by a service should be temp table, etc.).
NOTE: The select above can be nested in a view, so the data remain as they were, yet you gain the correctness information. Otherwise I would create a cursor inside a function that would go through the select like the one above and alter the original data, if that is the goal...
It sounds like you just need a NOT EXISTS / LEFT JOIN, as in:
SELECT tmp.InvalidValue
FROM dbo.HopeThisIsNotAWhileBasedSplit(#CSVlist) tmp
WHERE NOT EXISTS (
SELECT *
FROM dbo.Table tbl
WHERE tbl.Field = tmp.InvalidValue
);
Of course, depending on the size of the CSV list coming in, the number of rows in the table you are checking, and the style of splitter you are using, it might be better to dump the CSV to a temp table first (as you mentioned doing in the question).
Try following query:
SELECT SplitedValues.name,
CASE WHEN YourTable.Id IS NULL THEN 'invalid value' ELSE NULL END AS Result
FROM SplitedValues
LEFT JOIN yourTable ON SplitedValues.name = YourTable.name

insert a random number into each row in table

I currently have an oracle table (lovalarm) containing around 600,000 rows. I need to be able to run a query which will cycle through each row and update a field (lovsiteid) to a random number between 14300 and 17300.
So far I have:
update lovalarm
set lovsiteid = (select TRUNC(dbms_random.value(14300,17300)) FROM dual)
Sadly this picks a random number and then updates all rows with the same number which isn't exactly what I'm after!
Can anyone point me in the right direction?
Many thanks,
Cap
Just not use subquery:
update lovalarm
set lovsiteid = TRUNC(dbms_random.value(14300,17300))
Try this:
update lovalarm set lovsiteid = (select FLOOR(RAND() * (17300 - 14300) + 14300))
works in MySQL

Check whether a table contains rows or not sql server 2005

How to Check whether a table contains rows or not sql server 2005?
For what purpose?
Quickest for an IF would be IF EXISTS (SELECT * FROM Table)...
For a result set, SELECT TOP 1 1 FROM Table returns either zero or one rows
For exactly one row with a count (0 or non-zero), SELECT COUNT(*) FROM Table
Also, you can use exists
select case when exists (select 1 from table)
then 'contains rows'
else 'doesnt contain rows'
end
or to check if there are child rows for a particular record :
select * from Table t1
where exists(
select 1 from ChildTable t2
where t1.id = t2.parentid)
or in a procedure
if exists(select 1 from table)
begin
-- do stuff
end
Like Other said you can use something like that:
IF NOT EXISTS (SELECT 1 FROM Table)
BEGIN
--Do Something
END
ELSE
BEGIN
--Do Another Thing
END
FOR the best performance, use specific column name instead of * - for example:
SELECT TOP 1 <columnName>
FROM <tableName>
This is optimal because, instead of returning the whole list of columns, it is returning just one. That can save some time.
Also, returning just first row if there are any values, makes it even faster. Actually you got just one value as the result - if there are any rows, or no value if there is no rows.
If you use the table in distributed manner, which is most probably the case, than transporting just one value from the server to the client is much faster.
You also should choose wisely among all the columns to get data from a column which can take as less resource as possible.
Can't you just count the rows using select count(*) from table (or an indexed column instead of * if speed is important)?
If not then maybe this article can point you in the right direction.
Fast:
SELECT TOP (1) CASE
WHEN **NOT_NULL_COLUMN** IS NULL
THEN 'empty table'
ELSE 'not empty table'
END AS info
FROM **TABLE_NAME**