Is there a way to run an insert query in the IF statement, As I know the syntax for if statement is
IF(conditon, execute if condition is True, execute if condition is False)
My question is whether if it is possible run an insert statement based on the conditions, like
IF((select count(*) from table where id = x) = 0, insert1, insert2)
insert1 will be a direct insert like
insert into table (col1,col2..) values (val1, val2..)
insert2 will fetch the previous value with the id whose count is not 0 and then do some logic and then insert the query looks like
insert into table (col1, col2, col3..) select val1,val1+val2,someOperation from table where id = x;
I think you need something like this :
IF( select count(*) from Table1 ) is null
begin
IF( select count(*) from Table1 ) is null
begin
--execute if condition is True
--insert condition
end
IF( select count(*) from Table1 ) is not null
begin
--execute if condition is False
--insert condition
end
end
MYSQL example :
IF ((select count(*) from table where id = x)) = 0
THEN
--insert into table (col1,col2..) values (val1, val2..)
ELSE
IF ((select count(*) from table where id = x)) != 0
THEN
--insert into table (col1, col2, col3..) select val1,val1+val2,someOperation from table where id = x;
END IF;
END IF;
Related
Is it possible to insert multiple rows while checking each new row against a condition? I know that you can run a simple insert into with multiple rows
INSERT INTO table (a,b,c) VALUES (1,2,3),(4,5,6),(7,8,9)
AND
INSERT INTO table (a,b,c) VALUES (1,2,3),(4,5,6),(7,8,9)
ON DUPLICATE KEY UPDATE a=VALUES(a), b=VALUES(b), c=VALUES(c)
I am attempting to do something like this
INSERT INTO x_table(a,b,c)
SELECT VALUES(a),VALUES(b),VALUES(c)
FROM y_table
WHERE NOT EXISTS (SELECT * FROM x_table
WHERE a != VALUES(a)
AND b != VALUES(b))
Test Example (Tested and Working)
INSERT INTO `table` (id, timestamp, v1, v2, v3, v4, v5)
SELECT id, timestamp, v1, v2, v3, v4, v5
FROM (SELECT 6783 AS id, FROM_UNIXTIME('1580194194') AS timestamp, 1 AS v1, 0 AS v2, 1 AS v3, 0 AS v4, 45 AS v5
UNION ALL
SELECT 6845,FROM_UNIXTIME('1580194194'),1,0,1,0,107
UNION ALL
SELECT 6973,FROM_UNIXTIME('1580194194'),1,0,1,0,234
) y
WHERE NOT EXISTS (SELECT * FROM `table` x WHERE x.v1 = y.v1 AND x.v3 = y.v3 AND x.v5 = y.v5 ORDER BY TIMESTAMP DESC LIMIT 1)
You can write something like this:
INSERT INTO x_table
SELECT a, b, c
FROM (SELECT 1 AS a, 2 AS b, 5 AS c
UNION ALL
SELECT 4, 5, 6
UNION ALL
SELECT 7, 8, 9
) y
WHERE NOT EXISTS (SELECT * FROM x_table x WHERE x.a = y.a AND x.b = y.b)
Note that I think your EXISTS clause needs to use =, not != otherwise it will be true unless there is only 1 row in x_table which has matching a and b values to the first row to be inserted.
Demo on dbfiddle
You can do some checks in before insert trigger. Something like this:
CREATE TRIGGER `TRG_x_table_before_insert` BEFORE INSERT ON `x_table` FOR EACH ROW BEGIN
SET #found = NULL;
SELECT
a INTO #found
FROM
y_table
WHERE
a = NEW.a
AND b = NEW.b
;
IF #found IS NOT NULL THEN
SET #msg = 'Insert failed';
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = #msg;
END IF;
END
I am currently using the SQL command
Select * from where name='john'
Is it possible to return 20 no matter the query, for example
Select * from where name='john' or return = 20
EDIT
If you have an oracle database you can do something like that:
SELECT *
FROM dual
WHERE 1=0
UNION
SELECT '20'
FROM dual;
check my answer
if exists (Select * from item where ItemName='ABC Daycare1')
begin
Select * from item where ItemName='ABC Daycare1'
end
else
select '20'
Try running this. This should return the top result (which is never 20 due to the custom sort) and then when the name doesn't match a value it returns 'Mark' and 20
SQL
IF OBJECT_ID('tempdb..#temp') IS NOT NULL DROP TABLE #temp
CREATE TABLE #temp (id int NOT NULL, name varchar(255) NOT NULL)
INSERT INTO #temp (id, name) VALUES (88,'John')
INSERT INTO #temp (id, name) VALUES (20,'Mark')
SELECT TOP 1
*
FROM #temp
WHERE (name = 'Mark' OR name = 'John')
ORDER BY (
CASE
WHEN id = 20 THEN 0 ELSE 1
END) DESC
MySQL - MySQL fiddle
IF OBJECT_ID('tempdb..#temp') IS NOT NULL DROP TABLE #temp
CREATE TABLE #temp (id int NOT NULL, name varchar(255) NOT NULL)
INSERT INTO #temp (id, name) VALUES (88,'John')
INSERT INTO #temp (id, name) VALUES (20,'Mark')
SELECT
*
FROM temp
WHERE (name = 'Mark' OR name = 'John')
ORDER BY (
CASE
WHEN id = 20 THEN 0 ELSE 1
END) DESC
LIMIT 1
I have a query that regularly returns "nothing", and I would like to run a different query if this is the case, but I know not of the way of doing this. If anyone could be of help please.
Here is the current code I am using...
SELECT * FROM cfg_users JOIN cfg_ash ON cfg_users.iUserId = cfg_ash.iUserid WHERE iTeamId='0' AND sDisabled IS NULL AND iStatusId > 0 AND sDate = '2014-08-01' GROUP BY cfg_users.iUserId ORDER BY iStatusId, sName
I basically want to say
IF <my code> IS NULL THEN <do other code>, IF <my code> IS NOT NULL THEN return the result.
Thanks
There are some simple way only use sql.
Define your first query as a temp table, with union all, filter the second query with temp table's count.
with temp as (select * from t1 where 1=0)
select * from temp
union all
select * from t2 where (select count(*) from temp) =0
This query will return the second table's records.
with temp as (select * from t1 )
select * from temp
union all
select * from t2 where (select count(*) from temp) =0
And if temp query have result, only return temp query.
You can test with sql fiddle here.
A way you can do it is like this
set two variables equal to the queries you want to execute.
set another variable equal to the correct query when the first is not null.
execute that query with a stored procedure.
STORED PROCEDURE:
DELIMITER $$
CREATE PROCEDURE `dynamic_query`(in input varchar(255))
BEGIN
SET #a := input;
PREPARE stmt FROM #a;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
$$
DELIMITER ;
THE TWO SELECTS YOU WANT TO EXECUTE:
SET #A := "SELECT * FROM cfg_users JOIN cfg_ash ON cfg_users.iUserId = cfg_ash.iUserid WHERE iTeamId='0' AND sDisabled IS NULL AND iStatusId > 0 AND sDate = '2014-08-01' GROUP BY cfg_users.iUserId ORDER BY iStatusId, sName";
SET #B := "your other select here";
THE DEFINER TO GET THE CORRECT QUERY:
SET #C := (
SELECT
CASE
WHEN EXISTS
( SELECT *
FROM cfg_users
JOIN cfg_ash ON cfg_users.iUserId = cfg_ash.iUserid
WHERE iTeamId='0'
AND sDisabled IS NULL
AND iStatusId > 0
AND sDate = '2014-08-01'
GROUP BY cfg_users.iUserId
ORDER BY iStatusId, sName
)
THEN #A
ELSE #B
END
);
EXECUTE THE STATEMENT:
CALL dynamic_query(#C);
DEMO WHEN THE QUERY EXISTS
DEMO WHEN THE QUERY DOESN'T EXIST
You can store the results in a temporary table / table variable, and then check the count
e.g.
CREATE TABLE #Results ( --columns you need here )
INSERT INTO #Results SELECT *
FROM cfg_users
JOIN cfg_ash ON cfg_users.iUserId = cfg_ash.iUserid WHERE iTeamId='0' AND sDisabled IS NULL AND iStatusId > 0 AND sDate = '2014-08-01'
GROUP BY cfg_users.iUserId
ORDER BY iStatusId, sName
SET #Count = SELECT COUNT(*) FROM #Results
IF 0 = #Count THEN
INSERT INTO #Results -- Other Query Here
SELECT * FROM #Results
n.b. you should really specify what columns you want in both queries rather than using *
I want a query to insert a row into a table I know it is simple but the scenario is the table should not have more than 5 rows. If table has more than five rows I need to remove the old row(Or replace with new row ) (Based on the insert time stamp) then i need to insert a new row.If number of rows less than count 5 then i can directly insert a row.
Please share me the query.
How about something like this.
declare #count int
SELECT #count=COUNT(*)
from EP_ANSWERS
IF (#count<5)
// DO your insert here
ELSE
DELETE FROM TABLE
WHERE inserttimestamp = (SELECT x.inserttimestamp
FROM (SELECT MAX(t.inserttimestamp) AS inserttimestamp
FROM TABLE t) x)
// DO your insert here
If it is impossible for the table to have more than 5 rows:
DELETE FROM yourtable
WHERE 5 <= (SELECT COUNT(*) FROM yourtable)
AND yourtimestamp = (SELECT MIN(yourtimestamp) FROM yourtable)
;
INSERT INTO yourtable ...
;
If it is possible for the table to have more than 5 rows:
DELETE FROM yourtable
WHERE 5 <= (SELECT COUNT(*) FROM yourtable)
AND yourtimestamp NOT IN (SELECT yourtimestamp
FROM yourtable
ORDER BY yourtimestamp DESC
LIMIT 4)
;
INSERT INTO yourtable ...
;
It sounds like you want to put a trigger on the table to maintain this rule, in MySQL the something like this should work
CREATE TRIGGER trg__my_table__limit_rows
BEFORE INSERT
ON my_table
FOR EACH ROW
BEGIN
IF ((SELECT COUNT(1) FROM my_table) = 5)
BEGIN
DELETE FROM my_table
WHERE id = (SELECT MIN(id) FROM my_table) -- change this to fit your logic for which record should be removed
END
END
Some of the code here is in pseudo (you didn't wrote your schema), but i wrote where you need to complete your own code.
DECLARE #NumberOfRowsToInsert INT = -- select from the data you want to insert
DECLARE #MaxNumberOfRows INT = 5
DECLARE #NumberOfExistingRows INT
DECLARE #Query VARCHAR(MAX) = 'SELECT TOP #rows id FROM SomeTable ORDER BY createdDate ASC'
SELECT #NumberOfExistingRows = COUNT(*)
FROM SomeTable
SET #Query = REPLACE(#Query,'#rows',
CAST(#NumberOfRowsToInsert - (#MaxNumberOfRows - #NumberOfExistingRows))) AS VARCHAR(1))
CREATE TABLE #IdsToDelete(id INT PRIMARY KEY)
INSERT INTO #IdsToDelete
EXEC(#Query)
DELETE FROM SomeTable
WHERE id IN (SELECT * FROM #IdsToDelete)
-- insert here..
I'm trying to insert a record if a sum of 3 user columns from 2 tables exceeds a constant.
I've searched all over, found you can't put user variables in IFs, WHERE's etc. Found you can't put SUMs in IFs, WHERE's etc. I'm at a total loss. Here's an example of my earlier bad code before unsuccessfully trying to use SUMs in WHEREs, if it helps:
SELECT SUM(num1) INTO #mun1 FROM table1 WHERE user = '0';
SELECT SUM(num2) INTO #mun2 FROM table1 WHERE user = '0';
SELECT SUM(num3) INTO #mun3 FROM table2 WHERE column1 = 'd' AND user = '0';
SET #mun4 = #mun1 - #mun2 - #mun3;
INSERT INTO table2 (user, column1, column2) VALUES ('0', 'd', '100') WHERE #mun4 >= 100;
Try this:
INSERT INTO table2 (user, column1, column2)
select '0', 'd', '100'
from dual
where (SELECT SUM(num1 + num2) FROM table1 WHERE user = '0') +
(SELECT SUM(num3) FROM table2 WHERE column1 = 'd' AND user = '0') > 100;
This is a case of the general solution for a "insert if condition" problem:
insert into ... select ... where condition
The select will only return rows if the condition is true, and importantly, will return no rows if false - meaning the insert only happens if the condition is true, otherwise nothing happens.
This is same as #Bohemian's answer, but you got to add a LIMIT clause to stop inserting multiple records, since select clause may return multiple records
INSERT INTO table2 (user, column1, column2)
SELECT '0', 'd', '100'
FROM dual
WHERE
(SELECT SUM(num1 - num2) FROM table1 WHERE user = '0')
(SELECT SUM(num3) FROM table2 WHERE column1 = 'd' AND user = '0') >
100
LIMIT 1