SQL Challenges-1: Find the even or odd values
From the following table, write a SQL query to find the even or odd values. Return "Even" for even number and "Odd" for odd number.
Input:
Table: tablefortest
Structure:
Field | Type | Null | Key | Default | Extra |
---|---|---|---|---|---|
srno | int(11) | YES | |||
col_val | int(11) | YES |
Data:
srno | col_val |
---|---|
1 | 56 |
2 | 74 |
3 | 15 |
4 | 51 |
5 | 9 |
6 | 32 |
Sample Solution:
SQL Code(MySQL):
DROP TABLE IF EXISTS tablefortest;
CREATE TABLE tablefortest(srno int, col_val int);
INSERT INTO tablefortest VALUES (1, 56);
INSERT INTO tablefortest VALUES (2, 74);
INSERT INTO tablefortest VALUES (3, 15);
INSERT INTO tablefortest VALUES (4, 51);
INSERT INTO tablefortest VALUES (5, 9);
INSERT INTO tablefortest VALUES (6, 32);
SELECT * FROM tablefortest;
SELECT srno, col_val,
CASE WHEN col_val%2=0 THEN 'Even'
WHEN col_val%2=1 THEN 'Odd'
END AS Even_Odd
FROM tablefortest;
Sample Output:
srno|col_val|Even_Odd| ----|-------|--------| 1| 56|Even | 2| 74|Even | 3| 15|Odd | 4| 51|Odd | 5| 9|Odd | 6| 32|Even |
SQL Code Editor:
Contribute your code and comments through Disqus.
Previous: Century of a given date.
Next: Unique values.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics