Search code examples
mysqlsqlsequelpro

Syntax error when trying to run an IF EXISTS query


I am trying to run the below query (in Sequel Pro), but I am getting the following syntax error:

 '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 username FROM USER WHERE username = "TestObserver")) 
  {SELECT *' at line 1'

Code:

IF EXISTS (SELECT username FROM USER WHERE username = "TestObserver") 
SELECT * FROM USER WHERE username = "TestObserver"

Solution

  • You can't use an if block outside of a function. Instead just run the subsequent SQL statement:

    SELECT * FROM `USER` WHERE username = "TestObserver"
    

    If there is no username with testobserver value it will already return nothing all by itself.