SQL: Return all the Names when you have all the IDs

A silly one today, but worth recording here on my online memory bank because quite frankly, I forgot one could do it in the first place, and had to rely on Dave in the end to help me right.

So here’s the problem.

I have all the ID values for wildlife parks but instead of displaying the ID values I want to display the park names. These are stored in a table that has two fields, namely ID and the corresponding display name.

Now sure I could loop through each ID and use a plain and simple SELECT displayname FROM parks WHERE parkID = 1 or whatever the ID value is to return each and every name, but I want to simplify this into a single SQL statement because I’m feeling a little lazy today.

So how can this be done?

Well the trick here is to swap out the = operator for the in set operator, meaning we now have a sql statement that looks like this:

SELECT displayname FROM parks WHERE parkID IN (1,2,13,14,21,7)

This will evaluate true for each record where parkID falls into the designated ID set, returning the display name associated with that particular record retrieved record.

Nice. So from running multiple SQL select statments to executing just one, I’d say we’ve solved today’s little problem! :)

Related Posts :

About Craig Lotter

Craig Lotter is an established web developer and application programmer, with strong creative urges (which keep bursting out at the most inopportune moments) and a seemingly insatiable need to love all things animated. Living in the beautiful coastal town of Gordon's Bay in South Africa, he games, develops, takes in animated fare, trains under the Funakoshi karate style and for the most part, simply enjoys life with his amazing wife and daughter. Oh, and he draws ever now and then too.
This entry was posted in Technology & Code, Tutorials and tagged , , , , , . Bookmark the permalink.