0

I am trying to search a table for entries that feature a combination of specific values across two particular columns.

I'm having no problem performing the search using one condition:

SELECT *
FROM Table
WHERE [artist_id] IN ('ID1', 'ID2', etc)

But I'd like to add a second condition, something like this:

AND WHERE [track_name] IN (NAME1', 'NAME2', etc)

A few notes:

  1. "artist_id" and "track_name" are both formatted as nvarchar, with "track_name" taking the form of single words or phrases.

  2. There are multiple entries for each "artist_id" and "track_name," but all combinations of the two are unique.

So, how can I combine these conditions into a single query?

Here's a snippet of the code:

SELECT * 
FROM [Music].[dbo].[echonest_tracks]
WHERE [artist_id] IN ('AR03U0G1187B9B1D35', 'AR03U0G1187B9B1D35', etc)
AND [track_title] IN ('Location', 'Cape Vibes Got 'em?', 'Feeling Good (Instrumental Remix)', 'How my heart by you', etc)

2 Answers2

1

I think this is what you are looking for since you are looking for combinations:

SELECT * 
FROM [Music].[dbo].[echonest_tracks]
WHERE 
([artist_id] = 'AR03U0G1187B9B1D35' AND [track_title] IN ('Location', 'Cape Vibes Got 'em?', 'Feeling Good (Instrumental Remix)')
OR 
([artist_id] = 'AR03U0G1187B9B1D35' AND [track_title] IN ('How my heart by you', etc))
0

You are almost there.

SELECT *
FROM Table
WHERE [artist_id] IN ('ID1', 'ID2', etc)
AND [track_name] IN ('NAME1', 'NAME2', etc)

should do it.

As for the single quote within a query string, see this answer: How do I escape a single quote in SQL Server?

You need to double up a single quote to have it within a query string.

Community
  • 1
  • 1
Mark West
  • 161
  • 8
  • A few follow-ups: I'm having no trouble with the artist_id's, which look like this (AR03U0G1187B9B1D35), but many of the track_names are producing errors, either because they contain some character(s) ("Lef' am so !") or word ("Sometimes When We Touch (Unplugged)") that SQL misinterprets. Is there any way to deal with these exceptions en masse? Single quotes and parentheses appear often, but there are countless other characters that also appear in the track_titles and seem to be causing problems... – mgmauskapf May 08 '16 at 04:27
  • How are you creating your queries? Can you show a code example? – Mark West May 08 '16 at 04:30
  • I've edited my original question to include an example of the code at the bottom. The last three track_ids listed are examples of entries that are causing problems: (1) 'Cape Vibes Got 'em?' [because of the single quote before " 'em" (2) 'Feeling Good (Instrumental Remix)' [because of the parentheses) (3) 'How my heart by you' [because of the word "by"]. – mgmauskapf May 08 '16 at 04:49
  • If we were able to help you, please mark the answer that was most useful as "Accepted." http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – Mark West May 09 '16 at 22:57