'How to select columns with an even ID number?

I'm trying to solve the Hackerrank problem Weather Observation Station 3 which is stated below:

enter image description here

I came up with the following solution:

SELECT CITY
FROM STATION
WHERE MOD(ID, 2) = 0

but when I try to run it I get the compiler message "Wrong answer". I don't see what's wrong with this query?



Solution 1:[1]

SELECT DISTINCT CITY
FROM STATION
WHERE MOD(ID, 2) = 0

Solution 2:[2]

You can try this query:

SELECT DISTINCT CITY FROM STATION WHERE (ID % 2) = 0 

Solution 3:[3]

For DB2:

SELECT DISTINCT CITY 
FROM STATION
WHERE MOD(ID, 2) = 0;

For Oracle:

SELECT DISTINCT CITY 
FROM STATION
WHERE MOD(ID, 2) = 0;

For MySQL:

SELECT DISTINCT CITY 
FROM STATION
WHERE MOD(ID, 2) = 0;

-- Or --

SELECT DISTINCT CITY 
FROM STATION
WHERE ID%2=0;

For MSSQL:

SELECT DISTINCT CITY 
FROM STATION
WHERE ID%2=0;

Solution 4:[4]

MYSQL:

SELECT DISTINCT CITY FROM STATION WHERE (ID % 2)=0;

ORACLE:

SELECT DISTINCT CITY FROM STATION WHERE MOD(ID, 2)=0;

Solution 5:[5]

SELECT DISTINCT CITY FROM STATION WHERE (ID % 2) = 0;
  • DISTINCT for not allowing duplicates,
  • (Id % 2) tells SQL to divide the Id by 2 and return the remainder.
  • Since we're looking for only even values, we set this to = 0, as 2%2=0, 4%2=0, etc.
  • If we were looking for odd-numbered Ids, we'd use = 1 instead, since there's always a remainder of 1 when dividing odd numbers by 2.

Solution 6:[6]

If the question would like "Query a list of CITY names from STATION with even ID numbers only" then the answer would be

select CITY from station where ID % 2 = 0;

But due the further criteria like "But must exclude duplicates from your answer." your answer should be

select DISTINCT CITY from station where ID % 2 = 0;

Solution 7:[7]

I suggest another solution:

    SELECT DISTINCT CITY
    FROM STATION
    WHERE ID LIKE '%0' OR ID LIKE '%2' OR ID LIKE '%4' OR ID LIKE '%6' OR ID LIKE '%8';

Solution 8:[8]

In MSSQL:

SELECT CITY
FROM STATION
WHERE (ID % 2) = 0
GROUP BY CITY 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ted
Solution 2 Jibin Balachandran
Solution 3 Jeremy Caney
Solution 4 Samvel Aleqsanyan
Solution 5 Jeremy Caney
Solution 6 Subarata Talukder
Solution 7 aviboy2006
Solution 8 Paul Roub