MySQL Select when not exist return 1

1.3k Views Asked by At

I have a problem in the MySQL Query:

How can i SELECT something but when it errors because it doesn´t exist it should return a value like 1 or something else.

My Query

SELECT License FROM fivem_auth WHERE IP = '34.45.34.77';
3

There are 3 best solutions below

0
On BEST ANSWER

You can UNION your query with a query that returns the default if the row doesn't exist.

SELECT License FROM fivem_auth WHERE IP = '34.45.34.77'
UNION ALL
SELECT 1 FROM DUAL
WHERE NOT EXISTS (SELECT 1 FROM fivem_auth WHERE IP = '34.45.34.77')
0
On

There is no error when a row doesn't exist. It simply returns no rows. If you are expecting one value, here are two methods that return NULL instead:

SELECT (SELECT License FROM fivem_auth WHERE IP = '34.45.34.77') as Licence;

SELECT MAX(License)
FROM fivem_auth
WHERE IP = '34.45.34.77';

For either of these, you can use COALESCE() to returns a non-NULL value. But NULL seems appropriate for no value in the table.

0
On

If IP is unique and you expect just 1 row in the results, use aggregation which will always return a row even when the condition fails and in that case COALESCE() will return 1:

SELECT COALESCE(MAX(License), '1') 
FROM fivem_auth 
WHERE IP = '34.45.34.77';