<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ravi raj on Medium]]></title>
        <description><![CDATA[Stories by Ravi raj on Medium]]></description>
        <link>https://medium.com/@ravisk1514?source=rss-691f1bbb91bd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ONTUKz_gO-1_e1AtLNiYrA.jpeg</url>
            <title>Stories by Ravi raj on Medium</title>
            <link>https://medium.com/@ravisk1514?source=rss-691f1bbb91bd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 07:30:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ravisk1514/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Install Airflow Using Docker Compose]]></title>
            <link>https://medium.com/@ravisk1514/install-airflow-using-docker-compose-861cbdd41cc5?source=rss-691f1bbb91bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/861cbdd41cc5</guid>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[airflow]]></category>
            <dc:creator><![CDATA[Ravi raj]]></dc:creator>
            <pubDate>Tue, 17 Jan 2023 15:35:20 GMT</pubDate>
            <atom:updated>2023-01-17T15:35:20.890Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sTe-xzhpreLEywcZYV-47Q.png" /></figure><h3>What is airflow?</h3><p>In simple terms, Airflow is a tool that helps people make sure things happen in the right order and on time.</p><p>In other terms, Airflow is a powerful open-source tool for managing and scheduling data pipelines. It allows data engineers and scientists to programmatically author, schedule, and monitor their workflows. This can be especially useful for organizations that have complex data pipelines that need to be run on a regular schedule.</p><p>In this blog post, we’ll explore components of Airflow and how to get the airflow up and running using docker-compose.</p><h3>Components of airflow?</h3><ol><li><strong><em>The Airflow scheduler</em></strong> — Parses DAGs, checks their schedule interval, and (if the DAGs’ schedule has passed) starts scheduling the DAGs’ tasks for execution by passing them to the Airflow workers.</li><li><strong><em>The Airflow workers</em></strong> — Pick up tasks that are scheduled for execution and execute them. As such, the workers are responsible for actually “doing the work.”</li><li><strong><em>The Airflow webserver</em></strong> — Visualizes the DAGs parsed by the scheduler and provides the main interface for users to monitor DAG runs and their results.</li><li><strong><em>The Metadata Database</em></strong> — The metadata database is used to store information about workflows, tasks, and their execution. This includes information such as the status of tasks, start and end times, and any error messages.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*OqdpFIEN0ls-PqEptnBd5w.png" /><figcaption>Overview of the main components involved in Airflow (e.g., Airflow webserver, scheduler, and workers)</figcaption></figure><h4>Prerequisite</h4><p>— Install docker-compose: <a href="https://docs.docker.com/compose/install/">https://docs.docker.com/compose/install/</a></p><h3>Setup</h3><p>File: <strong>docker-compose.yml</strong></p><pre>version: &#39;2&#39;<br><br>services:<br>  postgresql:<br>    image: docker.io/bitnami/postgresql:15<br>    container_name: postgres<br>    volumes:<br>      - &#39;postgresql_data:/bitnami/postgresql&#39;<br>    env_file: <br>      - .env-bitnami<br>  redis:<br>    image: docker.io/bitnami/redis:7.0<br>    container_name: redis<br>    volumes:<br>      - &#39;redis_data:/bitnami&#39;<br>    environment:<br>      # ALLOW_EMPTY_PASSWORD is recommended only for development.<br>      - ALLOW_EMPTY_PASSWORD=yes<br>  airflow-scheduler:<br>    image: docker.io/bitnami/airflow-scheduler:2.5.0<br>    container_name: airflow-scheduler<br>    env_file: <br>      - .env-bitnami<br>    volumes:<br>      - airflow_scheduler_data:/bitnami<br>      - ./plugins:/opt/bitnami/airflow/plugins<br>      - ./dags:/opt/bitnami/airflow/dags<br>      - ./db_backups:/opt/bitnami/airflow/db_backups<br>      - /var/run/docker.sock:/var/run/docker.sock<br>  airflow-worker:<br>    image: docker.io/bitnami/airflow-worker:2.5.0<br>    container_name: airflow-worker<br>    env_file: <br>      - .env-bitnami<br>    volumes:<br>      - airflow_worker_data:/bitnami<br>      - ./plugins:/opt/bitnami/airflow/plugins<br>      - ./dags:/opt/bitnami/airflow/dags<br>      - ./db_backups:/opt/bitnami/airflow/db_backups<br>      - /var/run/docker.sock:/var/run/docker.sock<br>  airflow:<br>    image: docker.io/bitnami/airflow:2.5.0<br>    container_name: airflow-webserver<br>    env_file: <br>      - .env-bitnami<br>    ports:<br>      - &#39;8000:8080&#39;<br>    volumes:<br>      - airflow_data:/bitnami<br>      - ./dags:/opt/bitnami/airflow/dags<br>      - ./plugins:/opt/bitnami/airflow/plugins<br>      - ./db_backups:/opt/bitnami/airflow/db_backups<br>      - /var/run/docker.sock:/var/run/docker.sock<br>volumes:<br>  airflow_scheduler_data:<br>    driver: local<br>  airflow_worker_data:<br>    driver: local<br>  airflow_data:<br>    driver: local<br>  postgresql_data:<br>    driver: local<br>  redis_data:<br>    driver: local</pre><p>File: <strong>.env-bitnami</strong></p><pre># Meta-Database<br>POSTGRESQL_DATABASE=bitnami_airflow<br>POSTGRESQL_USERNAME=bn_airflow<br>POSTGRESQL_PASSWORD=bitnami1<br># ALLOW_EMPTY_PASSWORD is recommended only for development.<br>ALLOW_EMPTY_PASSWORD=yes<br><br># Airflow Core<br>AIRFLOW_DATABASE_NAME=bitnami_airflow<br>AIRFLOW_DATABASE_USERNAME=bn_airflow<br>AIRFLOW_DATABASE_PASSWORD=bitnami1<br>AIRFLOW_EXECUTOR=CeleryExecutor<br>AIRFLOW_WEBSERVER_HOST=airflow<br>AIRFLOW_LOAD_EXAMPLES=no</pre><p>Run:</p><pre>docker-compose up -d</pre><p>Now, Visit <a href="http://localhost:8000/">http://localhost:8000/</a></p><p>Credentials: User — user, Password — bitnami</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XF8BJ53s4frmQaJxFguFsw.png" /><figcaption>Airflow login page</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cg5p-wlPZ4ghPA0WpSmXtg.png" /><figcaption>Airflow Dag list page</figcaption></figure><p><em>References</em></p><ol><li>Book: Data Pipelines with Apache Airflow</li><li>Docker Hub: <a href="https://hub.docker.com/r/bitnami/airflow">https://hub.docker.com/r/bitnami/airflow</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=861cbdd41cc5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting started with Apache Pulsar using Python]]></title>
            <link>https://medium.com/@ravisk1514/getting-started-with-apache-pulsar-using-python-d79681187543?source=rss-691f1bbb91bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/d79681187543</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[apache-pulsar]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Ravi raj]]></dc:creator>
            <pubDate>Sun, 13 Nov 2022 08:26:49 GMT</pubDate>
            <atom:updated>2022-11-13T08:26:49.804Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*PNiJUWmqZY408rTnWPwcQQ.png" /></figure><h3>What is Pulsar?</h3><p>Apache Pulsar is a cloud-native, multi-tenant, high-performance solution for server-to-server messaging and queuing built on the publisher-subscribe (pub-sub) pattern.</p><h3>3 Concepts</h3><h4>Messages</h4><p>These are the basic units of pulsar Few components of a message are:</p><ol><li><strong>payload — </strong>The data carried by the message.</li><li><strong>Key — </strong>Messages are optionally tagged with keys.</li><li><strong>Topic name — </strong>The name of the topic on which the message is published.</li><li><strong>Message ID — </strong>The message ID of a message is assigned by bookies as soon as the message is persistently stored.</li></ol><h4>Producer</h4><p>A producer is a process that attaches to a topic and publishes messages to a Pulsar broker. These messages are processed by the broker.</p><p>There are 3 different types of access modes on topics for producing.</p><ol><li><strong>Shared (Default)</strong> — More than one client can produce the message</li><li><strong>Exclusive</strong> — Only one client can producer</li><li><strong>WaitForExclusive</strong> — If there is already a client connected, the producer creation is pending until the producer gets the Exclusive access.</li></ol><h4>Consumer</h4><p>A consumer is a process that attaches to a topic via a subscription and then receives messages.</p><p>In pulsar, there are 4 types of subscription, as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1ZlUb-xFZeab0aAp" /><figcaption>Image source: <a href="https://pulsar.apache.org/docs/concepts-messaging#subscriptions">pulsar.apache.org/docs/concepts-messaging#s..</a></figcaption></figure><h3>Demo</h3><h4>Setting up pulsar using docker-compose</h4><pre>version: &quot;3&quot;<br>services:<br>  pulsar:<br>    image: apachepulsar/pulsar:latest<br>    command: bin/pulsar standalone<br>    hostname: pulsar<br>    container_name: pulsar<br>    ports:<br>      - &quot;8090:8080&quot;<br>      - &quot;6650:6650&quot;<br>    restart: always<br>    volumes:<br>      - &quot;./data:/pulsar/data&quot;</pre><p>Run the docker-compose: docker-compose up -d</p><p>To check the logs use: docker logs -f pulsar</p><h4>Requirements</h4><p><em>requirement.txt</em></p><pre>pulsar-client[all]==2.10.1</pre><pre>pip3 install -r requirements.txt</pre><h4>Producer</h4><p><a href="http://producer.py/"><em>producer.py</em></a></p><pre>import pulsar<br>import json<br>import random<br><br>uri = &#39;pulsar://localhost:6650&#39;<br>topic= &#39;persistent://public/default/sample&#39;<br><br>client = pulsar.Client(uri)<br>producer = client.create_producer(topic)<br><br>for i in range(10):<br>    data = &#39;message-%d&#39; % random.randint(10,100)<br>    print(&#39;data:&#39;,data)<br>    producer.send(data.encode(&#39;utf-8&#39;))<br><br>client.close()</pre><h4>Consumer</h4><p><a href="http://consumer.py/"><em>consumer.py</em></a></p><pre>import pulsar<br>import datetime<br><br>uri = &#39;pulsar://localhost:6650&#39;<br>topic = &#39;persistent://public/default/sample&#39;<br>subscription_name = &quot;topic-sub-1&quot;<br><br>client = pulsar.Client(uri)<br>consumer = client.subscribe(topic,subscription_name=subscription_name)<br><br>while True:<br>    msg = consumer.receive()<br>    try:<br>        print(msg.publish_timestamp(), msg.message_id())<br>        consumer.acknowledge(msg)<br>    except Exception:<br>        # Message failed to be processed<br>        consumer.negative_acknowledge(msg)<br><br>    client.close()</pre><h4>Run</h4><pre>python producer.py</pre><p><em>output</em></p><pre><br>data: message-96<br>data: message-17<br>data: message-74<br>data: message-94<br>data: message-40<br>data: message-28<br>data: message-81<br>data: message-82<br>data: message-73<br>data: message-57</pre><pre>python consumer.py</pre><p><em>output</em></p><pre><br>Timestamp: 1668181403573, Message ID: (837,39,-1,-1), Payload: b&#39;message-96&#39;<br>Timestamp: 1668181403638, Message ID: (837,40,-1,-1), Payload: b&#39;message-17&#39;<br>Timestamp: 1668181403653, Message ID: (837,41,-1,-1), Payload: b&#39;message-74&#39;<br>Timestamp: 1668181403668, Message ID: (837,42,-1,-1), Payload: b&#39;message-94&#39;<br>Timestamp: 1668181403688, Message ID: (837,43,-1,-1), Payload: b&#39;message-40&#39;<br>Timestamp: 1668181403698, Message ID: (837,44,-1,-1), Payload: b&#39;message-28&#39;<br>Timestamp: 1668181403711, Message ID: (837,45,-1,-1), Payload: b&#39;message-81&#39;<br>Timestamp: 1668181403726, Message ID: (837,46,-1,-1), Payload: b&#39;message-82&#39;<br>Timestamp: 1668181403742, Message ID: (837,47,-1,-1), Payload: b&#39;message-73&#39;<br>Timestamp: 1668181403754, Message ID: (837,48,-1,-1), Payload: b&#39;message-57&#39;</pre><p><em>Note:</em> Run consumer before producer to see the consumed message in real-time</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d79681187543" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Data Pipeline — MongoDB, Debezium, Kafka, Kafka Connect — Part 1]]></title>
            <link>https://medium.com/@ravisk1514/building-data-pipeline-mongodb-debezium-kafka-kafka-connect-part-1-3cadcd2fc9a9?source=rss-691f1bbb91bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/3cadcd2fc9a9</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Ravi raj]]></dc:creator>
            <pubDate>Wed, 31 Aug 2022 11:50:31 GMT</pubDate>
            <atom:updated>2022-08-31T12:01:06.750Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building Data Pipeline — MongoDB, Debezium, Kafka, Kafka Connect — Part 1: Mongo Setup</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8wD0d7m3avBCyZtOMNDejA.jpeg" /><figcaption><a href="https://www.bigscal.com/wp-content/uploads/2022/01/How-to-setup-Node.jpg">How-to-setup-Node.jpg</a></figcaption></figure><p>This is a three-part blog, where we are going to learn how to set up a data pipeline that will take the oplogs from MongoDB and store them into Kafka topics using Debezium.</p><p>In this part we will set up MongoDB, NodeJS application to insert records into MongoDB and MongoUI for other purpose.</p><h4>Prerequisite</h4><ol><li>Docker [<a href="https://docs.docker.com/desktop/install/linux-install/">Linux</a>] [W<a href="https://docs.docker.com/desktop/install/windows-install/">indows</a>] [<a href="https://docs.docker.com/desktop/install/mac-install/">Mac</a>]</li></ol><h4>High-Level Diagram</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7gtzyDjlC-IbNs0gI2FVtw.png" /></figure><p>We will use <em>docker-compose.yml</em> to set up the services.</p><h4>Setup Mongo Service</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9b2bda0b2ce3e47381740a08cd1ba6c/href">https://medium.com/media/b9b2bda0b2ce3e47381740a08cd1ba6c/href</a></iframe><p>./mongodb/data:/data/db is for data-persistent</p><h4>Setup Nodejs App Service</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46ee59ca76e2eb2ace7d5b4af2501c0d/href">https://medium.com/media/46ee59ca76e2eb2ace7d5b4af2501c0d/href</a></iframe><p>Above service will insert 10 message at interval of 2 sec in collection: users of db: debezium_db</p><p>We can validate the inserts by following commands:</p><pre>docker exec -it mongodb /bin/bash<br>mongosh -u debeziumUser -p debeziumUser<br>use debezium_db<br>db.users.find().limit(1).pretty()</pre><p>Output</p><pre>[<br>  {<br>    _id: ObjectId(&quot;630f348309c687fcbef0524e&quot;),<br>    id: &#39;630f34838a7aa8b6db603625&#39;,<br>    currentJob: { title: &#39;Developer&#39;, salary: &#39;mask;&#39; },<br>    maxRunDistance: 11.9,<br>    cpf: &#39;468.615.337-93&#39;,<br>    cnpj: &#39;56.815.857/0001-14&#39;,<br>    pretendSalary: &#39;R$ 8.753,03&#39;,<br>    age: 30,<br>    gender: &#39;female&#39;,<br>    firstName: &#39;Gomez&#39;,<br>    lastName: &#39;Alexander&#39;,<br>    phone: &#39;+55 (83) 96507-8102&#39;,<br>    address: &#39;65 Drew Street - Klondike, Federated States Of Micronesia, Vatican City State (Holy See).&#39;,<br>    hairColor: &#39;spring green&#39;<br>  }<br>]</pre><p>Running command by docker iterative is good for debugging purpose. We can make our task easier by using the next service.</p><h4>Setup Mongo UI Service</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed59c08395d6297e25960c02ff9f4f63/href">https://medium.com/media/ed59c08395d6297e25960c02ff9f4f63/href</a></iframe><p>Visit <a href="http://localhost:3100/servers"><em>http://localhost:3100/servers</em></a><em> to </em>access the mongo_ui</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mNhWdk9FuY2PmH4f9DDoQA.png" /></figure><h4>Useful Docker Commands</h4><ol><li>docker ps — list all the running containers</li><li>docker logs -f &lt;my_container&gt; — tails the logs of container</li><li>docker restart &lt;my_container&gt; — restart the container</li></ol><p><strong>Note: </strong>sudo is required if you are using linux installation for docker.</p><p>Final file</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6596ef39d4c0ec1e54423a82c3f3a919/href">https://medium.com/media/6596ef39d4c0ec1e54423a82c3f3a919/href</a></iframe><h4>References:</h4><ol><li><a href="https://hub.docker.com/_/mongo">https://hub.docker.com/_/mongo</a></li><li><a href="https://hub.docker.com/r/teqsk1514/cdc-node-app">https://hub.docker.com/r/teqsk1514/cdc-node-app</a></li><li><a href="https://hub.docker.com/r/huggingface/mongoku">https://hub.docker.com/r/huggingface/mongoku</a></li><li><a href="https://dockerlabs.collabnix.com/docker/cheatsheet/">https://dockerlabs.collabnix.com/docker/cheatsheet/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3cadcd2fc9a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL — 108 (Intermediate)]]></title>
            <link>https://medium.com/@ravisk1514/sql-108-intermediate-77e13e49517?source=rss-691f1bbb91bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/77e13e49517</guid>
            <category><![CDATA[hackerrank]]></category>
            <category><![CDATA[hackerrank-solution]]></category>
            <category><![CDATA[sql-solution]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[sql-joins]]></category>
            <dc:creator><![CDATA[Ravi raj]]></dc:creator>
            <pubDate>Sun, 12 Jun 2022 03:40:24 GMT</pubDate>
            <atom:updated>2022-06-12T03:40:24.401Z</atom:updated>
            <content:encoded><![CDATA[<h3>SQL — 108 (Intermediate)</h3><h3>Introduction</h3><p>This series is the revision of SQL concepts. In this blog, I will solve some intermediate questions from Hackerrank.</p><p>Basics questions are already solved in the previous blogs. [Links are at the end of the blog]</p><h4><strong>Question 1</strong></h4><p>[<a href="https://www.hackerrank.com/challenges/binary-search-tree-1/problem">Ref: Hackerrank</a>]</p><p>You are given a table, BST, containing two columns: N and P, where N represents the value of a node in a Binary Tree, and P is the parent of N.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/0*MPZRahRTc5YyZuC0.png" /></figure><p>Write a query to find the node type of Binary Tree ordered by the value of the node. Output one of the following for each node:</p><ul><li><strong><em>Root</em></strong>: If the node is the root node.</li><li><strong><em>Leaf</em></strong>: If the node is a leaf node.</li><li><strong><em>Inner</em></strong>: If the node is neither root nor leaf node.</li></ul><p><strong>Sample Input</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/0*FymOz3QtayAUlukG.png" /></figure><p><strong>Sample Output</strong></p><pre>1 Leaf<br>2 Inner<br>3 Leaf<br>5 Root<br>6 Leaf<br>8 Inner<br>9 Leaf</pre><p><strong>Explanation:</strong></p><p>The Binary Tree below illustrates the sample:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*iEa1q2mMSx-nBLHjZL7fvg.png" /></figure><p><strong>Solution:</strong></p><pre>SELECT N AS Node,<br>    CASE<br>        WHEN P IS NULL THEN &#39;Root&#39;<br>        WHEN N IN (SELECT DISTINCT P FROM BST) THEN &#39;Inner&#39;<br>        ELSE &#39;Leaf&#39;<br>    END<br>FROM BST<br>ORDER BY Node;</pre><h4>Question 2</h4><p>[<a href="https://www.hackerrank.com/challenges/placements/problem">Ref: Hackerrank</a>]</p><p>You are given three tables: Students, Friends and Packages. Students contains two columns: ID and Name. Friends contains two columns: ID and Friend_ID (ID of the ONLY best friend). Packages contains two columns: ID and Salary (offered salary in $ thousands per month).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/0*4kZSVAwmY60twXOw.png" /></figure><p>Write a query to output the names of those students whose best friends got offered a higher salary than them. Names must be ordered by the salary amount offered to the best friends. It is guaranteed that no two students got same salary offer.</p><p><strong>Sample Input</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/0*GU6g7MT3F0FO3MOo.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/0*VYuRoobwrNolcK3Y.png" /></figure><p><strong>Sample Output</strong></p><pre>Samantha<br>Julia<br>Scarlet</pre><p><strong>Explanation</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*XFJp-E62FqQuQmz--uDNaQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*dbWp69822yZt3iKqPjW1kA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*wyevAu6q6i9KDk2tTths9A.png" /></figure><p>See the following table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/0*la7pInw0uYV0trTz.png" /></figure><p>Now,</p><ul><li>Samantha’s best friend got offered a higher salary than her at 11.55</li><li>Julia’s best friend got offered a higher salary than her at 12.12</li><li>Scarlet’s best friend got offered a higher salary than her at 15.2</li><li>Ashley’s best friend did NOT get offered a higher salary than her</li></ul><p>The name output, when ordered by the salary offered to their friends, will be:</p><ul><li>Samantha</li><li>Julia</li><li>Scarlet</li></ul><p><strong>Solution:</strong></p><pre>SELECT S.name FROM STUDENTS S <br>JOIN FRIENDS F ON S.ID = F.ID<br>JOIN PACKAGES Student_Package ON S.ID = Student_Package.ID<br>JOIN packages BestFriend_Package ON F.Friend_id = BestFriend_Package.ID<br>WHERE Student_Package.salary &lt; BestFriend_Package.salary<br>ORDER BY BestFriend_Package.salary;</pre><h4>Previous Posts</h4><ol><li><a href="https://medium.com/@ravisk1514/sql-104-basics-aggregation-9ab6c3be0087">SQL — 104 (Basics) Aggregation</a></li><li><a href="https://medium.com/@ravisk1514/sql-105-basics-aggregation-b2ef1ec12b0e">SQL — 105 (Basics) Aggregation</a></li><li><a href="https://medium.com/@ravisk1514/sql-106-basics-joins-6b9e5e6060dd">SQL — 106 (Basics) Joins</a></li><li><a href="https://medium.com/@ravisk1514/sql-107-basics-misc-5de45a3b02da">SQL — 107 (Basics) Misc</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77e13e49517" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL — 107 (Basics) Misc]]></title>
            <link>https://medium.com/@ravisk1514/sql-107-basics-misc-5de45a3b02da?source=rss-691f1bbb91bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/5de45a3b02da</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[sql-solution]]></category>
            <category><![CDATA[hackerrank-sql]]></category>
            <category><![CDATA[hackerrank]]></category>
            <category><![CDATA[hackerrank-solution]]></category>
            <dc:creator><![CDATA[Ravi raj]]></dc:creator>
            <pubDate>Tue, 31 May 2022 05:51:37 GMT</pubDate>
            <atom:updated>2022-05-31T05:51:37.039Z</atom:updated>
            <content:encoded><![CDATA[<h3>SQL — 107 (Basics) Misc</h3><h3>Introduction</h3><p>This series is the revision of SQL concepts. We are doing the basic questions, then intermediate, and so on.</p><h4><strong>Question 1</strong></h4><p>[<a href="https://www.hackerrank.com/challenges/the-pads/problem">Ref: Hackerrank</a>]</p><p>Generate the following two result sets:</p><ol><li>Query an alphabetically ordered list of all names in <strong>OCCUPATIONS</strong>, immediately followed by the first letter of each profession as a parenthetical (i.e.: enclosed in parentheses). For example: AnActorName(A), ADoctorName(D), AProfessorName(P), and ASingerName(S).</li><li>Query the number of ocurrences of each occupation in <strong>OCCUPATIONS</strong>. Sort the occurrences in ascending order, and output them in the following format:</li></ol><ul><li>There are a total of [occupation_count] [occupation]s.</li></ul><p>where [occupation_count] is the number of occurrences of an occupation in <strong>OCCUPATIONS</strong> and [occupation] is the lowercase occupation name. If more than one Occupation has the same [occupation_count], they should be ordered alphabetically.</p><p><strong>Note:</strong> There will be at least two entries in the table for each type of occupation.</p><p><strong>Input Format</strong></p><p>The <strong>OCCUPATIONS</strong> table is described as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/0*sMmGNYfrFNHMCHnz.png" /></figure><p>Occupation will only contain one of the following values: <strong>Doctor</strong>, <strong>Professor</strong>, <strong>Singer</strong> or <strong>Actor</strong>.</p><p><strong>Sample Input</strong></p><p>An <strong>OCCUPATIONS</strong> table that contains the following records:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/0*LBWj1tItmUgNzJ_z.png" /></figure><p><strong>Sample Output</strong></p><pre>Ashely(P)<br>Christeen(P)<br>Jane(A)<br>Jenny(D)<br>Julia(A)<br>Ketty(P)<br>Maria(A)<br>Meera(S)<br>Priya(S)<br>Samantha(D)<br>There are a total of 2 doctors.<br>There are a total of 2 singers.<br>There are a total of 3 actors.<br>There are a total of 3 professors.</pre><p><strong>Explanation</strong></p><p>The results of the first query are formatted to the problem description’s specifications.<br>The results of the second query are ascendingly ordered first by number of names corresponding to each profession <strong><em>(2≤2≤3≤3), </em></strong>and then alphabetically by profession ( <strong><em>doctor ≤ singer ≤, </em></strong>and <strong><em>actor ≤ professor</em></strong>).</p><h4><strong>Solution:</strong></h4><pre>SELECT CONCAT(Name,&#39;(&#39;,SUBSTRING(Occupation,1,1),&#39;)&#39;) FROM OCCUPATIONS ORDER BY Name;<br>SELECT CONCAT(&#39;There are a total of &#39;,COUNT(Occupation), &#39; &#39;, LOWER(Occupation),&#39;s.&#39;) FROM OCCUPATIONS GROUP BY Occupation ORDER BY count(OCCUPATION) ASC;</pre><h4>Question 2</h4><p>[<a href="https://www.hackerrank.com/challenges/weather-observation-station-18/problem">Ref: Hackerrank</a>]</p><p>Consider<em> </em><strong><em>P1(a,b)</em></strong><em> and </em><strong><em>P2(c,d)</em> </strong>to be two points on a 2D plane.</p><ul><li><strong><em>a</em></strong> happens to equal the minimum value in Northern Latitude (LAT_N in <strong>STATION</strong>).</li><li><strong><em>b </em></strong>happens to equal the minimum value in Western Longitude (LONG_W in <strong>STATION</strong>).</li><li><strong><em>c </em></strong>happens to equal the maximum value in Northern Latitude (LAT_N in <strong>STATION</strong>).</li><li><strong><em>d</em></strong> happens to equal the maximum value in Western Longitude (LONG_W in <strong>STATION</strong>).</li></ul><p>Query the <a href="https://xlinux.nist.gov/dads/HTML/manhattanDistance.html">Manhattan Distance</a> between points <strong><em>P1 </em></strong>and <strong><em>P2</em></strong> and round it to a scale of <strong><em>4</em></strong> decimal places.</p><p><strong>Input Format</strong></p><p>The <strong>STATION</strong> table is described as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*rn7woEWCXvJSvPDs.jpg" /></figure><p>where LAT_N is the northern latitude and LONG_W is the western longitude.</p><h4>Solution:</h4><pre>SELECT ROUND(ABS(MIN(LAT_N) -  MAX(LAT_N)) +  ABS(MIN(LONG_W) - MAX(LONG_W)),4)  FROM STATION</pre><h4>Question 3</h4><p>[<a href="https://www.hackerrank.com/challenges/weather-observation-station-19/problem">Ref: Hackerrank</a>]</p><p>Consider <strong><em>P1(a,b)</em></strong><em> and </em><strong><em>P2(c,d)</em></strong> to be two points on a 2D plane where <strong><em>(a,b)</em></strong> are the respective minimum and maximum values of Northern Latitude (LAT_N) and are <strong><em>(c,d)</em></strong> the respective minimum and maximum values of Western Longitude (LONG_W) in <strong>STATION</strong>.</p><p>Query the <a href="https://en.wikipedia.org/wiki/Euclidean_distance">Euclidean Distance</a> between points <strong><em>P1 </em></strong>and <strong><em>P2</em></strong> and format your answer to display <strong><em>4</em></strong> decimal digits.</p><p><strong>Input Format</strong></p><p>The <strong>STATION</strong> table is described as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*6jbipKVZDlGDSz1-.jpg" /></figure><p>where LAT_N is the northern latitude and LONG_W is the western longitude.</p><h4>Solution:</h4><pre>SELECT ROUND(SQRT(POWER(MIN(LAT_N) -  MAX(LAT_N),2) +  POWER(MIN(LONG_W) - MAX(LONG_W),2)),4)  FROM STATION</pre><h3>Previous Posts</h3><ol><li><a href="https://medium.com/@ravisk1514/sql-101-511e34f923df">SQL 101</a></li><li><a href="https://medium.com/@ravisk1514/sql-102-basics-222836417d1e">SQL 102 (Basics)</a></li><li><a href="https://medium.com/@ravisk1514/sql-103-basics-f6d470984619">SQL — 103 (Basics)</a></li><li><a href="https://medium.com/@ravisk1514/sql-104-basics-aggregation-9ab6c3be0087">SQL — 104 (Basics) Aggregation</a></li><li><a href="https://medium.com/@ravisk1514/sql-105-basics-aggregation-b2ef1ec12b0e">SQL — 105 (Basics) Aggregation</a></li><li><a href="https://medium.com/@ravisk1514/sql-106-basics-joins-6b9e5e6060dd">SQL — 106 (Basics) Joins</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5de45a3b02da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL — 106 (Basics) Joins]]></title>
            <link>https://medium.com/@ravisk1514/sql-106-basics-joins-6b9e5e6060dd?source=rss-691f1bbb91bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b9e5e6060dd</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[hackerrank]]></category>
            <category><![CDATA[sql-joins]]></category>
            <category><![CDATA[sql-solution]]></category>
            <dc:creator><![CDATA[Ravi raj]]></dc:creator>
            <pubDate>Sat, 28 May 2022 08:10:52 GMT</pubDate>
            <atom:updated>2022-05-28T08:10:52.266Z</atom:updated>
            <content:encoded><![CDATA[<h3>SQL — 106 (Basics) Joins</h3><h3>Introduction</h3><p>This series is the revision of SQL concepts. We are doing the basic questions, then intermediate, and so on.</p><h3>Previous Posts</h3><ol><li><a href="https://medium.com/@ravisk1514/sql-101-511e34f923df">SQL 101</a></li><li><a href="https://medium.com/@ravisk1514/sql-102-basics-222836417d1e">SQL 102 (Basics)</a></li><li><a href="https://medium.com/@ravisk1514/sql-103-basics-f6d470984619">SQL — 103 (Basics)</a></li><li><a href="https://medium.com/@ravisk1514/sql-104-basics-aggregation-9ab6c3be0087">SQL — 104 (Basics) Aggregation</a></li><li><a href="https://medium.com/@ravisk1514/sql-105-basics-aggregation-b2ef1ec12b0e">SQL — 105 (Basics) Aggregation</a></li></ol><p><strong>CITY </strong>Table description</p><pre>┌─────────────┬──────────────┐<br>│    Field    │     Type     │<br>├─────────────┼──────────────┤<br>│ ID          │ NUMBER       │<br>│ NAME        │ VARCHAR2(17) │<br>│ COUNTRYCODE │ VARCHAR2(3)  │<br>│ DISTRICT    │ VARCHAR2(20) │<br>│ POPULATION  │ NUMBER       │<br>└─────────────┴──────────────┘</pre><p><strong>COUNTRY </strong>Table description</p><pre>┌────────────────┬─────────────┐<br>│     Field      │    Type     │<br>├────────────────┼─────────────┤<br>│ CODE           │ VARCHAR(3)  │<br>│ NAME           │ VARCHAR(44) │<br>│ CONTINENT      │ VARCHAR(13) │<br>│ REGION         │ VARCHAR(25) │<br>│ SURFACEAREA    │ NUMBER      │<br>│ INDEPYEAR      │ VARCHAR(5)  │<br>│ POPULATION     │ NUMBER      │<br>│ LIFEEXPECTANCY │ VARCHAR(4)  │<br>│ GNP            │ NUMBER      │<br>│ GNPOLD         │ VARCHAR(9)  │<br>│ LOCALNAME      │ VARCHAR(44) │<br>│ GOVERMENTFROM  │ VARCHAR(44) │<br>│ HEADOFSTATE    │ VARCHAR(32) │<br>│ CAPITAL        │ VARCHAR(4)  │<br>│ CODE2          │ VARCHAR(4)  │<br>└────────────────┴─────────────┘</pre><h4>Question 1</h4><p>[<a href="https://www.hackerrank.com/challenges/asian-population/problem">Ref: Hackerrank</a>]</p><p>Given the <strong>CITY</strong> and <strong>COUNTRY</strong> tables, query the sum of the populations of all cities where the CONTINENT is ‘Asia’.</p><p><strong>Note:</strong> CITY.CountryCode and COUNTRY.Code are matching key columns.</p><p><strong>Solution:</strong></p><pre>SELECT SUM(CITY.POPULATION) FROM CITY INNER JOIN COUNTRY ON CITY.CountryCode = COUNTRY.Code WHERE COUNTRY.CONTINENT = &#39;Asia&#39;</pre><h4>Question 2</h4><p>[<a href="https://www.hackerrank.com/challenges/african-cities/problem">Ref: Hackerrank</a>]</p><p>Given the <strong>CITY</strong> and <strong>COUNTRY</strong> tables, query the names of all cities where the CONTINENT is ‘Africa’.</p><p><strong>Note:</strong> CITY.CountryCode and COUNTRY.Code are matching key columns.</p><p><strong>Solution:</strong></p><pre>SELECT (CITY.NAME) FROM CITY INNER JOIN COUNTRY ON CITY.CountryCode = COUNTRY.Code WHERE COUNTRY.CONTINENT = &#39;Africa&#39;</pre><h4>Question 3</h4><p>[<a href="https://www.hackerrank.com/challenges/average-population-of-each-continent/problem">Ref: Hackerrank</a>]</p><p>Given the <strong>CITY</strong> and <strong>COUNTRY</strong> tables, query the names of all the continents (COUNTRY.Continent) and their respective average city populations (CITY.Population) rounded down to the nearest integer.</p><p><strong>Note:</strong> CITY.CountryCode and COUNTRY.Code are matching key columns.</p><p><strong>Solution:</strong></p><pre>SELECT A.Continent, FLOOR(AVG(A.Population))  FROM (SELECT COUNTRY.Continent, CITY.POPULATION  FROM CITY INNER JOIN COUNTRY ON CITY.CountryCode = COUNTRY.Code ) A GROUP BY A.Continent</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b9e5e6060dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL — 105 (Basics) Aggregation]]></title>
            <link>https://medium.com/@ravisk1514/sql-105-basics-aggregation-b2ef1ec12b0e?source=rss-691f1bbb91bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2ef1ec12b0e</guid>
            <category><![CDATA[aggregation]]></category>
            <category><![CDATA[hackerrank]]></category>
            <category><![CDATA[hackerrank-solution]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[hackerrank-sql]]></category>
            <dc:creator><![CDATA[Ravi raj]]></dc:creator>
            <pubDate>Thu, 26 May 2022 06:48:30 GMT</pubDate>
            <atom:updated>2022-05-26T06:48:30.198Z</atom:updated>
            <content:encoded><![CDATA[<h3>SQL — 105 (Basics) Aggregation</h3><h3>Introduction</h3><p>This series is the revision of SQL concepts. We are doing the basic questions, then intermediate, and so on.</p><p>All questions use the aggregation concept. You can learn more <a href="https://www.geeksforgeeks.org/aggregate-functions-in-sql/"><em>here</em></a>.</p><h3>Previous Posts</h3><ol><li><a href="https://medium.com/@ravisk1514/sql-101-511e34f923df">SQL 101</a></li><li><a href="https://medium.com/@ravisk1514/sql-102-basics-222836417d1e">SQL 102 (Basics)</a></li><li><a href="https://medium.com/@ravisk1514/sql-103-basics-f6d470984619">SQL — 103 (Basics)</a></li><li><a href="https://medium.com/@ravisk1514/sql-104-basics-aggregation-9ab6c3be0087">SQL — 104 (Basics) Aggregation</a></li></ol><p><strong>STATION </strong>Table description</p><pre>┌────────┬─────────────┐<br>│ Field  │    Type     │<br>├────────┼─────────────┤<br>│ ID     │ NUMBER      │<br>│ CITY   │ VARCHAR(21) │<br>│ STATE  │ VARCHAR(2)  │<br>│ LAT_N  │ NUMBER      │<br>│ LONG_W │ NUMBER      │<br>└────────┴─────────────┘</pre><p>where LAT_N is the northern latitude and LONG_W is the western longitude.</p><h4>Question 1</h4><p>[<a href="https://www.hackerrank.com/challenges/weather-observation-station-2/problem">Ref: Hackerrank</a>]</p><p>Query the following two values from the <strong>STATION</strong> table:</p><ol><li>The sum of all values in LAT_N rounded to a scale of <strong><em>2</em></strong> decimal places.</li><li>The sum of all values in LONG_W rounded to a scale of <strong><em>2</em></strong> decimal places.</li></ol><p><strong>Output Format</strong></p><p>Your results must be in the form:</p><pre>lat lon</pre><p>where <strong><em>lat </em></strong>is the sum of all values in LAT_N and <strong><em>lon</em></strong> is the sum of all values in LONG_W. Both results must be rounded to a scale of <strong><em>2</em></strong> decimal places.</p><p><strong>Solution:</strong></p><pre>SELECT ROUND(SUM(LAT_N ),2), ROUND(SUM(LONG_W ),2) FROM STATION;</pre><h4>Question 2</h4><p>[<a href="https://www.hackerrank.com/challenges/weather-observation-station-13/problem">Ref: Hackerrank</a>]</p><p>Query the sum of Northern Latitudes (LAT_N) from <strong>STATION</strong> having values greater than <strong><em>38.7880</em></strong> and less than 1<strong><em>37.2345</em></strong> . Truncate your answer to <strong><em>4</em></strong> decimal places.</p><p><strong>Solution:</strong></p><pre>SELECT ROUND(SUM(LAT_N),4) FROM STATION WHERE LAT_N &gt; 38.7880 and LAT_N &lt; 137.2345;</pre><h4>Question 3</h4><p>[<a href="https://www.hackerrank.com/challenges/weather-observation-station-14/problem">Ref: Hackerrank</a>]</p><p>Query the greatest value of the Northern Latitudes (LAT_N) from <strong>STATION</strong> that is less than 1<strong><em>37.2345</em></strong>. Truncate your answer to <strong><em>4</em></strong> decimal places.</p><p><strong>Solution:</strong></p><pre>SELECT ROUND(MAX(LAT_N),4) FROM STATION WHERE LAT_N &lt; 137.2345;</pre><h4>Question 4</h4><p>[<a href="https://www.hackerrank.com/challenges/weather-observation-station-15/problem">Ref: Hackerrank</a>]</p><p>Query the Western Longitude (LONG_W) for the largest Northern Latitude (LAT_N) in <strong>STATION</strong> that is less than <strong><em>137.2345</em></strong>. Round your answer to <strong><em>4</em></strong> decimal places.</p><p><strong>Solution:</strong></p><pre>SELECT ROUND(LONG_W,4) FROM STATION WHERE LAT_N = (SELECT MAX(LAT_N) FROM STATION WHERE LAT_N &lt; 137.2345);</pre><p><strong>Explanation:</strong></p><ol><li>SELECT MAX(LAT_N) FROM STATION WHERE LAT_N &lt; 137.2345 will give the largest Northern Latitude in STATION that is less than <strong><em>137.2345</em></strong></li></ol><h4>Question 5</h4><p>[<a href="https://www.hackerrank.com/challenges/weather-observation-station-16/problem">Ref: Hackerrank</a>]</p><p>Query the smallest Northern Latitude (LAT_N) from <strong>STATION</strong> that is greater than <strong><em>38.7780</em></strong> . Round your answer to <strong><em>4</em></strong> decimal places.</p><p><strong>Solution:</strong></p><pre>SELECT ROUND(MIN(LAT_N),4) FROM STATION WHERE LAT_N &gt; 38.7780</pre><h4>Question 6</h4><p>[<a href="https://www.hackerrank.com/challenges/weather-observation-station-17/problem">Ref: Hackerrank</a>]</p><p>Query the Western Longitude (LONG_W)where the smallest Northern Latitude (LAT_N) in <strong>STATION</strong> is greater than <strong><em>38.7780</em></strong> . Round your answer to <strong><em>4 </em></strong>decimal places.</p><p><strong>Solution:</strong></p><pre>SELECT ROUND(LONG_W,4) FROM STATION WHERE LAT_N = (SELECT MIN(LAT_N) FROM STATION WHERE LAT_N &gt; 38.7780);</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2ef1ec12b0e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL — 104 (Basics) Aggregation]]></title>
            <link>https://medium.com/@ravisk1514/sql-104-basics-aggregation-9ab6c3be0087?source=rss-691f1bbb91bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ab6c3be0087</guid>
            <category><![CDATA[hackerrank]]></category>
            <category><![CDATA[aggregation]]></category>
            <category><![CDATA[sql-solution]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Ravi raj]]></dc:creator>
            <pubDate>Tue, 24 May 2022 10:03:23 GMT</pubDate>
            <atom:updated>2022-05-24T10:03:23.302Z</atom:updated>
            <content:encoded><![CDATA[<h3>SQL — 104 (Basics) Aggregation</h3><h3>Introduction</h3><p>This series is the revision of SQL concepts. We are doing the basic questions, then intermediate, and so on.</p><p>All questions use the aggregation concept. You can learn more <a href="https://www.geeksforgeeks.org/aggregate-functions-in-sql/"><em>here</em></a>.</p><h3>Previous Posts</h3><ol><li><a href="https://medium.com/@ravisk1514/sql-101-511e34f923df">SQL 101</a></li><li><a href="https://medium.com/@ravisk1514/sql-102-basics-222836417d1e">SQL 102 (Basics)</a></li><li><a href="https://medium.com/@ravisk1514/sql-103-basics-f6d470984619">SQL — 103 (Basics)</a></li></ol><h4>CITY table</h4><pre>┌─────────────┬──────────────┐<br>│    Field    │     Type     │<br>├─────────────┼──────────────┤<br>│ ID          │ NUMBER       │<br>│ NAME        │ VARCHAR2(17) │<br>│ COUNTRYCODE │ VARCHAR2(3)  │<br>│ DISTRICT    │ VARCHAR2(20) │<br>│ POPULATION  │ NUMBER       │<br>└─────────────┴──────────────┘</pre><h4><strong>Question 1</strong></h4><p>[<a href="https://www.hackerrank.com/challenges/revising-aggregations-the-count-function/problem">Ref: Hackerrank</a>]</p><p>Query counts the number of cities in the <strong>CITY</strong> having a Population larger than <strong>100,000</strong>.</p><p><strong>Solution:</strong></p><pre>SELECT COUNT(*) FROM CITY WHERE POPULATION &gt; 100000;</pre><h4>Question 2</h4><p>[<a href="https://www.hackerrank.com/challenges/revising-aggregations-sum/problem">Ref: Hackerrank</a>]</p><p>Query the total population of all cities in <strong>CITY</strong> where District is <strong>California</strong>.</p><p><strong>Solution:</strong></p><pre>SELECT SUM(POPULATION) FROM CITY WHERE DISTRICT = &#39;California&#39;;</pre><h4>Question 3</h4><p>[<a href="https://www.hackerrank.com/challenges/revising-aggregations-the-average-function/problem">Ref: Hackerrank</a>]</p><p>Query the average population of all cities in <strong>CITY</strong> where District is <strong>California</strong>.</p><p><strong>Solution:</strong></p><pre>SELECT AVG(POPULATION) FROM CITY WHERE DISTRICT = &#39;California&#39;;</pre><h4>Question 4</h4><p>[<a href="https://www.hackerrank.com/challenges/average-population/problem">Ref: Hackerrank</a>]</p><p>Query the average population for all cities in <strong>CITY</strong>, rounded down to the nearest integer.</p><p><strong>Solution:</strong></p><pre>SELECT ROUND(AVG(POPULATION)) FROM CITY WHERE DISTRICT = &#39;California&#39;;</pre><h4>Question 5</h4><p>[<a href="https://www.hackerrank.com/challenges/population-density-difference/problem">Ref: Hackerrank</a>]</p><p>Query the difference between the maximum and minimum populations in <strong>CITY</strong>.</p><p><strong>Solution:</strong></p><pre>SELECT MAX(POPULATION) - MIN(POPULATION) FROM CITY ;</pre><h4>Question 6</h4><p>[<a href="https://www.hackerrank.com/challenges/the-blunder/problem?isFullScreen=false">Ref: Hackerrank</a>]</p><p>Samantha was tasked with calculating the average monthly salaries for all employees in the <strong>EMPLOYEES</strong> table but did not realize her keyboard’s key was broken until after completing the calculation. She wants your help finding the difference between her miscalculation (using salaries with any zeros removed), and the actual average salary.</p><p>Write a query calculating the amount of error (i.e.: <em>actual — miscalculated </em>average monthly salaries), and round it up to the next integer. The table description is shown below:</p><pre>┌────────┬─────────┐<br>│ Field  │  Type   │<br>├────────┼─────────┤<br>│ ID     │ Integer │<br>│ NAME   │ String  │<br>│ SALARY │ Integer │<br>└────────┴─────────┘</pre><p>Note: Salary is per month</p><p>Constraints<br>1000 &lt; Salary &lt; 10⁵</p><p>Sample Input</p><pre>┌────┬──────────┬────────┐<br>│ ID │  Name    │ Salary │<br>├────┼──────────┼────────┤<br>│  1 │ Kristeen │   1420 │<br>│  2 │ Ashley   │   2006 │<br>│  3 │ Julia    │   2210 │<br>│  4 │ Maria    │   3000 │<br>└────┴──────────┴────────┘</pre><p>Sample Output</p><pre>2061</pre><p><strong>Explanation:</strong></p><p>The table below shows the salaries without zeros as they were entered by Samantha:</p><pre>┌────┬──────────┬────────┐<br>│ ID │  Name    │ Salary │<br>├────┼──────────┼────────┤<br>│  1 │ Kristeen │    142 │<br>│  2 │ Ashley   │     26 │<br>│  3 │ Julia    │    221 │<br>│  4 │ Maria    │      3 │<br>└────┴──────────┴────────┘</pre><p>Samantha computes an average salary of <strong>98.00</strong>. The actual average salary is <strong>2159.00</strong>.</p><p>The resulting error between the two calculations is <strong>2159.00 — 98.00 = 2061.00</strong>. Since it is equal to the integer <strong>2061</strong>, it does not get rounded up.</p><p><strong>Solution:</strong></p><pre>SELECT CEIL(AVG(Salary)-AVG(REPLACE(Salary,&#39;0&#39;,&#39;&#39;))) FROM EMPLOYEES;</pre><h4>Question 7</h4><p>[<a href="http://hackerrank.com/challenges/earnings-of-employees/problem?isFullScreen=true">Ref: Hackerrank</a>]</p><p>We define an employee’s total earnings to be their monthly <strong><em>salary * months </em></strong>worked, and the maximum total earnings to be the maximum total earnings for any employee in the <strong>Employee</strong> table. Write a query to find the maximum total earnings for all employees as well as the total number of employees who have maximum total earnings. Then print these <strong><em>2</em></strong> values as space-separated integers.</p><p><strong>Input Format</strong></p><p>The <strong>Employee</strong> table containing employee data for a company is described as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/191/0*Cf3Vowh3ErNgu9OA.png" /></figure><p>where employee_id is an employee’s ID number, name is their name, months is the total number of months they’ve been working for the company, and salary is the their monthly salary.</p><p><strong>Sample Input</strong></p><pre>┌─────────────┬──────────┬────────┬────────┐<br>│ employee_id │  name    │ months │ Salary │<br>├─────────────┼──────────┼────────┼────────┤<br>│       12228 │ Rose     │     15 │   1968 │<br>│       33645 │ Angela   │      1 │   3443 │<br>│       45692 │ Frank    │     17 │   1680 │<br>│       56118 │ Pathrick │      7 │   1345 │<br>│       59725 │ Lisa     │     11 │   2330 │<br>│       74197 │ Kimberly │     16 │   4372 │<br>│       78454 │ Bonnie   │      8 │   1771 │<br>│       83565 │ Michaeal │      6 │   1017 │<br>│       98607 │ Todd     │      5 │   3396 │<br>│       99989 │ Joe      │      9 │   3573 │<br>└─────────────┴──────────┴────────┴────────┘</pre><p><strong>Sample Output</strong></p><pre>69952 1</pre><p><strong>Explanation</strong></p><p>The table and earnings data is depicted in the following diagram:</p><pre>┌─────────────┬──────────┬────────┬────────┬──────────┐<br>│ employee_id │  name    │ months │ salary │ earnings │<br>├─────────────┼──────────┼────────┼────────┼──────────┤<br>│       12228 │ Rose     │     15 │   1968 │    29520 │<br>│       33645 │ Angela   │      1 │   3443 │     3443 │<br>│       45692 │ Frank    │     17 │   1680 │    27336 │<br>│       56118 │ Pathrick │      7 │   1345 │     9415 │<br>│       59725 │ Lisa     │     11 │   2330 │    25630 │<br>│       74197 │ Kimberly │     16 │   4372 │    69952 │<br>│       78454 │ Bonnie   │      8 │   1771 │    14168 │<br>│       83565 │ Michaeal │      6 │   1017 │    12102 │<br>│       98607 │ Todd     │      5 │   3396 │    16980 │<br>│       99989 │ Joe      │      9 │   3573 │    32157 │<br>└─────────────┴──────────┴────────┴────────┴──────────┘</pre><p>The maximum earnings value is <strong>69952</strong>. The only employee with earnings = <strong>69952</strong> is Kimberly, so we print the maximum earnings value (<strong>69952</strong>) and a count of the number of employees who have earned <strong>$69952</strong>(which is <strong>1</strong> ) as two space-separated values.</p><p><strong>Solution:</strong></p><pre>SELECT (months*salary) as earnings , COUNT(*) FROM Employee GROUP BY earnings ORDER BY earnings DESC LIMIT 1 ;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ab6c3be0087" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL — 103 (Basics)]]></title>
            <link>https://medium.com/@ravisk1514/sql-103-basics-f6d470984619?source=rss-691f1bbb91bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6d470984619</guid>
            <category><![CDATA[hackerrank-solution]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[hackerrank]]></category>
            <category><![CDATA[sql-solution]]></category>
            <dc:creator><![CDATA[Ravi raj]]></dc:creator>
            <pubDate>Fri, 20 May 2022 04:07:07 GMT</pubDate>
            <atom:updated>2022-05-20T04:09:22.496Z</atom:updated>
            <content:encoded><![CDATA[<h3>SQL — 103 (Basics)</h3><h3>Introduction</h3><p>This series is the revision of SQL concepts. We are doing the basic questions, then intermediate, and so on.</p><h4>Previous Posts</h4><ol><li><a href="https://medium.com/@ravisk1514/sql-101-511e34f923df">SQL 101</a></li><li><a href="https://medium.com/@ravisk1514/sql-102-basics-222836417d1e">SQL 102 (Basics)</a></li></ol><p>All 4 questions use the regular expression concept. You can learn more about regular expressions <a href="https://www.geeksforgeeks.org/mysql-regular-expressions-regexp/">here</a>.</p><pre>╔═════════╦══════════════════════════════════════════════════════╗<br>║ Pattern ║                  Matching Patterns                   ║<br>╠═════════╬══════════════════════════════════════════════════════╣<br>║ ^       ║ Beginning of string                                  ║<br>║ $       ║ End of string                                        ║<br>║ .       ║ Any single character                                 ║<br>║ *       ║ Zero or more instances of the preceding element      ║<br>║ [^...]  ║ Any character not listed between the square brackets ║<br>╚═════════╩══════════════════════════════════════════════════════╝</pre><h4>Question 1</h4><p>[<a href="https://www.hackerrank.com/challenges/weather-observation-station-9/problem">Ref: Hackerrank</a>]</p><p>Query the list of CITY names from <strong>STATION</strong> that does not start with vowels. Your result cannot contain duplicates.</p><p><strong>Input Format</strong></p><p>The <strong>STATION</strong> table is described as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*nZnXRg9Ip74Tr6yD.jpg" /></figure><p>where LAT_N is the northern latitude and LONG_W is the western longitude.</p><p><strong>Solution:</strong></p><pre>SELECT DISTINCT(CITY) FROM STATION WHERE CITY NOT REGEXP &quot;^[aeiou]&quot; AND LAT_N &gt; 0 and LONG_W &gt;0;</pre><h4>Question 2</h4><p>[<a href="https://www.hackerrank.com/challenges/weather-observation-station-10/problem">Ref: Hackerrank</a>]</p><p>Query the list of CITY names from <strong>STATION</strong> that do not end with vowels. Your result cannot contain duplicates.</p><p>where LAT_N is the northern latitude and LONG_W is the western longitude.</p><p><strong><em>Note</em></strong><em>: The </em><strong><em>STATION </em></strong><em>table is the same as described in Question 1.</em></p><p><strong>Solution:</strong></p><pre>SELECT DISTINCT(CITY) FROM STATION WHERE CITY NOT REGEXP &quot;[aeiou]$&quot; AND LAT_N &gt; 0 and LONG_W &gt;0;</pre><h4>Question 3</h4><p>[<a href="https://www.hackerrank.com/challenges/weather-observation-station-11/problem">Ref: Hackerrank</a>]</p><p>Query the list of CITY names from <strong>STATION</strong> that either do not start with vowels or do not end with vowels. Your result cannot contain duplicates.</p><p>where LAT_N is the northern latitude and LONG_W is the western longitude.</p><p><strong><em>Note</em></strong><em>: The </em><strong><em>STATION </em></strong><em>table is the same as described in Question 1.</em></p><p><strong>Solution:</strong></p><pre>SELECT DISTINCT(CITY) FROM STATION WHERE CITY NOT REGEXP &quot;^[aeiou].*[aeiou]$&quot; AND LAT_N &gt; 0 and LONG_W &gt;0;</pre><h4>Question 4</h4><p>[<a href="https://www.hackerrank.com/challenges/weather-observation-station-12/problem">Ref: Hackerrank</a>]</p><p>Query the list of CITY names from <strong>STATION</strong> that do not start with vowels and do not end with vowels. Your result cannot contain duplicates.</p><p>where LAT_N is the northern latitude and LONG_W is the western longitude.</p><p><strong><em>Note</em></strong><em>: The </em><strong><em>STATION </em></strong><em>table is the same as described in Question 1.</em></p><p><strong>Solution:</strong></p><pre>SELECT DISTINCT(CITY) FROM STATION WHERE CITY REGEXP  &#39;^[^aeiou].*[^aeiou]$&#39; AND LAT_N &gt; 0 and LONG_W &gt;0;</pre><p><strong>Explanation:</strong></p><p>So, do not start with vowels mean: (<strong>^[^aeiou])</strong>, then zero or any number of characters (<strong>.*) </strong>and do not end with vowels <strong>([^aeiou]$).</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6d470984619" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL — 102 (Basics)]]></title>
            <link>https://medium.com/@ravisk1514/sql-102-basics-222836417d1e?source=rss-691f1bbb91bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/222836417d1e</guid>
            <category><![CDATA[hackerrank-solutions-sql]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Ravi raj]]></dc:creator>
            <pubDate>Thu, 19 May 2022 16:29:58 GMT</pubDate>
            <atom:updated>2022-05-19T16:29:58.877Z</atom:updated>
            <content:encoded><![CDATA[<h3>SQL — 102 (Basics)</h3><h3>Introduction</h3><p>This series is the revision of SQL concepts. We are doing the basic questions, then intermediate, and so on.</p><h4>Previous Posts</h4><ol><li><a href="https://medium.com/@ravisk1514/sql-101-511e34f923df">SQL 101</a></li></ol><h3>Question 1</h3><p>[<a href="https://www.hackerrank.com/challenges/weather-observation-station-6/problem">Ref: Hackerrank</a>]</p><p>Query the list of CITY names starting with vowels (i.e., a, e, i, o, or u) from <strong>STATION</strong>. Your result cannot contain duplicates.</p><p><strong>Input Format</strong></p><p>The <strong>STATION</strong> table is described as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*-6ndi4RfrUdKTaDS.jpg" /></figure><p>where LAT_N is the northern latitude and LONG_W is the western longitude.</p><p><strong>Solution:</strong></p><pre>SELECT DISTINCT(CITY) FROM STATION WHERE CITY REGEXP “^[aeiou]” AND LAT_N &gt; 0 and LONG_W &gt;0;</pre><p><strong>Explanation:</strong></p><ol><li>To match the start of the string, we use the Caret (^) that matches the position before the first character in the string. [<a href="https://howtodoinjava.com/java/regex/start-end-of-string/">Ref</a>]</li><li>The lines of latitude and longitude divide Earth into four hemispheres: <em>Northern</em>, <em>Southern</em>, <em>Eastern</em>, and <em>Western</em>. The United States lies in both the Northern Hemisphere and the Western Hemisphere. That’s because it lies west of the prime meridian or 0° of longitude, and north of the equator, or 0° of latitude. [<a href="https://www.gedonlineclass.net/Curric/geo3longitude_and_latitude.htm">Ref</a>]</li></ol><h3>Question 2</h3><p>[<a href="https://www.hackerrank.com/challenges/weather-observation-station-5/problem">Ref: Hackerrank</a>]</p><p>Query the two cities in <strong>STATION</strong> with the shortest and longest CITY names, as well as their respective lengths (i.e.: number of characters in the name). If there is more than one smallest or largest city, choose the one that comes first when ordered alphabetically.<br>The <strong>STATION</strong> table is described as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*hLrdBv1lHHbhUlJ7.jpg" /></figure><p>where <strong>LAT_N</strong> is the northern latitude and <strong>LONG_W</strong> is the western longitude.</p><p><strong>Sample Input</strong></p><p>For example, <strong>CITY</strong> has four entries: <strong>DEF, ABC, PQRS,</strong> and <strong>WXY</strong>.</p><p><strong>Sample Output</strong></p><pre>ABC 3<br>PQRS 4</pre><p><strong>Explanation</strong></p><p>When ordered alphabetically, the <strong>CITY</strong> names are listed as <strong>ABC, DEF, PQRS,</strong> and <strong>WXY</strong>, with lengths and. The longest name is <strong>PQRS</strong>, but there are options for the shortest named city. Choose <strong>ABC</strong>, because it comes first alphabetically.</p><p><strong>Note</strong><br>You can write two separate queries to get the desired output. It need not be a single query.</p><p><strong>Solution:</strong></p><pre>SELECT CITY, LENGTH(CITY) as CITY_LENGTH FROM STATION WHERE LAT_N &gt; 0 and LONG_W &gt;0 ORDER BY LENGTH(CITY), CITY ASC LIMIT 1;</pre><pre>SELECT CITY, LENGTH(CITY) as CITY_LENGTH FROM STATION WHERE LAT_N &gt; 0 and LONG_W &gt;0 ORDER BY LENGTH(CITY) DESC LIMIT 1;</pre><h3>Question 3</h3><p>[<a href="https://www.hackerrank.com/challenges/weather-observation-station-7/problem">Ref: Hackerrank</a>]</p><p>Query the list of CITY names ending with vowels (a, e, I, o, u) from <strong>STATION</strong>. Your result cannot contain duplicates.</p><p><strong>Input Format</strong></p><p>The <strong>STATION</strong> table is described as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*B4BUIKQwySa5ZxQH.jpg" /></figure><p>where LAT_N is the northern latitude and LONG_W is the western longitude.</p><p><strong>Solution:</strong></p><pre>SELECT DISTINCT(CITY) FROM STATION WHERE CITY REGEXP “[aeiou]$” AND LAT_N &gt; 0 and LONG_W &gt;0;</pre><p><strong>Explanation:</strong></p><ol><li>To match the end of the string, we use the Dollar ($) that matches the position right after the last character in the string. [<a href="https://howtodoinjava.com/java/regex/start-end-of-string/">Ref</a>]</li></ol><h3>Question 4</h3><p>[<a href="https://www.hackerrank.com/challenges/weather-observation-station-8/problem">Ref: Hackerrank</a>]</p><p>Query the list of CITY names from <strong>STATION</strong> which has vowels (i.e., a, e, i, o, and u) as both their first and last characters. Your result cannot contain duplicates.</p><p><strong>Input Format</strong></p><p>The <strong>STATION</strong> table is described as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*mmXndkHVCVyzCv4m.jpg" /></figure><p>where LAT_N is the northern latitude and LONG_W is the western longitude.</p><p><strong>Solution:</strong></p><pre>SELECT DISTINCT(CITY) FROM STATION WHERE CITY REGEXP “^[aeiou].*[aeiou]$” AND LAT_N &gt; 0 and LONG_W &gt;0;</pre><p><strong>Explanation:</strong></p><ol><li>Caret (^) will match the first character, (.*) means zero or more characters, and at the end Dollar ($) will match the last character.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=222836417d1e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>