Reputation: 13166
I think I have a conflict between my knowledge on SQL Server and MySQL.
When I run this query, I get an error always from MySQL:
If EXISTS (select * from tbl_admin) THEN
select 'OK';
END IF;
The error message is:
[Err] 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'if EXISTS (select * from tbl_admin) then select '1' -- select '1' WHERE EXISTS ' at line 1
Please help me and tell me am I wrong in writing this query? What's wrong?
I want to do something if I have something in tbl_admin
table.
Upvotes: 1
Views: 12512
Reputation: 204766
select 'ok'
from INFORMATION_SCHEMA.tables
where table_name = 'tbl_admin'
To check if a table contains data you can do this:
SELECT 'OK' FROM dual
WHERE EXISTS (SELECT * FROM tbl_admin);
Upvotes: 3
Reputation: 810
select if(count(*), 'OK', '') as result from table_name where 1
This will print "OK" if there are records present, else nothing will be shown.
Upvotes: 0
Reputation: 1079
if you want to check table existence then use this
select 'Message' from INFORMATION_SCHEMA.tables where table_name = 'tbl_admin'
because all information is stored here.EXISTS also works fine in mysql.
Upvotes: 0
Reputation: 5380
select case when count(*) > 0 then 'OK' else 'Empty' end from tbl_admin;
OR
select 'OK' from tbl_admin having count(*) > 0;
Upvotes: 0
Reputation: 10270
You can do something like:
if ( (select count(*) from tbl_admin) > 0) then
...
This counts all the rows in the table. If no rows are there, it will return 0.
Upvotes: 1
Reputation: 1963
If I understand correctly, you know there is a table, you just need an info if there are any rows? In that case I think this solves your problem:
SELECT
'OK'
FROM
Korisnik
WHERE
EXISTS( SELECT
COUNT(*)
FROM
Korisnik)
LIMIT 1;
You can use IF EXISTS
to check for stored procedure or trigger existence. In SELECT queries you can use WHERE EXISTS
or WHERE NOT EXISTS
http://dev.mysql.com/doc/refman/5.5/en/exists-and-not-exists-subqueries.html
Upvotes: 1