How to test run an UPDATE statement in PostgreSQL? - sql

How can I test an UPDATE statement for example to see if it would work, for example if it would actually update rows etc?
Is there a way to simulate it easily?

Use a transaction to wrap your update statement and a select query (to test the update) and then always roll it back.
Example:
BEGIN;
UPDATE accounts SET balance = balance - 100.00
WHERE name = 'Alice';
SELECT balance FROM accounts WHERE name = 'Alice';
ROLLBACK; -- << Important! Un-does your UPDATE statement above!
A transaction typically ends with a commit but since you're just testing and do not want the changes to be permanent you will just roll back.

Wrap it in a transaction, test the results with a SELECT and rollback at the end.
BEGIN;
UPDATE ...;
SELECT ...;
ROLLBACK;

Prepend your SQL UPDATE command with EXPLAIN [ref], and it will tell you how many lines will be affected by your command. And it will not perform the actual update.
This is much simpler than wrapping your command in a transaction. E.g.:
EXPLAIN UPDATE accounts SET balance = balance + 100.00 WHERE name = 'Alice';

You could always build up a sample database on SQL Fiddle and try out your update statements there.
Full disclosure: I am the author of sqlfiddle.com

With Postgres you can use the UPDATE clause RETURNING to show which rows have been modificated.
-- example data
CREATE TABLE data(id int, text text);
INSERT INTO DATA VALUES(1,'aaa'),(2,'bbb'),(3,'ccc'),(4,'ddd');
-- original data
SELECT * from data;
-- dry-run update
BEGIN;
UPDATE
data
SET
text = 'modified'
WHERE
id > 2
RETURNING
id, text;
ROLLBACK;
-- data after dry-run update
SELECT * from data;

Run the same check with a SELECT statement first: the rows returned by SELECT will be the rows modified by UPDATE

Given this simple update:
UPDATE Products
SET price_including_vat = price * 1.05
WHERE product_type = 'Food';
I would test it using something like this:
SELECT price_including_vat AS price_including_vat__before,
price * 1.05 AS price_including_vat__after,
*
FROM Products
WHERE product_type = 'Food';
Actually, I'd proably engage brain and do analysis more like this:
WITH updated AS
(
SELECT price_including_vat AS price_including_vat__before,
price * 1.05 AS price_including_vat__after,
*
FROM Products
WHERE product_type = 'Food'
)
SELECT *
FROM updated
WHERE price_including_vat__before = price_including_vat__after;

Related

Snowfalke sql update if exists else insert

