How i can to insert after select statement in SQL? - sql

I using django framework and Postgresql develop my project. But I have a problem when many user requests at the same time. It will double inserted data when server is slow. For this reason, I will try to prevent in SQL. I want to know how to SELECT, then INSERT in one command.
Such as
is_created = select created_at,product from payment where created_at=current_date,product_id = '1'
if is_created == False then
insert into table (...) values (....)

postgreSQL supports conditionals you may find this helpful
https://www.postgresql.org/docs/current/functions-conditional.html
example
CASE expression
WHEN value THEN result
[WHEN ...]
[ELSE result]
END

Related

Using Regex to determine what kind of SQL statement a row is from a list?

I have a large list of SQL commands such as
SELECT * FROM TEST_TABLE
INSERT .....
UPDATE .....
SELECT * FROM ....
etc. My goal is to parse this list into a set of results so that I can easily determine a good count of how many of these statements are SELECT statements, how many are UPDATES, etc.
so I would be looking at a result set such as
SELECT 2
INSERT 1
UPDATE 1
...
I figured I could do this with Regex, but I'm a bit lost other than simply looking at everything string and comparing against 'SELECT' as a prefix, but this can run into multiple issues. Is there any other way to format this using REGEX?
You can add the SQL statements to a table and run them through a SQL query. If the SQL text is in a column called SQL_TEXT, you can get the SQL command type using this:
upper(regexp_substr(trim(regexp_replace(SQL_TEXT, '\\s', ' ')),
'^([\\w\\-]+)')) as COMMAND_TYPE
You'll need to do some clean up to create a column that indicates the type of statement you have. The rest is just basic aggregation
with cte as
(select *, trim(lower(split_part(regexp_replace(col, '\\s', ' '),' ',1))) as statement
from t)
select statement, count(*) as freq
from cte
group by statement;
SQL is a language and needs a parser to turn it from text into a structure. Regular expressions can only do part of the work (such as lexing).
Regular Expression Vs. String Parsing
You will have to limit your ambition if you want to restrict yourself to using regular expressions.
Still you can get some distance if you so want. A quick search found this random example of tokenizing MySQL SQL statements using regex https://swanhart.livejournal.com/130191.html

Error when using INSERT INTO inside CASE statement

