Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the result of SELECT statement inside a transaction?

I can't get information of that simple question over the PostgreSQL documentation, over the Web or even here on StackOverflow... I must not understand something essential here.

I am making a simple SELECT/UPDATE transaction in PostgreSQL:

START TRANSACTION;
SELECT "column" FROM "table" WHERE "criterion" = 'value' AND "activated" = true;
UPDATE "table" SET "activated" = false WHERE "criterion" = 'value';
COMMIT

Basically, I need to get the value of a column when its activated state is true and then deactivate it. PostgreSQL tells me that there was a 1 row result that has been cancelled

The same happens if I do the following (basically the same transaction without the UPDATE statement):

START TRANSACTION;
SELECT "column" FROM "table" WHERE "criterion" = 'value' AND "activated" = true;
COMMIT

What don't I understand about transactions? Can't any SELECT output get out of a transaction block?

like image 247
Bernard Rosset Avatar asked Oct 24 '12 22:10

Bernard Rosset


People also ask

Is select statement is a transaction?

If all you are asking about is what the Isolation Level does, then understand that all Select statements (hey, all statements of any kind) - are in a transaction.

Should we use transaction for select query?

In a highly concurrent application it could (theoretically) happen that data you've read in the first select is modified before the other selects are executed. If that is a situation that could occur in your application you should use a transaction to wrap your selects.

What is the result of a select query?

The SQL SELECT statement is used to fetch the data from a database table which returns this data in the form of a result table. These result tables are called result-sets.

Can we use transaction in SQL function?

T-SQL Statements Allowed in a Transaction You can use all T-SQL statements in a transaction, except for the following statements: ALTER DATABASE, RECONFIGURE, BACKUP, RESTORE, CREATE DATABASE, UPDATE STATISTICS, and DROP DATABASE.


1 Answers

This will return all "column"'s values from the updated rows:

UPDATE "table" SET "activated" = false WHERE "criterion" = 'value' AND "activated" = true
returning "column";

There is no relation to the transaction.

returning will return the values as if a select was issued:

insert into foo (ticket, row, archived) values (3,7,true) returning *;
 ticket | row | archived 
--------+-----+----------
      3 |   7 | t

update foo
set archived = true
where not archived
returning *;
 ticket | row | archived 
--------+-----+----------
      2 |   5 | t
like image 50
Clodoaldo Neto Avatar answered Nov 13 '22 23:11

Clodoaldo Neto