{"id":20856768,"url":"https://github.com/dhia-gharsallaoui/hackerrank-sql-solutions","last_synced_at":"2026-05-20T13:32:10.402Z","repository":{"id":144533308,"uuid":"435475647","full_name":"dhia-gharsallaoui/HackerRank-SQL-Solutions","owner":"dhia-gharsallaoui","description":"The solutions of all SQL hackerrank in MYSQL","archived":false,"fork":false,"pushed_at":"2022-07-30T17:58:29.000Z","size":16,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-01-19T07:13:05.242Z","etag":null,"topics":["hackerrank","hackerrank-solutions","mysql","sql"],"latest_commit_sha":null,"homepage":"","language":"SQL","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/dhia-gharsallaoui.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-12-06T11:46:27.000Z","updated_at":"2022-09-09T15:29:56.000Z","dependencies_parsed_at":null,"dependency_job_id":"49f07802-b377-4d73-9cbd-873a3bc3ca1e","html_url":"https://github.com/dhia-gharsallaoui/HackerRank-SQL-Solutions","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dhia-gharsallaoui%2FHackerRank-SQL-Solutions","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dhia-gharsallaoui%2FHackerRank-SQL-Solutions/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dhia-gharsallaoui%2FHackerRank-SQL-Solutions/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dhia-gharsallaoui%2FHackerRank-SQL-Solutions/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/dhia-gharsallaoui","download_url":"https://codeload.github.com/dhia-gharsallaoui/HackerRank-SQL-Solutions/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243230066,"owners_count":20257640,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["hackerrank","hackerrank-solutions","mysql","sql"],"created_at":"2024-11-18T04:34:05.060Z","updated_at":"2025-12-26T14:10:11.124Z","avatar_url":"https://github.com/dhia-gharsallaoui.png","language":"SQL","funding_links":[],"categories":[],"sub_categories":[],"readme":"# HackerRank-SQL-Solutions\n## Description\n\nThe solutions of all the SQL challenges for all easy, medium and hard challenges on HackerRank executed on MySQL environment compiled.\n\n## Solutions\n\n## [Basic Select Challenges](https://www.hackerrank.com/domains/sql?filters%5Bsubdomains%5D%5B%5D=select)\n\n### Revising the Select Query I\n```SQL\nSELECT * FROM CITY WHERE population \u003e 100000 AND Countrycode =\"USA\";\n```\n### Revising the Select Query II\n```SQL\nSelect name from city where population \u003e 120000 and Countrycode = \"USA\";\n```\n### Select All\n```SQL\nSelect * from city;\n```\n### Select by ID\n```SQL\nselect * from city where ID=1661;\n```\n### Japanese Cities' Attributes\n```SQL\nselect * from city where countrycode=\"JPN\";\n```\n### Japanese Cities' Names\n```SQL\nselect name from city where CountryCode=\"JPN\";\n```\n### Weather Observation Station 1\n```SQL\nselect city,State from station;\n```\n### Weather Observation Station 3\n```SQL\nSelect distinct city from station where ID%2=0;\n```\n### Weather Observation Station 4\n```SQL\nselect count(city) - count(distinct city) from station;\n```\n### Weather Observation Station 5\n```SQL\nselect city,length(city) from station order By length(city) asc, city asc limit 1;\nselect distinct(City),length(city) from station order by length(city) desc, city asc limit 1;\n```\n### Weather Observation Station 6\n```SQL\nselect distinct city from station where left(city,1) in('a','e','i','o','u');\n```\n### Weather Observation Station 7\n```SQL\nselect distinct city from station where right(city,1) in('a','e','i','o','u');\n```\n### Weather Observation Station 8\n```SQL\nselect distinct city from station where left(city,1) in('a','e','i','o','u') and right(city,1) in('a','e','i','o','u') ;\n```\n### Weather Observation Station 9\n```SQL\nselect distinct city from station where left(city,1) not in('a','e','i','o','u') ;\n```\n### Weather Observation Station 10\n```SQL\nselect distinct city from station where  right(city,1) not in('a','i','e','o','u') ;\n```\n### Weather Observation Station 11\n```SQL\nselect distinct city from station where left(city,1) not in('a','i','e','o','u') or right(city,1) not in('a','i','e','o','u');\n```\n### Weather Observation Station 12\n```SQL\nselect distinct city from station where left(city,1) not in('a','i','e','o','u') and right(city,1) not in('a','i','e','o','u') ;\n```\n### Higher than 75 marks\n```SQL\nselect name from students where marks \u003e 75 order by right(name,3),id asc;\n```\n### Employee Names\n```SQL\nselect name from employee order by name;\n```\n### Employee Salaries\n```SQL\nselect name from employee where salary \u003e 2000 and months \u003c10 order By employee_id;\n ```\n\n## [ Advanced Select Challenges](https://www.hackerrank.com/domains/sql?filters%5Bsubdomains%5D%5B%5D=advanced-select)\n\n### Type of Triangle\n```SQL\nSelect case \n    when  (A+B\u003c=C or A+C\u003c=B or B+C\u003c=A ) then 'Not A Triangle'\n    when (A=B) and(B=C) then 'Equilateral' \n    when (A=B or B=C or A=C)  then 'Isosceles'\n    else 'Scalene'\n    End as \"triangle_type\"\n    from triangles;\n```\n\n### The PADS\n```SQL\nselect CONCAT_WS('',name,'(',left(occupation,1),')')  \n    from occupations \n    order by name;\n\nselect CONCAT_WS(\"\",\"There are a total of \",count(occupation),\" \",LOWER(occupation),\"s.\") \n    from occupations \n    group by occupation\n    order by count(occupation), occupation; \n```    \n\n### Occupations\n```SQL\nset @d=0, @p=0, @s=0, @a=0; -- initial counters \n\nselect  min(Doctor), min(Professor), min(Singer), min(Actor)\n    from(\n        SELECT case\n                when Occupation='Doctor' then (@d:=@d+1)\n                when Occupation='Professor' then (@p:=@p+1)\n                when Occupation='Singer' then (@s:=@s+1)\n                when Occupation='Actor' then (@a:=@a+1) end as counter,\n\n            case when Occupation='Doctor' then Name end as Doctor,\n            case when Occupation='Professor' then Name end as Professor,\n            case when Occupation='Singer' then Name end as Singer,\n            case when Occupation='Actor' then Name end as Actor\n        FROM OCCUPATIONS order by name )temp\n      group by  counter;\n```\n### Binary Tree Nodes\n```SQL\nselect N,case  \n    when P is NULL then 'Root'\n    WHEN EXISTS (SELECT B.P FROM BST B WHERE B.P = BT.N) THEN 'Inner'        \n    else 'Leaf' end as node_type\n    from BST  as BT order by N;\n```\n### New Companies\n- With `left join`. \n    \n```SQL\n\n        SELECT\n        c.company_code,c.founder,\n        count(distinct lm.lead_manager_code),\n        count(distinct sm.senior_manager_code),\n        count(distinct m.manager_code), \n        count(distinct e.employee_code)\n    FROM \n        Company c\n        left join Lead_Manager lm on c.company_code=lm.company_code\n        left join Senior_Manager sm on sm.lead_manager_code=lm.lead_manager_code\n        left join Manager m on m.senior_Manager_code=sm.senior_Manager_code\n        left join Employee e on e.manager_code=m.manager_code\n    GROUP BY\n        c.company_code,c.founder\n    ORDER BY \n        c.company_code ASC\n```\n- Without `left join`\n```SQL\n    SELECT \n        c.company_code,c.founder,\n        count(distinct lm.lead_manager_code),\n        count(distinct sm.senior_manager_code),\n        count(distinct m.manager_code), \n        count(distinct e.employee_code)\n    FROM \n        Company c, Lead_Manager lm, Senior_Manager sm, Manager m, Employee e\n    WHERE\n        c.company_code=lm.company_code AND\n        lm.lead_manager_code=sm.lead_manager_code AND\n        sm.senior_manager_code=m.senior_manager_code AND\n        m.manager_code=e.manager_code\n    GROUP BY \n        c.company_code,c.founder\n    ORDER BY \n        c.company_code ASC;\n ```\n## [Aggregation Challenges](https://www.hackerrank.com/domains/sql?filters%5Bsubdomains%5D%5B%5D=aggregation)\n\n### Revising Aggregations - The Sum Function\n```SQL\nselect \n    sum(population) \nfrom\n    city \nwhere\n    district=\"California\";\n```\n### Revising Aggregations - Averages\n```SQL\nselect \n    avg(population) \nfrom\n    city \nwhere\n    district=\"California\";\n```\n### Revising Aggregations - The Count Function\n```SQL\nselect \n    count(*)\nfrom\n    city\nwhere\n    population\u003e100000;\n```\n\n### Average Population\n```SQL\nselect\n    floor(avg(population))\nfrom \n    city;\n```\n\n### Japan Population\n```SQL\nselect\n    sum(population)\nfrom \n    city\nwhere\n    countrycode='JPN';\n```\n\n### Population Density Difference\n```SQL\nselect \n    max(population)-min(population)\nfrom \n    city;\n```\n\n### The Blunder\n```SQL\nselect \n    ceil(avg(salary)-avg(replace(salary,0,'')))\nfrom \n    employees;\n```\n\n### Top Earners\n```SQL\nselect \n    salary*months, COUNT(*)\nfrom \n    employee\nwhere \n    (salary*months) = (select max(salary*months) from employee) \ngroup by salary*months;\n```\n\n### Weather Observation Station 2\n```SQL\nselect \n    round(sum(lat_n),2),round(sum(long_w),2)\nfrom \n    station;\n```\n### Weather Observation Station 13\n```SQL\nselect \n    truncate(sum(lat_n),4)\nfrom \n    station\nwhere\n    lat_n\u003e38.7880 and lat_n\u003c137.2345 ;\n```\n### Weather Observation Station 14\n```SQL\nselect \n    truncate(max(lat_n),4)\nfrom \n    station\nwhere\n    lat_n\u003c137.2345 ;\n```\n\n### Weather Oservation Station 15\n```SQL\nselect \n    round(long_w,4) \nfrom \n    station\nwhere \n    lat_n =(select max(lat_n) from station where lat_n \u003c137.2345);\n``` \n### Weather Oservation Station 16\n```SQL\nselect \n    round(min(lat_n),4)\nfrom \n    station\nwhere \n     lat_n\u003e38.7780;\n``` \n### Weather Oservation Station 17\n```SQL\nselect \n    round(long_w,4)\nfrom \n    station\nwhere \n     lat_n=(select min(lat_n) from station where lat_n\u003e38.7780);\n``` \n### Weather Oservation Station 18\n```SQL\nselect \n    round(abs(max(lat_n)-min(lat_n))+abs(max(long_w)-min(long_w)),4)\nfrom \n    station;\n``` \n\n### Weather Oservation Station 19\n```SQL\nselect \n    round(power((power(max(lat_n)-min(lat_n),2)+power(max(long_w)-min(long_w),2)),0.5),4)\nfrom \n    station;\n``` \n### Weather Oservation Station 20\n\n```SQL\nset \n    @rownum=0;\n\nSELECT \n    ROUND(t.lat_n, 4)\nFROM(\n    SELECT \n        s.LAT_N,\n        @rownum := @rownum + 1 as `row_number`,\n        @total_rows := @rownum\n    FROM \n        STATION s\n    ORDER BY \n        s.LAT_N\n  ) as t\nWHERE \n    t.row_number IN (FLOOR((@total_rows + 1) / 2), FLOOR((@total_rows + 2) / 2));\n```\n\n## [Basic Join Challenges](https://www.hackerrank.com/domains/sql?filters%5Bsubdomains%5D%5B%5D=join)[]()\n\n### Population Census\n```SQL\nselect \n    sum(city.population)\nfrom \n    country left join city on city.countrycode=country.code\nwhere \n    country.continent=\"Asia\";\n```\n### African Cities\n```SQL\nselect \n    city.name\nfrom \n    country inner join city on city.countrycode=country.code\nwhere \n    country.continent=\"Africa\";\n```\n\n### Average Population of Each Continent\n```SQL\nselect\n    country.continent, floor(avg(city.population))\nfrom\n    country inner join city on city.countrycode=country.code\ngroup by\n    country.continent\n```\n\n### The Report\n```SQL\nselect \n    case when g.grade\u003c8 then NULL\n    else s.name end as names,\n    g.grade,s.marks\nfrom \n    students s join grades g on s.marks between g.min_mark and g.max_mark\norder by   \n    g.grade Desc,\n    s.name,\n    s.marks;\n```\n\n### Top Competitors\n```SQL\nselect\n  h.hacker_id,h.name\nfrom \n    submissions s join hackers h on s.hacker_id=h.hacker_id\n    join challenges c on c.challenge_id=s.challenge_id\n    join difficulty d on c.difficulty_level=d.difficulty_level and s.score=d.Score\ngroup by \n    h.hacker_id,h.name\nhaving count(h.hacker_id) \u003e 1 \norder by \n    count(h.hacker_id) desc,\n    h.hacker_id ;\n```\n\n### Ollivander's Inventory\n```SQL\nselect\n    w.id,wp.age,w.coins_needed,w.power\nfrom \n    wands w join wands_property wp on w.code=wp.code\nwhere \n    wp.is_evil=0 and \n    w.coins_needed=(select \n                        min(w2.coins_needed)\n                    from \n                        wands w2 join wands_property wp2 on w2.code=wp2.code\n                    where \n                        w2.power=w.power and wp2.age=wp.age)\norder by\n    w.power desc,\n    wp.age desc;\n\n```\n\n### Challenges\n```SQL\nselect \n    h.hacker_id,h.name,count(h.hacker_id) as challenges_created\nfrom \n    hackers h join challenges c on h.hacker_id=c.hacker_id\ngroup by\n    h.hacker_id,\n    h.name\nhaving \n\n    challenges_created=(\n    select \n        count(challenge_id) as max_challenges \n    from\n        challenges \n    group by \n        hacker_id\n    order by \n        max_challenges desc \n    limit 1 ) \n    or\n    challenges_created in(\n    select \n        temp.max_challenges \n    from \n        (select  count(challenge_id) AS max_challenges\n    FROM \n         challenges\n    group by \n         hacker_id order by max_challenges) temp \n    group by \n        temp.max_challenges\n    having \n        count(temp.max_challenges)=1)\n\norder by \n    challenges_created desc,\n    h.hacker_id\n  \n\n```\n\n### Contest Leaderboard\n```SQL\nselect \n    h.hacker_id,h.name,sum(ss.max_score) as total_score\nfrom \n    hackers h join (select \n                        s.hacker_id,s.challenge_id,max(score) as max_score\n                    from \n                        submissions s\n                    group by \n                        s.hacker_id,s.challenge_id) ss\n                    on h.hacker_id=ss.hacker_id\ngroup by \n    h.hacker_id,h.name\nhaving\n    total_score\u003e0\norder by\n    total_score desc,\n    h.hacker_id\n```\n\n\n\n## [Advanced Join Challenges](https://www.hackerrank.com/domains/sql?filters%5Bsubdomains%5D%5B%5D=advanced-join)\n\n### SQL Project Planning     \n```sql\nselect\n    s.start_date,min(e.end_date)\nfrom \n(select\n    end_date\n from \n    projects\n where \n    end_date not in (select start_date from projects)) e,\n    (select \n    start_date\nfrom \n    projects\nwhere \n    start_date not in (select end_date from projects)) s\n    \nwhere \n    s.start_date\u003ce.end_date\ngroup by \n    s.start_date\norder by\n    datediff(min(e.end_date), s.start_date) asc,\n    s.start_date ;\n```\n### Placements\n```sql\nselect \n    s.name\nfrom \n    students s join friends f on s.id=f.id\n    join packages p on p.id=s.id\n    join packages pf on pf.id=f.friend_id\nwhere\n    pf.salary\u003ep.salary\norder by\n    pf.salary ;\n```\n### Symmetric Pairs\n```sql\nselect \n    f1.x,f1.y\nfrom\n    functions f1 ,functions f2\nwhere\n    f1.x\u003c=f1.y\n    and f1.x=f2.y\n    and f1.y=f2.x\ngroup by\n    f1.x,f1.y\nhaving \n    count(case when f1.x=f1.y then f1.x END)\u003e2\n    or count(case when f1.x\u003cf1.y then f1.x end)=1\norder by\n    f1.x,f1.y;\n\n```\n\n### Interviews\n```sql\nselect\n    c.contest_id,c.hacker_id,c.name,sum(s.ts) as tst,\n    sum(s.tas)  as tast,sum(vs.tv) as tvt , sum(vs.tuv) as tuvt\nfrom \n    contests c join colleges co on c.contest_id=co.contest_id\n    join challenges ch on ch.college_id=co.college_id \n    left join (select \n                challenge_id, sum(total_submissions) as ts, sum(total_accepted_submissions) as tas\n         from \n            submission_stats\n          group by \n            challenge_id\n         ) s on s.challenge_id=ch.challenge_id\n         \n    left join (select \n          challenge_id,sum(total_views) as tv,sum(total_unique_views) tuv\n          from \n            view_stats\n          group by \n            challenge_id\n         ) vs on vs.challenge_id=ch.challenge_id\n\ngroup by \n    c.contest_id,c.hacker_id,c.name\nhaving \n    sum(s.ts)+ sum(s.tas)+sum(vs.tv)+ sum(vs.tuv) \u003e0\norder by\n    c.contest_id\n\n\n```\n\n### 15 Days of Learning SQL\n```sql\n\n```\n\n\n## [Alternative Queries Challenges](https://www.hackerrank.com/domains/sql?filters%5Bsubdomains%5D%5B%5D=alternative-queries)\n\n\n### Draw The Triangle 1\n```sql\nset \n    @n_lines =21;\n\nselect \n    repeat('* ',@n_lines:=@n_lines-1)\nfrom \n    INFORMATION_SCHEMA.TABLES\nlimit 20;\n```\n\n\n### Draw The Triangle 2\n```sql\nset \n    @n_lines =0;\n\nselect \n    repeat('* ',@n_lines:=@n_lines+1)\nfrom \n    INFORMATION_SCHEMA.TABLES\nlimit 20;\n```\n\n\n### Print Prime Numbers\n```sql\nwith recursive tblnums\nas (\n    select 2 as nums\n    union all\n    select nums+1 \n    from tblnums\n    where nums\u003c1000)\n    \nselect group_concat(tt.nums order by tt.nums separator '\u0026')  as nums\nfrom tblnums tt\nwhere not exists \n    ( select 1 from tblnums t2 \n    where t2.nums \u003c= tt.nums/2 and mod(tt.nums,t2.nums)=0) ;\n```\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdhia-gharsallaoui%2Fhackerrank-sql-solutions","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdhia-gharsallaoui%2Fhackerrank-sql-solutions","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdhia-gharsallaoui%2Fhackerrank-sql-solutions/lists"}