Return Value from sql commands - mysql

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

Related

Insert in the IF statement Query in mysql

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;

Operand Should Contain 1 Column(s), Trying to generate volunteer data

I can't seem to troubleshoot my problem.
My stored procedure:
CREATE DEFINER=`myschoolusername`#`%` PROCEDURE `generate_volunteers`(in nfolks int)
BEGIN
set #i=0;
while #i < nfolks do
insert into Volunteer(firstname, lastname, dateofbirth)
values (((floor(1+(rand()*(4-1))), "Fred", "Wang", "Fatimah", "Marcella")),
((floor(1+(rand()*(3-1))), "Kaser", "Fang", "Kumar")),
DATE_ADD('1965-01-01', INTERVAL rand()*200000 DAY));
set #i = #i+1;
end while;
END
Additionally, here is my volunteer table in my MYSQL script:
drop table if exists Volunteer;
create Table Volunteer(
member_num int not null auto_increment primary key,
firstname varchar(20) not null,
lastname varchar(20) not null,
dateofbirth date not null
);
I am trying to insert 500 lines into this table, however error 1305 is coming up.
Any help is heavily appreciated, I am quite unsure of where to go from this point.
This logic doesn't do anything:
(floor(1+(rand()*(4-1))), "Fred", "Wang", "Fatimah", "Marcella"))
Although not the most efficient, this should be fine for 500 rows:
insert into Volunteer(firstname, lastname, dateofbirth)
select f.firstname, l.lastname,
DATE_ADD('1965-01-01', INTERVAL rand()*200000 DAY)
from (select 'Fred' as firstname union all
select 'Wang' union all
select 'Fatimah' union all
select 'Marcella'
) f cross join
(select 'Kaser' as lastname union all
select 'Fang' union all
select 'Kumar'
) l
order by rand()
limit 1;
I think you are actually trying to write:
insert into Volunteer(firstname, lastname, dateofbirth)
select elt(floor(rand() * 4) + 1,
'Fred', 'Wang', 'Fatimah', 'Marcella'
) as firstname,
elt(floor(rand() * 3) + 1,
'Kaser', 'Fang', 'Kumar'
) as lastname,
DATE_ADD('1965-01-01', INTERVAL rand()*200000 DAY);

SQL IDENTITY column based on another column

Is there a way to define an identity column on another column? What I want to accomplish is a table that holds positions of an order and these orders can be put there anytime. So it could be that there are already lets say three positions in the table and it would look somewhat like this:
OrderNumber | OrderPosition
10001 1
10001 2
10001 3
And now I want to add another position without calculating the right value for the OrderPosition column. This is because I want to write new positions for multiple orders into the table and would like to avoid cursoring over the individual orders. I would prefer a solution wher OrderPosition is an identity column that is reseeded based on the OrderNumber column. So that If i add an order position for a new order it would start with 1 and if I add another position for order 10001 it would continue with 4.
Write a Scalar Function that returns the MAX(OrderPosition) based on OrderNumber. Then reference that function in the insert statement of orders
your requirement will not work for identity column.
You need to create custom logic to get from the normal columns and on combination based new no will generate.. like (read comments, only choose one logic)
declare #t table(OrderNumber int, OrderPosition int)
insert into #t values (10001, 1),(10001, 2),(10001, 3),(10001, 4)
select * from #t
--now insert new record with old orderno
declare #seq int = 1
declare #ordernumberNew int = 10001
--Eigher you can use :- insert to more understand
if( exists(select orderposition from #t where OrderNumber = #ordernumberNew ))
begin
set #seq = (select max(OrderPosition) + 1 from #t where OrderNumber = #ordernumberNew )
end
insert into #t values (#ordernumberNew , #seq )
select * from #t
--or another twist of above statement, insert directly as
insert into #t
values
(
#ordernumberNew,
case when exists (select orderposition from #t where OrderNumber = #ordernumberNew )
then (select max(OrderPosition) + 1 from #t where OrderNumber = #ordernumberNew )
else 1 end
)
select * from #t
--Now enter the not exist order no
set #ordernumberNew = 10006
insert into #t
values
(
#ordernumberNew,
case when exists (select orderposition from #t where OrderNumber = #ordernumberNew )
then (select max(OrderPosition) + 1 from #t where OrderNumber = #ordernumberNew )
else 1 end
)
select * from #t

SQL: using group by concat()

I have a query which returns result of number of calls made by customers and some suggestions made for customers and etc.. for that particular date ie... grouping it by date
But now I want to find number of customers I tried grouping by lead_id and cuncat(lead_id,timecreatredFormat) still there is a data mismatch
Below is the query that I have tried
select
sum(t.enquiry_cnt),
sum(t.suggested_cnt),
sum(t.tot_cnt)
from
(select
case
when source = 1 then 1
else 0
end enquiry_cnt,
case
when source = 6 then 1
else 0
end suggested_cnt,
case
when (source = 1 || source = 6) then 1
else 0
end tot_cnt,
date_format(timecreated, '%d-%b-%Y') created_time,
lead_id,timecreated
from
mg_lead_suggested_listing group by concat(created_time,lead_id) ) t
group by t.created_time
order by t.timecreated desc
limit 10;
Thanks in advance
Check whether following query is correct or not. I have added COUNT(DISTINCT t.lead_id) to get customer count.
DECLARE #TEMP TABLE
(
[source] INT,
lead_id INT,
timecreated DATETIME
)
INSERT INTO #TEMP VALUES (1,1,GETDATE())
INSERT INTO #TEMP VALUES (6,1,GETDATE())
INSERT INTO #TEMP VALUES (6,1,GETDATE())
INSERT INTO #TEMP VALUES (1,2,DATEADD(d,-1,GETDATE()))
INSERT INTO #TEMP VALUES (1,1,DATEADD(d,-1,GETDATE()))
INSERT INTO #TEMP VALUES (1,1,DATEADD(d,-1,GETDATE()))
SELECT
CAST(t.timecreated AS DATE) [date],
SUM(t.enquiry_cnt) enquiry_cnt,
(SELECT COUNT(DISTINCT lead_id) FROM #TEMP WHERE CAST(timecreated AS DATE) = CAST(t.timecreated AS DATE) AND [source] = 1) as lead_enquiry_cnt,
SUM(t.suggested_cnt) suggested_cnt,
(SELECT COUNT(DISTINCT lead_id) FROM #TEMP WHERE CAST(timecreated AS DATE) = CAST(t.timecreated AS DATE) AND [source] = 6) as lead_suggested_cnt,
SUM(t.tot_cnt) tot_cnt,
COUNT(t.lead_id) as lead_cnt
FROM
(
SELECT
CASE
WHEN [source] = 1 THEN 1
ELSE 0
END enquiry_cnt,
CASE
WHEN [source] = 6 THEN 1
ELSE 0
END suggested_cnt,
CASE
WHEN ([source] = 1 OR [source] = 6) THEN 1
ELSE 0
END tot_cnt,
lead_id,
timecreated
FROM
#TEMP
) AS t
group by
CAST(t.timecreated AS DATE)
order by
[date] desc

Insert query based on number of rows

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..