I have looked at other question but seems that snowflake doesn't support if/else in sql, at least not the way that other sql servers support it.
some suggested to use javascript but i would like to avoid that if I can.
I am trying to Insert into a table using snowflake python library some data, if it's already there then I would like to update the data, I have looked at merge but it doesn't seem to fit me since my data isn't a table
that's what I have so far that isn't working
f"""BEGIN
IF (EXISTS (SELECT * FROM {self.okr_table} WHERE kpi=TRUE AND Month(month)=MONTH(current_date()) AND year(month)=YEAR(current_date())))
THEN
UPDATE {self.okr_table} SET [DATA] = {json.dumps(self.data)} WHERE kpi=TRUE AND Month(month)=MONTH(current_date()) AND year(month)=YEAR(current_date()))
ELSE
INSERT INTO {self.okr_table} (month, data, kpi) SELECT current_date(),parse_json('{json.dumps(self.data)}'), true;
END"""
To perfrom INSERT/UPDATE it is better to use single MERGE statement
I have looked at merge but it doesn't seem to fit me since my data isn't a table
It is not an issue as source could be a table or subquery:
MERGE INTO {self.okr_table}
USING (SELECT PARSE_JSON({json.dumps(self.data)} AS data
, MONTH(current_date()) AS month
, YEAR(current_date()) AS year
) s
ON {self.okr_table}.KPI
AND MONTH({self.okr_table}.month) = s.month
AND YEAR({self.okr_table}.month) = s.year
WHEN MATCHED THEN UPDATE
WHEN NOT MATCHED THEN INSER ...;
IF/ELSE branching works in Snowflake:
BEGIN
IF (EXISTS (...)) THEN
UPDATE ... ;
ELSE
INSERT ... ;
END IF;
END;
Please note ; after each statement, END IF and parenthesis around condition.

SQL TRIGGER ON UPDATE

Hey guys i am trying to make a trigger to update the feild Bill.BillAmmount everytime a new row is added to Reading
The feild should = (Reading.MeterReading - Reading.LastMeterReading)*Resedent.Rate )
REDEDENT
BILL
READING
are the 3 tables
also thankyou sooo much
AFTER INSERT ON Reading
Begin
UPDATE bill
SET bill.BillAmount = (SELECT (Reading.MeterReading - Reading.LastMeterReading)*Resedent.Rate
FROM Reading, Resedent
WHERE Reading.ReadingID = ReadingID AND Resedent.AccountID = AccountID)
End;
DROP TRIGGER BILLAMOUNT_ON_INSERT; ```
In Oracle, a trigger should be referring to :NEW (or perhaps :OLD). In addition, Oracle doesn't support FROM in UPDATE statements.
I suspect you want something like this:
Begin
UPDATE bill b
SET BillAmount = (SELECT (:new.MeterReading - :new.LastMeterReading) * rs.Rate
FROM Resedent rs
WHERE rs.ReadingID = :new.AccountID
)
WHERE b.AccountId = :new.AccountId
End;
However, without more information about your data model, it is hard to be specific about what you really want to do.

Execute stored procedure in UPDATE T-SQL

I have next t-sql code
UPDATE
#f_contr_temp
SET
sum_percent = (EXEC get_f_contr_credit_delay_pz fct.f_contr, #date_loop, #sum_percent OUTPUT)
FROM
#f_contr_temp AS fct,
f_garanty AS fg
WHERE
fct.f_contr = fg.f_contr
Im trying to update sum_percent column but throw an exception what i can't execute procedure in update.
I have no idea, how update my column. Please help.
Use a temporary table to store result of your S.P. as follow:
CREATE TABLE #temp (percentage decimal(18,9))
INSERT INTO #temp
(EXEC get_f_contr_credit_delay_pz fct.f_contr, #date_loop, #sum_percent OUTPUT)
UPDATE
#f_contr_temp
SET
sum_percent = (select top 1 percentage from #temp)
FROM
#f_contr_temp AS fct,
f_garanty AS fg
WHERE
fct.f_contr = fg.f_contr
I suppose your S.P. return values, so I use TOP 1 command to get only the first.
Pay attention fct.f_contr, which is its source? In this way the query is not correct.

Sql update statement, any way of knowing what it actually did?

Typically, I test an update by running a query using the where statement and then after verifying that it does what I think I want it to copying the where clause to the update statement and executing it. But is there any way of getting the statement to return what the update did besides the '4 rows updated'
Sure, take a look at the output clause of T-SQL
http://msdn.microsoft.com/en-us/library/ms177564.aspx
You could load your records into a temp table/variable in SQL Server:
DECLARE #Temp TABLE(ID INT)
INSERT INTO #Temp (ID)
SELECT ID
FROM Customer
WHERE AcctBalance > 5000
--inspect as needed
UPDATE Customer
SET AcctBalance = 0
WHERE ID IN (SELECT ID FROM #Temp)
That depend in the server, library that you use, in php, pdo exec return number of row effected by delete or update cluase

Get the number of affected rows in a MySQL update statement?

I have stored procedure in MySQL, something like the below:
create procedure SP_Test (input1 varchar(20))
begin
update Table1 set Val1='Val' where country=input1;
//I want to see if this update changed how many rows and
//do some specific action based on this number
....
end
How can I determine how many rows were changed by this update?
Use ROW_COUNT():
SELECT ROW_COUNT();
one way, not very optimal is to simply do a select before you do the update.
select count(*) from table1 where country = 'country1'
Try the following code:
int mysql_affected_rows ([ resource $link_identifier = NULL ] )