Return of SQL SELECT

Asked

Viewed 1,701 times

0

I need to make a select comparing whether user login already exists or not. But I do not want to return values from the table, only a symbolic value to verify the existence (true or false). The comparison code is the basic:

SELECT * FROM USUARIOS WHERE LOGIN = '$LOGIN'

$LOGIN being the login I will compare. And select will return me all table contents unnecessarily.

3 answers

3


You could do it like this:

SELECT count(1) FROM USUARIOS WHERE LOGIN = '$LOGIN'

The select will return 1 find the user and 0 if not found. Similar to true and false.

  • unnecessary the 'Count' right?

  • No. Quite the contrary, without him the query would have only two results: 1 (if found) or empty (if not found). With the Count you can get 1 (if found) or 0 (if not found).

  • as I see it, the good thing about Count is that it will not return an array if it returns more than one value right?

  • In this case you will never return more than 1 result.

  • can you tell me if there is a "Uppercase" in the login check = "$login"?? type, select Count(1) from usuarios Where UPPER(LOGIN) = '$LOGIN'...

  • 1

    Yes, just use it upper(login) = upper('$LOGIN').

Show 1 more comment

1

Douglas, try this:

SELECT 1 FROM USUARIOS WHERE LOGIN = '$LOGIN'

SELECT 1 it 1 if there is a record instead of the table fields, it is often used in your case, that you need to verify the existence of a record. And if it doesn’t exist, it returns nothing.

The Electus solution is good but you’ll have to make one if to check if the return was 0 or 1 and also it uses the function COUNT that will count being that you will always have only 1 record that meets the requirements soon unnecessary the use of this function, in this solution proposed by me if registration means that there is, so do not need to check.

  • only if you have more than 1 record it returns a certain array?

  • Correct! But in this specific case of it which is a login table will always be only 1 return.

  • The problem is that if you don’t find the user, the return of the query is empty. So he would have to use a specific function to check how many lines a query returned or if the result "is not Empty".

  • I assumed that I already have this check, because he in the question does not want to return columns that he will not use.

0

You can do it in many ways:

select id from usuarios where login = '$LOGIN';

select count(*) from usuarios where login = '$LOGIN' limit 1;

Sqlfiddle

Browser other questions tagged

You are not signed in. Login or sign up in order to post.