Recent Posts

HackerRank: [SQL Basic Select] (11/20) Weather Observation Station-6 | regexp_like, like, left function in SQL

HackerRank: [Basic Select - 11/20] Weather Observation Station-6 | REGEXP_LIKE, LIKE, LEFT function in SQL
I started studying SQL from a very famous site - HackerRank. Here I will try to provide multiple approaches & solutions to the same problem. It will help you learn and understand SQL in a better way.

Please make use of my blog posts for learning purpose only and feel free to ask your questions in the comment box below in case of any doubt.

Click Here for the previous blog-post in the series.


SQL Problem Statement:

Query the list of CITY names starting with vowels (i.e., a, e, i, o, or u) from STATION. Your result cannot contain duplicates.




The STATION table is described as follows:

Table: STATION
Table: STATION
where LAT_N is the northern latitude and LONG_W is the western longitude.




Sample data in Table (STATION):
ID CITY STATE LAT_N LONG_W
794 Kissee Mills MO 140 73
824 Loma Mar CA 49 131
603 Sandy Hook CT 72 148
478 Tipton IN 34 98
619 Arlington CO 75 93
711 Turner AR 50 101
839 Slidell LA 85 152
.
.
.
754 South Haven MI 145 53
144 Eskridge KS 1




Solution-1: Using LIKE Function (MySQL Query):

SELECT DISTINCT CITY
FROM STATION
WHERE CITY LIKE 'A%'
OR CITY LIKE 'E%'
OR CITY LIKE 'I%'
OR CITY LIKE 'O%'
OR CITY LIKE 'U%';


Solution-2: Using REGEXP_LIKE Function (MySQL Query):

SELECT DISTINCT CITY
FROM STATION
WHERE REGEXP_LIKE(CITY, '^[aeiou]', 'i');

NOTE: 
  1. "^" character in REGEXP_LIKE function is used to check string starting with matching pattern.
  2. "[]" (square brackers) are used to pass list of characters to check. Here, it is a,e,i,o,u.
  3. "i" is passed as an argument to the REGEXP_LIKE function for case_insensitivity. i.e. It will try check match with small as well as capital letters.



Solution-3: Using LEFT Function (MySQL Query):

SELECT DISTINCT CITY
FROM STATION
WHERE LEFT(CITY,1) in ('a','e','i','o','u','A','E','I','O','U');

NOTE: 
  1. LEFT function is used to take substring of CITY starting from left, and "1" is passed as an argument to select only 1 character from left. 

Sample Output:
Arlington
Albany
Upperco
Aguanga
Odin
East China
Algonac
Onaway
Irvington
Arrowsmith
Udall
Oakfield
Elkton




--------------------------------------------------------------------------------
Click here to see solutions for all Machine Learning Coursera Assignments.
&
Click here to see more codes for Raspberry Pi 3 and similar Family.
&
Click here to see more codes for NodeMCU ESP8266 and similar Family.
&
Click here to see more codes for Arduino Mega (ATMega 2560) and similar Family.
Feel free to ask doubts in the comment section. I will try my best to answer it.
If you find this helpful by any mean like, comment and share the post.
This is the simplest way to encourage me to keep doing such work.

Thanks & Regards,
-Akshay P Daga

No comments