Select multiple rows using id in SQLite
Asked Answered
B

3

8

I am trying to query specific rows from my SQLite database using WHERE conditions on the IDs of the rows I want. However, the query is not returning any results, and it is causing my logger to throw an error stating that there is a syntax error.

Here is the query:

Select * From Equipment Where ID = 2 and ID = 3 and ID = 4 and ID = 7 and ID = 11 and ID = 34

And here is the syntax error from my log:

Aug 17 2017 23:12:23  [Err]: Err002 - Query on Equipment could not be prepared: near "=": syntax error at File: c:\users\geowil\documents\visual studio 2015\projects\ov_pocs\universearc_poc\datasystem.cpp  Line: 323.

So I sailed over to SQLFiddle to try and see if I missed something. It is displaying the same behavior. With and conditions, it returns no results - but running queries on single IDs or a range of IDs works.

Am I doing something wrong or is this a limitation of SQLite?

Update:

Had a brain wave. Using Where ID IN(1,3,4) works on SQLFiddle so now I want to repurpose my question to ask why this works, but my original query did not.

Bismuthous answered 18/8, 2017 at 6:46 Comment(0)
D
11

Use IN to select your multiple tuples.

Select * From Equipment Where ID IN (2, 3, 4, 7, 11, 34);

Every tuple will be selected if every ids existed in your SQLite or Database.


For your query, your logical equation will never select one of the tuple because an id won't have two or more values (ID=2 AND ID=3: if ID equal to 2 it won't be equal to 3). In your case you must use OR instead of AND.

Select * From Equipment Where ID=2 OR ID=3 OR ID=4 OR ID=7 OR ID=11 OR ID=34;

So that every tuple will be selected if every ids existed in your SQLite or Database.

Domino answered 18/8, 2017 at 7:7 Comment(2)
Oh jesus. Duh, don't know why that did not occur to me lol. Thanks.Bismuthous
You are welcome! Please help to check it as a correct answer!Domino
F
1

Use IN instead of = like, issue will be fixed:

SELECT * FROM Equipment WHERE ID IN (1 , 2);
Farahfarand answered 18/8, 2017 at 6:59 Comment(0)
C
1

AND means that the conditions on both sides must be true. But for any single row, there can only be a single ID value.

To check for a match with any one of multiple values, replace AND with OR, or use IN.

Cerelly answered 18/8, 2017 at 7:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.