MySQL Conditional If-else when selection returns empty result set
05 Sep 2017I am still very new to MySQL or SQL in general. So, this is kind of new.
I need to run a select statement and if that select statement return nothing, I would like to run another different select statement :
IF EXISTS (select something from TABLE_A) THEN select something from TABLE_A;
<pre class="lang-sql prettyprint prettyprinted" style="background-color: #eff0f1; border: 0px; font-family: Consolas, Menlo, Monaco, "Lucida Console", "Liberation Mono", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Courier New", monospace, sans-serif; font-stretch: inherit; font-variant-numeric: inherit; line-height: inherit; margin-bottom: 1em; max-height: 600px; overflow: auto; padding: 5px; vertical-align: baseline; width: auto; word-wrap: normal;"><div style="font-family: "Times New Roman"; white-space: normal;">
</pre>More from StackOverflow :
ELSE</div>
<div style="font-family: "Times New Roman"; white-space: normal;">
select something from TABLE_B;</div>
<div style="font-family: "Times New Roman"; white-space: normal;">
END IF;</div>
<pre class="lang-sql prettyprint prettyprinted" style="background-color: #eff0f1; border: 0px; font-family: Consolas, Menlo, Monaco, "Lucida Console", "Liberation Mono", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Courier New", monospace, sans-serif; font-size: 13px; font-stretch: inherit; font-variant-numeric: inherit; line-height: inherit; margin-bottom: 1em; max-height: 600px; overflow: auto; padding: 5px; vertical-align: baseline; width: auto; word-wrap: normal;">IF NOT EXISTS (SELECT ...)
</pre>And with more control :
BEGIN
INSERT ...
END
<pre class="lang-sql prettyprint prettyprinted" style="background-color: #eff0f1; border: 0px; font-family: Consolas, Menlo, Monaco, "Lucida Console", "Liberation Mono", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Courier New", monospace, sans-serif; font-size: 13px; font-stretch: inherit; font-variant-numeric: inherit; line-height: inherit; margin-bottom: 1em; max-height: 600px; overflow: auto; padding: 5px; vertical-align: baseline; width: auto; word-wrap: normal;">IF EXISTS (SELECT ...)
</pre>
BEGIN
PRINT 'Do nothing.';
END
ELSE
BEGIN
INSERT ...
END