I'm trying to insert values into a table inside a CASE statement, but I'm getting the error "missing expression" in my INSERT INTO.
What is the correct way to use INSERT INTO within CASE? You can find the code below. I am using this SELECT statement in a procedure, and I'm putting the result of this into a cursor.
SELECT
COALESCE(a.file_type,b.file_type) AS file_type,a.input AS a_input,b.input AS b_input,a.output AS a_output,b.output AS b_output,
CASE WHEN a.input = b.input THEN
input_num+1
WHEN a.input <> b.input THEN
INSERT INTO diff_values(file_type,a_input,b_input,report_date)
SELECT file_type,a.input,b.input FROM test1 a, tset2 b WHERE
a.file_type=b.file_type
WHEN a.output = b.output THEN
out_num+1
END CASE
FROM
test1 a, tset2 b
WHERE a.file_type=b.file_type
AND a.report_date=b.report_date;
You cannot embed a DML statement (e.g. INSERT) within a SQL query.
You cannot embed a CASE statement (which is PL/SQL) within a SQL query. You can embed a CASE expression within a SQL query, however, but the expression can only evaluate a result, it cannot include PL/SQL (see #1 above)*.
The outcome you seem to want to achieve is to query some data from two tables (test1 and tset2), evaluate an expression, and insert the result back into the same tables as new records. Since your final outcome is an INSERT, you would start with that and then create a query that gathers the data needed for it, e.g.:
INSERT INTO diff_values(file_type,a_input,b_input,report_date)
SELECT a.file_type,
a.input,
b.input,
a.report_date
FROM test1 a, tset2 b
WHERE a.file_type=b.file_type
AND a.report_date=b.report_date
AND a.input <> b.input;
Note that I've removed the COALESCE because the WHERE clause guarantees both a.file_type and b.file_type are identical anyway, so you can just refer to one of those columns.
Now, your original statement included the following lines as well:
WHEN a.input = b.input THEN
input_num+1
...
WHEN a.output = b.output THEN
out_num+1
I don't know what these are supposed to do, but I suppose you could write additional queries to detect these conditions and output the results.
technically, in Oracle 12.1 you can include procedural code in a WITH clause within SQL https://oracle-base.com/articles/12c/with-clause-enhancements-12cr1

Update multiple values in an oracle table using values from an APEX collection

I am using APEX collections to store some values and pass them between pages in Oracle Application Express 4.2.3.
I would like to then perform an update statement on a table called "project" with the values from the collection.
My code so far is as follows:
update project
SET name=c.c002,
description=c.c007,
start_date=c.c004,
timeframe=c.c005,
status=c.c009
FROM
apex_collections c
WHERE
c.collection_name = 'PROJECT_DETAILS_COLLECTION'
and id = :p14_id;
where :p14_id is the value of a page item.
However, I am getting the following error:
ORA-00933: SQL command not properly ended
Anyone have any idea on how to approach this?
Thanks!
The UPDATE syntax you are using is not valid in Oracle; it does not allow you to use FROM in the way you are attempting.
The simplest way to do this in Oracle would with a subquery:
update project
set (name, description, start_date, timeframe, status) =
(select c.c002, c.c007, c.c004, c.c005, c.c009
FROM
apex_collections c
WHERE
c.collection_name = 'PROJECT_DETAILS_COLLECTION'
)
WHERE
id = :p14_id
;
Note that if the subquery returns no rows, the columns in the target table will be updated to NULL; this could be avoided by adding a similar EXISTS condition in the predicate for the update. It could also be avoided by using a MERGE statement instead of an UPDATE.
If the subquery returns multiple rows, the statement will throw an error. It looks like tthat should not be the case here.

How to write a update SQL using a select SQL

I want to write a update SQL statement, but one conidtion of this statement is the result from a select SQL statement, and I also want to return the result of the select SQL statement.
Like this: update ... set ... where id = (select id from ...)
I want to return the value of id back.
Does anybody know how should I do this?
Thanks in advance!
I don't believe that's possible in one statement. Update then query (select) the new value, or query the value first, and then submit an update.
Alternative would be a stored procedure on the database, which executes the multiple queries and returns the result for you.
This is not possible in all Java database frameworks that I know. Probably you need to separate your query and update in Java.
I don't see any problem in using a subselect in a WHERE clause of an update statement.
For the second request, getting back the value of id, I know this is possible in DB2, and maybe others implement that syntax too:
SELECT id FROM FINAL TABLE (
update ... set ... where id = (select id from ...)
)
This works also for INSERT and DELETE statements. (See the documentation.)
Update statements won't return the updated datasets. The select in that case would be a subselect that isn't directly accessible.
You'd thus have to use at least two queries:
select the ids you want
call the update query passing the previously selected ids as a parameter

Why do SQL INSERT and UPDATE Statements have Different Syntaxes?

While contemplating this question about a SQL INSERT statement, it occurred to me that the distinction in syntax between the two statements is largely artificial. That is, why can't we do:
INSERT INTO MyTable SET Field1=Value1, Field2=Value2, ...
or
UPDATE MyTable ( Field1, Field2 ...) VALUES ( Value1, Value2, ... )
WHERE some-key = some-value
Perhaps I'm missing something critical. But for those of us who have had to concatenate our SQL statements in the past, having comparable syntax for an INSERT and an UPDATE statement would have saved a significant amount of coding.
They're serving different grammatical functions. In an update you are specifying a filter that chooses a set of rows to which you will apply an update. And of course that syntax is shared with a SELECT query for the same purpose.
In an INSERT you are not choosing any rows, you are generating a new row which requires specifying a set of values.
In an UPDATE, the LHS=RHS stuff is specifying an expression which yields true or false (or maybe null :) and in an INSERT, the VALUES clause is about assignment of value. So while they are superficially similar, they are semantically quite different, imho. Although I have written a SQL parser, so that may influence my views. :)
SQL Server 2008 has introduced UPSERT functionality via the MERGE command. This is the logical equivalent of
IF FOUND THEN
UPDATE
ELSE
INSERT
I believe this is so that you may make an insert statement without being explicit about the values. If you are putting a value in every single column in the table you can write:
insert into my_table values ("value1", 2);
instead of:
insert into my_table (column1, column2) values ("value1", 2);
When importing and exporting entire (large) databases, this is invaluable for cutting down file size and processing time. Nowadays, with binary snapshots and the like, it may be "less invaluable" :-)