SQL Challenges-1: Find the even or odd values
SQL Challenges-1: Exercise-13 with Solution
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.
SQL: Tips of the Day
SQL Server SELECT into existing table.
INSERT INTO dbo.TABLETWO SELECT col1, col2 FROM dbo.TABLEONE WHERE col3 LIKE @search_key
This assumes there's only two columns in dbo.TABLETWO - you need to specify the columns otherwise:
INSERT INTO dbo.TABLETWO (col1, col2) SELECT col1, col2 FROM dbo.TABLEONE WHERE col3 LIKE @search_key
Database: SQL Server
Ref: https://bit.ly/3y6tpA3
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework