I have a table representing a card deck with 4 cards that each have a unique ID. Now i want to look for a specific card id in the table and find out which card in the deck it is.
card1 | card 2 | card3 | card4 |
---|---|---|---|
cardID1 | cardID2 | cardID3 | cardID4 |
if my table would like this for example I would like to do something like :
SELECT column_name WHERE cardID3 IN (card1, card2, card3, card4)
looking for an answer i found this: SQL Server : return column names based on a record's value
but this doesn’t seem to work for PostgreSQl
2
Answers
This is a rather bad idea. Column names belong to the database structure, not to the data. So you can select IDs and names stored as data, but you should not have to select column names. And actually a user using your app should not be interested in column names; they can be rather technical.
It would probably be a good idea you changed the data model and stored card names along with the IDs, but I don’t know how exactly you want to work with your data of course.
Anyway, if you want to stick with your current database design, you can still select those names, by including them in your query:
SQL Server’s
cross apply
is the SQL standardcross join lateral
.Demonstration.
However, the real problem is the design of your table. In general, if you have col1, col2, col3… you should instead be using a join table.
We’ve made sure a deck can’t have the same card, nor two cards in the same position.
You can query a card’s position directly.
And there is no arbitrary limit on the number of cards in a deck, you can apply one with a trigger.
Demonstration.