SQL Challenges-1: Century of a given date
SQL Challenges-1: Exercise-12 with Solution
From the following table, write a SQL query to find the century of a given date. Return the century.
Input:
Table: tablefortest
Structure:
Field | Type | Null | Key | Default | Extra |
---|---|---|---|---|---|
ID | int(11) | YES | |||
date_of_birth | date | YES |
Data:
ID | date_of_birth |
---|---|
1 | 1907-08-15 |
2 | 1883-06-27 |
3 | 1900-01-01 |
4 | 1901-01-01 |
5 | 2005-09-01 |
6 | 1775-11-23 |
7 | 1800-01-01 |
Sample Solution:
SQL Code(MySQL):
DROP TABLE IF EXISTS tablefortest;
CREATE TABLE tablefortest(ID int, date_of_birth date);
INSERT INTO tablefortest VALUES (1, '1907-08-15');
INSERT INTO tablefortest VALUES (2, '1883-06-27');
INSERT INTO tablefortest VALUES (3, '1900-01-01');
INSERT INTO tablefortest VALUES (4, '1901-01-01');
INSERT INTO tablefortest VALUES (5, '2005-09-01');
INSERT INTO tablefortest VALUES (6, '1775-11-23');
INSERT INTO tablefortest VALUES (7, '1800-01-01');
SELECT * FROM tablefortest;
SELECT id, date_of_birth, (SUBSTRING((EXTRACT(YEAR FROM(date_of_birth))-1),1,2))+1 AS Century
FROM tablefortest;
Sample Output:
id|date_of_birth|Century| --|-------------|-------| 1| 1907-08-15| 20 | 2| 1883-06-27| 19 | 3| 1900-01-01| 19 | 4| 1901-01-01| 20 | 5| 2005-09-01| 21 | 6| 1775-11-23| 18 | 7| 1800-01-01| 18 |
SQL Code Editor:
Contribute your code and comments through Disqus.
Previous: Convert negative numbers to positive and vice verse.
Next: Find the even or odd 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