How to determine if a table contains a value in SQL?

TacoManStan picture TacoManStan · Dec 28, 2013 · Viewed 35.1k times · Source

I feel like I'm missing something very obvious here, but it seems that the only way to go about doing this is to get the value, and then see if it returns a null (empty) value, which I would rather not do.

Is there an equivalent to List.contains(Object o) in SQL? Or perhaps the JDBC has something of that nature? If so, what is it? Thank you.

EDIT: I am using Microsoft Access 2013.

EDIT 2: Unfortunately I don't have any useful code to show, but here is the gist of what I am trying to do. It isn't anything unique at all. I want to have a method (Java) that returns the values of a user that are stored in the database. If the user has not previously been added to the database, the user should be added, and the default values of the user should be set. Then those newly created values will be returned. If a player has already been added to the database (with the username as the primary key), I don't want to overwrite the data that is already there.

EDIT 3: I have solved the problem! Refer to my answer below.

Answer

Darin Dimitrov picture Darin Dimitrov · Dec 28, 2013

The only way to see if an SQL table contains a row with some condition on a column is to actually make an SQL query. I don't see why you wouldn't do that. Just make sure that you have an index on the column that you will be constraining the results on. Also for better speed use count to prevent from retrieving all the data from the rows.

SELECT count(*) FROM foos WHERE bar = 'baz'

Assuming you have an index on the bar column this query should be pretty fast and all you have to do is check whether it returns > 0. If it does then you have rows matching your criteria.