BASIC SELECT SQL QUERIES

Let me explain it with some "Hackerank" qns


QN: 1

Query all columns for a city in CITY with the ID 1661


ANS: SELECT * from CITY where ID = 1661;

since, it is to select all columns from table city.. and the condition is for ID = 1661.


QN: 2

Query all attributes of every Japanese city in the CITY table. The COUNTRYCODE for Japan is JPN.


ANS: SELECT * from CITY where COUNTRYCODE= 'JPN';

since, it is to select all attributes from the table city.. and the condition is for a COUNTRYCODE =JPN


QN:3

Query the NAME field for all American cities in the CITY table with populations larger than 120000. The CountryCode for America is USA.


ANS: SELECT NAME from CITY where POPULATION > 120000 and COUNTRYCODE = 'USA';

since it is to select all the names from the table city , condition is population is more than 120000 and CountryCode =USA


QN:4

Query the list of CITY names from STATION that do not start with vowels. Your result cannot contain duplicates.


ANS: SELECT DISTINCT CITY FROM STATION WHERE CITY NOT LIKE"A%" AND CITY NOT LIKE "E%"AND CITY NOT LIKE "I%"AND CITY NOT LIKE "O%"AND CITY NOT LIKE "U%";

Since, it is to select the unique city names from the table STATION and the condition is to the names of the city should not start with vowels(a,e,i,o,u).

so, A%,E%,I%,O%,U%.. is that all other character after that are considered . so, this represents the first leter.


QN:5

Query a list of CITY and STATE from the STATION table.


ANS: SELECT CITY,STATE FROM STATION;

Since, we need both city and state columns from table STATION .. we select both table

QN:6

Query all columns for all American cities in the CITY table with populations larger than 100000. The CountryCode for America is USA.



ANS: SELECT * FROM CITY WHERE POPULATION >100000 AND COUNTRYCODE = 'USA';
Since, it is to select all from table CITY . the condition is where population is more than 100000 and COUNTRYCODE IS USA

QN:7

Find the difference between the total number of CITY entries in the table and the number of distinct CITY entries in the table.


ANS: SELECT COUNT(CITY)-COUNT(DISTINCT CITY) from STATION;

here it is asked for the difference between all city and unique city names to find the repetition we use COUNT keyword to city and distinct city .

QN:8

Query the names of all the Japanese cities in the CITY table. The COUNTRYCODE for Japan is JPN


ANS: SELECT NAME FROM CITY WHERE COUNTRYCODE = 'JPN';

Here, it is to select the names of the city from table CITY and the condition is COUNTRYCODE to be JPN


Comments

Popular posts from this blog

THE DELIVERY MAN

EC2 LAUNCHING

SORT A LINKED LIST USING MERGE SORT