<?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 Gracevalerie on Medium]]></title>
        <description><![CDATA[Stories by Gracevalerie on Medium]]></description>
        <link>https://medium.com/@gracevalerie1?source=rss-695c8867011f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*EVwCSA1LcMLVg69q.jpg</url>
            <title>Stories by Gracevalerie on Medium</title>
            <link>https://medium.com/@gracevalerie1?source=rss-695c8867011f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 11:09:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gracevalerie1/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[Working with containers and Kubernetes]]></title>
            <link>https://medium.com/@gracevalerie1/working-with-containers-and-kubernetes-b33b92d08f7b?source=rss-695c8867011f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b33b92d08f7b</guid>
            <category><![CDATA[replicaset]]></category>
            <category><![CDATA[kubernetes-cluster]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[docker-container]]></category>
            <category><![CDATA[containerization]]></category>
            <dc:creator><![CDATA[Gracevalerie]]></dc:creator>
            <pubDate>Tue, 23 Jun 2026 05:54:01 GMT</pubDate>
            <atom:updated>2026-06-23T05:54:01.076Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine you want to deploy a simple Node.js application on a server. Before it can run, you’ll need to configure the operating system, set up networking, install dependencies, and ensure it can communicate with other services. Doing this manually for every application or server quickly becomes repetitive, error‑prone, and difficult to scale.</p><p>This is exactly the challenge Kubernetes was designed to solve: it automates deployment, scaling, and management so you don’t have to reinvent the wheel each time.</p><h4>What is a container?</h4><p>A container packages everything needed to run an application including dependencies, configurations and libraries. It then isolates the packaged application from the underlying host infrastructure and makes it portable.</p><h4>What is a container image?</h4><p>The packaged container application is referred to as a <strong>container image</strong>. Images make containers light weight, portable and easily reusable across different systems.</p><p>Images consist of <strong>layers</strong> which represent a change in the filesystem, the <strong>image index </strong>that has metadata and file manifests, config file to specify how to execute the container</p><h4>Evolution of containers</h4><p>Container technology was introduced in Version 7 of Unix in 1979. The chroot command was used to change the root directory to a simulated root directory <strong><em>chroot-jail</em></strong> by isolating a process from the main filesystem.</p><p>Current Linux kernels use <strong>namespaces</strong> to isolate resources and <strong>cgroups</strong> to organize processes into hierarchical groups</p><h4>How to write a Dockerfile</h4><pre># start with the base image<br>FROM node:latest<br><br># define the working dir <br>WORKDIR /app<br><br># COPY source destination<br>COPY package*.json .<br><br># Run commands to add software to your image<br>RUN npm install<br><br># copy code to the image<br><br>COPY . .<br><br># define the process<br>CMD [&quot;node&quot;, &quot;app.js&quot;]</pre><p>To build the image, use the command docker build -t image-name -f Dockerfile</p><p>Use a container registry to distribute the images</p><pre># docker push <br># docker pull</pre><h4>Fundamentals of container orchestration</h4><p>Scaling an application from one container to possibly hundreds of thousands makes it challenging to manage the infrastructure. Container orchestration reduces the complexity by automating container management and networking.</p><p><strong>What are the benefits of container orchestration?</strong></p><ol><li>It automates scalability based on demand, ensures network availability and enforces infrastructure restrictions.</li><li>If a container fails, a container orchestration tool automatically restarts or replaces it to maintain high availability.</li><li>It improves the software delivery process by making it easier to build a reliable CI/CD pipeline.</li></ol><h3><strong>How does container orchestration work?</strong></h3><p><strong><em>Requirements.</em></strong></p><p>Pick a <strong>containerization tool</strong> such as <strong>Docker </strong>to run on every node in the cluster. The <strong>control plane</strong> uses a master node to manage the cluster and container operations while <strong>worker nodes</strong> run the actual containers.</p><p><strong><em>Configuration</em></strong></p><p>The orchestration tool reads from a yaml/ json configuration file. It then obtains the specified container image, provisions the containers and configures the required networking.</p><p><strong><em>Scheduling</em></strong></p><p>The orchestration tool schedules and deploys the application in the cluster with multiple containers.</p><p><strong><em>Management</em></strong></p><p>The orchestration tool then manages the system’s health once the clusters are deployed and containers running.</p><p><strong><em>Networking</em></strong></p><p>Containers in a microservice architecture communicate with each other through the network. Each container is given its own IP address by the network namespaces. Through service discovery, containers can find and communicate with each other dynamically without manual configuration.</p><h4>What is a service mesh?</h4><p>A service mesh is a lightweight proxy layer that handles communication between services. Service mesh proxies make up the data plane which manages the traffic policies and rules.</p><h4>Benefits of a service mesh</h4><ol><li>They automate service discovery by using a service registry to dynamically discover and keep track of all services within the mesh.</li><li>Advanced traffic control, request routing and load balancing.</li><li>Automatically divides incoming traffic between different service versions during a gradual rollout.</li><li>They provide secure communication features such as mutual TLS to enable identity verification for services.</li><li>Service meshes offer in-depth logging, monitoring and observability features to gain insights into the services health.</li></ol><h3>Kubernetes Architecture</h3><p>Kubernetes is an open-source platform for orchestrating, deploying and scaling containers. A Kubernetes cluster consists of a group of worker nodes that run containerized applications.</p><h4>Fundamental concepts</h4><p><strong>Container</strong></p><p>Application code that is packaged with its libraries, dependencies to make it deployable and runnable as an isolated application environment or microservice.</p><p><strong>Monolith vs microservices</strong></p><p>A monolithic architecture is a traditional model of deploying applications as a single unit. This often leads to duplicated logic and can be hard to manage if the application grows and needs to scale.</p><p>In a microservice architecture, business functions and features are separated into services, which can be deployed independently on separate servers.</p><p><strong>Control Plane</strong></p><p>The control plane is responsible for managing the state of a Kubernetes cluster. It is the node that bridges the communication between users and the cluster through requests. The control plane consists of the following components</p><p><strong>kube-apiserver</strong>: a RESTful client that manages data for all Kubernetes resources such as pods, services and others. It coordinates all administrative tasks in the cluster.</p><p><strong>kube-scheduler: </strong>the scheduler is responsible for assigning the most fitted worker node to a newly created pod or workload object.</p><p><strong>control managers: </strong>regulates and manages the state of the cluster using continuous control loops.</p><p><strong>etcd: </strong>persistent key-value database that records the state of the cluster.</p><figure><img alt="Kubernetes cluster architecture with cluster components" src="https://cdn-images-1.medium.com/max/1024/1*ySWgW_gzjOX1tjguoRzx7g.png" /><figcaption>Kubernetes cluster architecture</figcaption></figure><p><strong>Worker node</strong></p><p>Worker nodes are responsible for running client applications such as microservice containers. The key components of a worker node include:</p><ol><li><strong>kubelet: </strong>runs on each worker node to ensure running containers in a pod are healthy.</li><li><strong>pod:</strong> a collection of containers that can be started, stopped or rescheduled as a single unit of work.</li><li><strong>container runtime: </strong>Kubernetes cannot directly run containers, therefore requires an external runtime engine to manage the lifecycle of containers.</li><li><strong>kube-proxy:</strong> maintains all the networking rules on the node which allow communication inside and outside the cluster.</li></ol><p><strong>Kubernetes Objects</strong></p><p>These are entities that represent the state of your cluster. Objects define the desired state of a cluster. Their definitions are written in a YAM file which can be used to create the resources.</p><pre>apiVersion: apps/v1<br>kind: Pod<br>metadata:<br>  name: example-pod<br>  namespace: ...<br>spec:<br>  containers:<br>  - name: simple-container<br>    image: nginx:latest<br>    ports:<br>    - containerPort: 80</pre><p>The YAML manifest file has the following mandatory fields:</p><ul><li><em>apiVersion: </em>which version of the Api should be used</li><li><em>kind</em>: type of object to create</li><li><em>metadata:</em> uniquely identifies the object</li><li><em>spec:</em> defines the desired state for the object</li></ul><p><strong>Types of Kubernetes Objects</strong></p><p>Kubernetes object types are many which you can list using kubectl api-resources to view the available ones. kubectl explain [object-type provides for information about an object. The most common object types you will encounter include:</p><ol><li>Pods: the smallest deployable unit in Kubernetes that can host a single or multiple containers.</li><li>Deployment: manages the full lifecycle of pods through a ReplicaSet. This object ensures the declared desired state (number of replicas, pod images) is achieved.</li><li>ReplicaSet: ensures the specified number of pods defined by the replicas field are running at all times.</li><li>StatefulSet: used to manage stateful applications that require persistent data.</li><li>DaemonSet: ensures a specific pods runs across all nodes in the cluster. This can be logging, monitoring or security tools that need to run on every node.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b33b92d08f7b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build an ETL pipeline with Kafka and Cassandra]]></title>
            <link>https://medium.com/@gracevalerie1/build-an-etl-pipeline-with-kafka-and-cassandra-7b374824bc27?source=rss-695c8867011f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b374824bc27</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[etl-pipeline]]></category>
            <category><![CDATA[apache-cassandra]]></category>
            <dc:creator><![CDATA[Gracevalerie]]></dc:creator>
            <pubDate>Mon, 01 Jun 2026 17:58:07 GMT</pubDate>
            <atom:updated>2026-06-01T17:58:07.251Z</atom:updated>
            <content:encoded><![CDATA[<p>ETL pipelines are the backbone of modern analytics for data driven organizations. This article explores how to design and implement an ETL pipeline using <strong>Apache Kafka</strong> for real time streaming, and <strong>Cassandra</strong> as the NoSQL database optimized for fast writes.</p><p>We’ll walk through the concepts, architecture, and practical steps to connect Kafka producers and consumers with Cassandra tables, showing how to build a real time weather monitoring pipeline.</p><h4>Benefits of using Kafka + Cassandra</h4><ul><li>Kafka’s streaming capabilities enable custom applications to store and process big data in milliseconds.</li><li>Kafka’s distributed architecture can scale horizontally by adding more brokers and partitions as data volumes grow. This allows them to handle more traffic with low latency.</li><li>Kafka ensures durability by using a <strong><em>leader</em></strong> broker to handle read and write requests to a partition, while <strong><em>follower</em></strong> brokers replicate the data.</li><li>Cassandra is also easily scalable by adding new nodes to the cluster, which allows it to handle high traffic without performance degradation.</li><li>Cassandra is highly optimized for fast writes making it suitable for applications that continuously generate large streams of data.</li></ul><p>Kafka combined with Cassandra allow you to ingest data in real time and persist them for live analytics or any other use case.</p><h4><strong>Architecture Overview</strong></h4><p>For this project we will use open weather Api to stream current weather updates for several cities around the world.</p><ol><li><strong>ETL pipeline (Extraction and Transformation)</strong></li></ol><p>In this architecture, data is extracted from the open-weather API, then basic transformation is done.</p><p>2. <strong>Kafka producers</strong></p><p>A producer is the client application that writes events to Kafka partitions.</p><p>3. <strong>Kafka Consumer</strong></p><p>A consumer is the application that reads data from Kafka topics by issuing fetch requests to brokers and using offsets to track its position.</p><p>4. <strong>Kafka Broker</strong></p><p>A broker is the server process which stores messages from producers across partitions and distributes them to consumers.</p><p>5. <strong>Cassandra Cluster</strong></p><p>This is the storage layer in the consumer group that stores transformed data in a database table that is query able.</p><figure><img alt="Simple Kafka Architecure diagram" src="https://cdn-images-1.medium.com/max/1024/1*v9y31YkmbhqWP2C8wrMDoQ.png" /><figcaption>Single node Kafka architecture</figcaption></figure><p>In a typical architecture, more than one broker is used to easily replicate data. This is done by utilizing the leader follower architecture. The leader partition reads and writes data while the follower duplicates that data for backup and recovery.</p><h4>Local Environment Setup</h4><p>In your project folder, create a python virtual environment to isolate project dependencies and packages.</p><pre>python3 -m venv weather_venv<br># activate virtual environment<br>source weather_venv/bin/activate</pre><p>Install required dependencies</p><pre>pip install requests pandas cassandra-driver kafka-python pycountry dotenv<br># generate requirements.txt file<br><br>pip freeze &gt; requirements.txt</pre><p>Setup the Kafka producer in a python file e.g. producer.py</p><pre># import packages<br>from kafka import KafkaProducer<br>import json<br>import requests<br>import pandas as pd<br>import pycountry<br>import time<br>import os<br>from dotenv import load_dotenv<br><br># initialize the kafka producer<br>weather_producer = KafkaProducer(<br>  bootstrap_servers=&#39;broker:9092&#39;,<br>  api_version=(2, 3, 1),<br>  value_serializer=lambda v: json.dumps(v).encode(&#39;utf-8&#39;)<br>)<br><br># create the kafka topic<br>weather_topic = &#39;current_weather&#39;<br><br># import the open-weather api key<br>load_dotenv()<br>API_KEY = os.getenv(&quot;WEATHER_API_KEY&quot;)</pre><p>Extract data from the API.</p><pre>def extract_weather(CITY_NAME):<br>  url = f&quot;https://api.openweathermap.org/data/2.5/weather?q={CITY_NAME}&amp;appid={API_KEY}&quot;<br>  response = requests.get(url)<br><br>  return response.json()</pre><p>Next, we’ll do some light transformation.</p><pre>def transform_weather(weather_data):<br>  weather_dict = {<br>        &quot;longitude&quot;: weather_data.get(&quot;coord&quot;, {}).get(&quot;lon&quot;),<br>        &quot;latitude&quot;: weather_data.get(&quot;coord&quot;, {}).get(&quot;lat&quot;),<br>        &quot;condition&quot;: weather_data.get(&quot;weather&quot;, [])[0].get(&quot;main&quot;, &quot;&quot;),<br>        &quot;description&quot;: weather_data.get(&quot;weather&quot;, [])[0].get(&quot;description&quot;, &quot;&quot;),<br>        &quot;temperature_kelvin&quot;: weather_data.get(&quot;main&quot;, {}).get(&quot;temp&quot;, 0),<br>        &quot;cloud_coverage_pct&quot;: weather_data.get(&quot;clouds&quot;, {}).get(&quot;all&quot;, 0),<br>        &quot;country_code&quot;: weather_data.get(&quot;sys&quot;, {}).get(&quot;country&quot;, &quot;&quot;),<br>        &quot;city&quot;: weather_data.get(&quot;name&quot;, &quot;&quot;),<br>    }<br><br>  # convert this data to a pandas Series<br>  weather_pd = pd.Series(weather_dict)<br>  <br>  # extract the country name from country code<br>  code = weather_pd[&#39;country_code&#39;]<br>  country_name = pycountry.countries.get(alpha_2=code)<br>  weather_pd[&#39;country_code&#39;] = country_name.name<br><br>  # rename the country code column<br>  weather_pd = weather_pd.rename({&quot;country_code&quot;, &quot;country&quot;})<br>  <br>  # convert the series to json<br>  return weather_pd.to_json(orient=&#39;index&#39;)</pre><p>Write data to the producer</p><pre>def produced:<br>  cities = [...add city names here...]<br>  while True:<br>    for city in cities:<br>      weather_data = extract_weather(city)<br>      current_weather = transform_weather(weather_data)<br>      # write to producer (weather_producer.send(kafka_topic_name, data)<br>      weather-producer.send(weather_topic, current_weather)<br>      <br>      time.sleep(10)</pre><h4>Sending data to the consumer</h4><p>In the consumer.py file, we will load data in the consumer then insert it to the Cassandra database.</p><p>First, we import the necessary dependencies</p><pre>from kafka import KafkaConsumer <br>from cassandra.cluster import Cluster # install cassandra-driver<br>import json<br>import uuid</pre><p>Create a cluster (the database instance operation on multiple nodes) and a new session (a connection to the database cluster).</p><pre># Cluster(contact_points,port,executor_threads)<br>cluster = Cluster([&#39;cassdb&#39;], port=9042)<br>session = cluster.connect()</pre><p>A keyspace is a namespace that defines how data is replicated on nodes. We can create a keyspace with the query</p><pre>session.execute(&quot;&quot;&quot;<br>CREATE KEYSPACE IF NOT EXISTS current_climate WITH \<br>replication = {<br>&#39;class&#39;: &#39;SimpleStrategy&#39;,<br>&#39;replication_factor&#39;: 3<br>}<br>&quot;&quot;&quot;<br>)<br>      <br><br># set the keyspace<br>session.set_keyspace(&#39;current_climate&#39;)</pre><p>Create a Cassandra table for storage</p><pre>session.execute(&quot;&quot;&quot;CREATE TABLE IF NOT EXISTS current_climate.climate_data(<br>    weather_id uuid PRIMARY KEY,<br>    longitude DOUBLE,<br>    latitude DOUBLE,<br>    status TEXT,<br>    description TEXT,<br>    city TEXT,<br>    country TEXT,<br>    temperature_kelvin DOUBLE,<br>    cloud_coverage_pct INT<br>) WITH comment=&#39;Latest Weather status&#39;&quot;&quot;&quot;)<br></pre><p>Prepare an insert statement</p><pre>insert_stmt = session.prepare(&quot;&quot;&quot;<br>                INSERT INTO current_climate.climate_data(<br>                    weather_id, longitude, latitude, status, description, country, city, temperature_kelvin, cloud_coverage_pct<br>                )<br>                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)<br>                &quot;&quot;&quot;)</pre><p>Write the consumer function</p><pre>def consumed():<br><br>    consumer = KafkaConsumer(<br>        &#39;current_weather&#39;,<br>        bootstrap_servers=&#39;broker:9092&#39;,<br>        enable_auto_commit=True,<br>        auto_offset_reset=&#39;earliest&#39;,<br>        value_deserializer=lambda m: json.loads(m.decode(&#39;utf-8&#39;))<br>    )<br><br>    try:<br><br>        for message in consumer:<br>            data = json.loads(message.value)<br>            <br>            print(f&quot;Updated weather in topic: {message.topic}&quot;)<br>           <br>            return session.execute(insert_stmt,<br>                        (uuid.uuid1(),<br>                        data.get(&#39;longitude&#39;), <br>                        data.get(&#39;latitude&#39;),<br>                        data.get(&#39;status&#39;),<br>                        data.get(&#39;description&#39;),<br>                        data.get(&#39;country&#39;),<br>                        data.get(&#39;city&#39;), <br>                        data.get(&#39;temperature_kelvin&#39;),<br>                        data.get(&#39;cloud_coverage_pct&#39;)<br>                        )<br>                        )<br>    except Exception as e:<br>        print(f&quot;An error occured: {e}&quot;)</pre><p>Create the Dockerfile</p><pre>FROM python:3.11-slim # base image<br><br># set working directory<br>WORKDIR /app <br><br>COPY requirements.txt ./<br><br>RUN pip install --no-cache-dir -r requirements.txt<br><br># copy code to the image<br>COPY . .<br><br>CMD [&quot;python&quot;, &quot;-u&quot;, &quot;main.py&quot;]</pre><h4><strong>Setting Up Kafka</strong></h4><p>Kafka is setup by installing it locally on your server or by running the Kafka image. In this case we will setup a Kafka broker container in a docker compose file.</p><pre>services:<br>  broker:<br>    image: apache/kafka:latest<br>    container_name: broker<br>    ports:<br>      - 9092:9092 # default kafka port<br>    </pre><h4>Kafka broker environment</h4><p>The broker environment requires the following essential configurations</p><p><strong>Node ID</strong></p><p>The node id is essential when running in KRaft mode. It is a unique identifier for the current node in the cluster. We can add the node id to the broker service environment as follows</p><pre>environment:<br>  KAFKA_NODE_ID: 1</pre><p><strong>Process Roles</strong></p><p>Process roles define the roles that the current process plays which can be broker, controller or both. The broker handles client traffic while the controller manages cluster metadata. We can run both on a single node in this single node architecture.</p><pre>environment:<br>  KAFKA_NODE_ID: 1<br>  KAFKA_PROCESS_ROLES: broker, controller</pre><p><strong>Networking configuration</strong></p><p><strong><em>Kafka listeners</em></strong></p><p>The listener defines which network interfaces and ports the process will bind to and listen on. Specifying the hostname as 0.0.0.0 will bind to all interfaces inside the container.</p><pre>environment:<br>  KAFKA_LISTENERS: PLAINTEXT://0.0.0.0:9092, CONTROLLER://0.0.0.0:9093<br>  # port 9092 =&gt; client traffic (consumers/producers) under name PLAINTEXT<br>  # port 9093 =&gt; controller communication for internal metadata under name CONTROLLER</pre><p><strong><em>Advertised Listeners</em></strong></p><p>This configuration specifies the address that the broker will share with the client and other brokers. If an external client such as a python application wants to connect, this is the address they will use.</p><pre>environment:<br>  KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://broker:9092</pre><p><strong><em>Why is the advertised listener set to </em></strong><strong><em>broker and not </em></strong><strong><em>localhost?</em></strong></p><p>In a docker container, localhost usually refers to the container itself, and not your host machine. Since our producer and consumers will likely be running in another container, if we use for example</p><pre>KafkaProducer(<br>  bootstrap-servers=localhost:9092,<br>...<br>)❌</pre><p>The producer will try to connect to its own loopback IP. This will fail with the error NoBrokersAvailable.</p><p>Instead, we will use <strong>broker, </strong>the name of our service, so that Docker’s internal DNS automatically resolves the correct container IP address and the client can connect successfully.</p><pre>KafkaProducer(<br>  bootstrap-servers=broker:9092,<br>...<br>)✅</pre><p><strong><em>Controller listener names</em></strong></p><p>the name of the of the listener used by the controller. used to communicate with controller quorum</p><pre>environment:<br>  KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER</pre><p><strong><em>Listener Security protocol</em></strong></p><p>This is essential when the listener&#39;s name is not a security protocol. The listener&#39;s name is mapped to a security protocol.</p><pre>environment:<br>  KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT<br>  # using PLAINTEXT means no (ssl/tls) therefore both listeners are using<br>  #  unencrypted with no auth PLAINTEXTcommunication</pre><p><strong><em>Controller Quorum Voters</em></strong></p><p>Raft uses a consensus algorithm where quorum voters are a set of selected controllers. They play an important part in leader selection.</p><pre>environment: <br>  KAFKA_CONTROLLER_QUORUM_VOTERS:1@localhost:9093<br>                    # format-&gt; {node_id}@host:port</pre><p><strong>Full Configuration</strong></p><pre>services:<br>  broker:<br>    image: apache/kafka:latest<br>    container_name: broker<br>    ports:<br>      - 9092:9092<br>    environment:<br>      KAFKA_NODE_ID: 1<br>      KAFKA_PROCESS_ROLES: broker,controller<br>      KAFKA_LISTENERS: PLAINTEXT://0.0.0.0:9092,CONTROLLER://0.0.0.0:9093<br>      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://broker:9092<br>      KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER<br>      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT<br>      KAFKA_CONTROLLER_QUORUM_VOTERS: 1@localhost:9093<br>      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1<br>      KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1<br>      KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1<br>      KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0<br>      KAFKA_NUM_PARTITIONS: 3</pre><p>Create two more services for Cassandra and the image created by the Docker file.</p><pre># service<br>cassdb:<br>    image: cassandra:latest<br>    container_name: cass_container<br>    environment:<br>      - CASSANDRA_CLUSTER_NAME=weather_cluster<br>    ports:<br>     - &quot;7000:7000&quot; # storage port<br>     - &quot;9042:9042&quot;<br>    volumes:<br>      - cassandra-node:/var/lib/cassandra:rw<br>    restart: on-failure<br>    healthcheck:<br>      test: [&quot;CMD-SHELL&quot;, &quot;nodetool status&quot;]<br>      interval: 2m<br>      timeout: 20s<br>      retries: 5<br>      start_period: 2m<br># service  <br>etl:<br>    container_name: weather_etl<br>    build: .<br>    depends_on:<br>      cassdb:<br>        condition: service_healthy<br>    environment:<br>      - CASSANDRA_CLUSTER_NAME=weather_cluster<br>    develop:<br>      watch:<br>        - path: .<br>          include: &quot;*.py&quot;<br>          action: rebuild<br><br>volumes:<br>  cassandra-node: # declare the volume<br>    driver: local<br><br></pre><h4>Running the application</h4><p>Since we setup Kafka, Cassandra and our application server using docker containers, we can use docker compose up to build the application.</p><p>Run docker ps to view running containers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LSdn9lMyLLkDJ_FcdpZAyQ.png" /><figcaption>running containers</figcaption></figure><p>We can then open a bash shell in the broker container.</p><pre>docker exec --workdir /opt/kafka/bin -it broker sh</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g1uPZm7xDLwEv81lYSLCUg.png" /><figcaption>kafka container shell</figcaption></figure><p>Now we can read the events in the current_weather topic which we created in the producer.py file</p><pre>./kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic current_weather --from-beginning </pre><p>This outputs the events sent to our consumer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SgWx-Fx3doQ6zU-dGGOq6Q.png" /><figcaption>Kafka consumer events</figcaption></figure><p>Next, we can view the data sent to the Cassandra database</p><pre>docker exec -it cass_container cqlsh</pre><p>This command gives you access to the Cassandra shell inside the container</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fF_F6M4jJne9yYHfum0VVg.png" /><figcaption>Cassandra shell</figcaption></figure><p>The shell connects to the weather_cluster since we declared it in the container environment.</p><pre>environment:<br>  - CASSANDRA_CLUSTER_NAME=weather_cluster</pre><p>We can change the Keyspace to the one we created in the consumer file.</p><pre>USE current_climate;</pre><p>To view data in the table, run:</p><pre>SELECT * FROM climate_data;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_5_ZxEssRDYncK85gvutGw.png" /><figcaption>Cassandra table</figcaption></figure><p>To stop and remove the containers including volumes and images, run</p><pre>docker compose down --rmi all -v</pre><h4>Conclusion</h4><p>Data-driven applications require speed and reliability. By combining Kafka’s real-time streaming capabilities with Cassandra’s scalable storage, we built a resilient ETL data pipeline. This architecture ensures data flows continuously from producers to consumers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b374824bc27" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Write your first Airflow DAG]]></title>
            <link>https://medium.com/@gracevalerie1/write-your-first-airflow-dag-d2a1049be940?source=rss-695c8867011f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2a1049be940</guid>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[etl-pipeline]]></category>
            <category><![CDATA[airflow-dag]]></category>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[apache-airflow]]></category>
            <dc:creator><![CDATA[Gracevalerie]]></dc:creator>
            <pubDate>Sun, 10 May 2026 15:24:12 GMT</pubDate>
            <atom:updated>2026-05-10T15:24:12.146Z</atom:updated>
            <content:encoded><![CDATA[<p>Orchestrating data pipelines can quickly become complex as the pipeline needs grow. This is where <strong>Apache Airflow</strong> shines. It is a python-based open-source platform for scheduling and monitoring workflows. Airflow uses <strong>DAGS (Directed Acyclic Graphs)</strong> to define workflows as tasks and dependencies.</p><p>In this article, we’ll walk step by step through creating your very first DAG, explain the essential components, and show you how to run it in Airflow’s UI. By the end, you’ll have a working pipeline and the confidence to start building more complex workflows.</p><h4>How to setup your environment</h4><p><strong>Prerequisites</strong></p><ol><li>Install at least python version 3. 7</li></ol><p>2. For this project we will use airflow version 3.2.0</p><p><strong>Airflow Setup</strong></p><ol><li>Create a directory for airflow then setup python virtual environment.</li></ol><pre>mkdir airflow<br>cd airflow<br>python -m venv airflow_env<br>source airflow_env/bin/activate</pre><p>2.Use pip to install airflow</p><pre>AIRFLOW_VERSION=3.2.1<br><br>PYTHON_VERSION=&quot;$(python -c &#39;import sys; print(f&quot;{sys.version_info.major}.{sys.version_info.minor}&quot;)&#39;)&quot;<br><br>CONSTRAINT_URL=&quot;https://raw.githubusercontent.com/apache/airflow/constraints-${AIRFLOW_VERSION}/constraints-${PYTHON_VERSION}.txt&quot;<br><br>pip install &quot;apache-airflow==${AIRFLOW_VERSION}&quot; --constraint &quot;${CONSTRAINT_URL}&quot;</pre><p>3. Start the webserver and the scheduler</p><pre>airflow standalone</pre><p>4. At this point you should be able to access the Airflow UI at localhost:8080.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*XBaMUUeX3GDSXLgSzHbH7g.png" /><figcaption>Airflow login</figcaption></figure><p>5. Modify the configuration file</p><pre>nano airflow.cfg<br># OR<br>vi airflow.cfg</pre><p>Our goal is to modify the folder in which our DAGS will live in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QdbrdwXEQte7LjJNROW6Sw.png" /><figcaption>changing the DAGS folder</figcaption></figure><p><strong>Setup the project</strong></p><ol><li>Create a new separate directory where our DAG workflows will live.</li></ol><pre>mkdir workflows<br>cd workflows</pre><p>2. Inside the workflows folder, create the DAG file</p><pre>touch simple_dag.py</pre><p><strong>Structure of the DAG</strong></p><p>A simple DAG is made up of tasks which are chained as dependencies. It can also contain x-comms, assets, operators, schedule</p><p>We start by importing the necessary dependencies.</p><pre>from airflow.sdk import DAG<br>form datetime import datetime, timedelta<br>from airflow.providers.standard.operators import BashOperator, PythonOperator</pre><p>We then set default arguments for tasks within a DAG. The arguments are passed on to each operator defines and can be overridden by tasks when initializing the operator.</p><pre>default_args = {<br>    &quot;owner&quot;: &quot;owner_name&quot;,<br>    &quot;start_date&quot;: datetime(2025, 1, 1),<br>    &quot;retries&quot;: no_of_retries,<br>    &quot;retry_delay&quot;: timedelta(minutes=20),<br>    &quot;email_on_failure&quot;: True,<br>}</pre><p>Create the DAG object</p><pre>with DAG(  <br>    &quot;dag-example&quot;,<br>    default_args,<br>    description=&quot;Simple DAG example&quot;,<br>    schedule=timedelta(minutes=15),<br>    start_date=datetime(2026,1,1),<br>    catchup=False<br>) as dag:</pre><p>Create tasks by instantiating operators</p><pre>task1 = BashOperator(<br>  task_id=&quot;example_bash_task&quot;,<br>  bash_command=&quot;echo &#39;first task&#39;&quot;,<br>  retries=3<br>)<br>  </pre><p>We can create another task using the python operator</p><pre># This requires an existing python function that can be called by the operator<br>def hello_world():<br>  return &quot;This is the second task&quot;<br><br># Instantiating the python operator<br>task2 = PythonOperator(<br>  task_id=&quot;example_python_task&quot;,<br>  python_callable= hello_world<br>)</pre><p><strong>Putting it all together</strong></p><pre>from airflow.sdk import DAG<br>form datetime import datetime, timedelta<br>from airflow.providers.standard.operators import BashOperator, PythonOperator<br><br>default_args = {<br>    &quot;owner&quot;: &quot;owner_name&quot;,<br>    &quot;start_date&quot;: datetime(2025, 1, 1),<br>    &quot;retries&quot;: no_of_retries,<br>    &quot;retry_delay&quot;: timedelta(minutes=20),<br>    &quot;email_on_failure&quot;: True,<br>}<br>with DAG(  <br>    &quot;dag-example&quot;,<br>    default_args,<br>    description=&quot;Simple DAG example&quot;,<br>    schedule=timedelta(minutes=15),<br>    start_date=datetime(2026,1,1),<br>    catchup=False<br>) as dag:<br>    task1 = BashOperator(<br>      task_id=&quot;example_bash_task&quot;,<br>      bash_command=&quot;echo &#39;first task&#39;&quot;,<br>      retries=3<br>  )<br>    task2 = PythonOperator(<br>      task_id=&quot;example_python_task&quot;,<br>      python_callable= hello_world<br>)<br><br># chain the tasks dependencies<br><br>task1 &gt;&gt; task2</pre><p><strong>Conclusion</strong></p><p>You’ve just written your first DAG in Airflow. This simple pipeline demonstrates how to define, schedule, and execute tasks. From here, you can expand into real‑world workflows and build ETL jobs, machine learning pipelines, or automated reporting.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2a1049be940" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Core Differences Between OLTP and OLAP systems]]></title>
            <link>https://medium.com/@gracevalerie1/the-core-differences-between-oltp-and-olap-systems-56488199d279?source=rss-695c8867011f------2</link>
            <guid isPermaLink="false">https://medium.com/p/56488199d279</guid>
            <category><![CDATA[olap]]></category>
            <category><![CDATA[oltp-vs-olap]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[oltp]]></category>
            <category><![CDATA[normalization]]></category>
            <dc:creator><![CDATA[Gracevalerie]]></dc:creator>
            <pubDate>Fri, 08 May 2026 14:27:29 GMT</pubDate>
            <atom:updated>2026-05-08T14:27:29.220Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>OLTP (Online Transaction Processing)</strong> and <strong>OLAP (Online Analytical Processing) </strong>systems serve two distinct purposes in data management. OLTP systems are designed to manage and process large volumes of business transaction records as they occur. On the other hand, OLAP systems are optimized for analyzing large datasets and extracting business intelligence from data.</p><p>This article is for anyone building a modern data-driven application. Choosing between OLAP and OLTP will directly impact performance, scalability and the efficiency and accuracy of business insights.</p><h4><strong>The contrast between OLAP and OLTP queries</strong></h4><p>Suppose you have the following queries running against the same database orders table.</p><pre>INSERT into orders(user_id, product_id, amount) VALUES(23, 10, 246.0);</pre><p>The query above is fast and precise because only one row record will be affected. This use case is perfect for OLTP since large numbers of transactions can be processed individually.</p><p>With the following query</p><pre>SELECT store_id, SUM(amount) FROM orders WHERE year = 2025 GROUP BY store_id;</pre><p>Millions of rows can be scanned then data is aggregated across dimensions. Such a query on an OLTP database would be painfully slow and resource intensive, which may hinder transactional processes. It can however thrive in an OLAP system, which is optimized for large-scale multi-dimensional analysis.</p><h4>Characteristics of OLTP systems</h4><ol><li><strong>ACID compliance:</strong> They rely on relational databases with enforce ACID properties.</li><li><strong>High concurrency control:</strong> ensures multiple transactions from multiple users can occur at the same time, following the right order without causing data anomalies.</li><li><strong>High throughput: </strong>they can handle a large number of concurrent transactions fast and efficiently.</li><li><strong>High availability: </strong>Due to how frequent inserts, updates and deletes occur, OLTP systems utilize backups to prevent downtimes.</li></ol><h4><strong>Real-world use case examples</strong></h4><p>OLTP systems are mostly chosen when there is need to efficiently process transactions and make avail them to client applications immediately. The following are examples where this system appears in real business applications.</p><ul><li><strong>Banking transfers: </strong>banking institutions rely on OLTP systems to process transactions in real-time such as deposits, withdrawals, account balance checks, and transfers.</li><li><strong>E-commerce checkouts</strong>: a customer places an order, the inventory is checked and updated, payment is processed, order receipt is generated and order details inserted into the database. This is recorded as a single transaction by the database within milliseconds and other similar transactions can take place concurrently.</li><li><strong>Booking systems: </strong>whether for hotels, flights, or ridesharing, all operate on the same OLTP principles. When a user initiates a booking, the system checks availability, captures payment details, stores user information, and makes a reservation by updating the database so the resource cannot be claimed by others. These operations require low latency and must be completed within milliseconds to avoid conflicts.</li></ul><h4>Characteristics of OLAP Systems</h4><ol><li><strong>Read-heavy workloads:</strong> OLAP databases are optimized to handle complex queries and aggregations.</li><li><strong>Fewer concurrent users: </strong>Typical users of an OLAP system include Data analysts, engineers, data scientists, BI analysts.</li><li><strong>Large dataset queries:</strong> a single query can quickly scan millions to billions of rows without consuming a lot of resources.</li><li><strong>Batch-oriented updates</strong>: OLAP systems mostly deal with historical data since data is uploaded in batches periodically and not in real time.</li></ol><h4>Real world use case examples</h4><p>OLAP systems are relied upon to deliver real-time insights that drive data-driven decision making. It plays a pivotal role in driving business success across various industries.</p><ul><li><strong>Financial analysis and reporting:</strong> the ability to integrate data from different datasets enables access to key information that drive financial metrics.</li><li><strong>Business intelligence dashboards:</strong> an OLAP database paired with a powerful visualization tool can help track KPIs and performance metrics.</li><li><strong>Customer segmentation:</strong> OLAP systems makes it easier to group customers by demographic, behavior or purchase history which can help drive targeted marketing campaigns.</li><li><strong>Trend analysis</strong>: historical data in the OLAP system can be analyzed to understand past performance, identify key trends and predict future outcomes.</li></ul><h4>Key Differences Between OLTP and OLAP</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*rtdv54sVq3sPj5emNjU8-g.png" /><figcaption>Comparison between OLAP and OLTP databases</figcaption></figure><h4><strong>Final Thoughts</strong></h4><p>Understanding the difference between OLAP and OLTP informs how you design schemas, choose infrastructure and select the right tools that fit your data architecture. Both systems play a unique role. OLTP ensures transactions are captured with speed, accuracy and reliability, while OLAP transforms those transactions into business insights.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56488199d279" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ETL vs ELT: Understanding the Tradeoffs]]></title>
            <link>https://medium.com/@gracevalerie1/etl-vs-elt-understanding-the-tradeoffs-f502f2714a84?source=rss-695c8867011f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f502f2714a84</guid>
            <category><![CDATA[data-transformation]]></category>
            <category><![CDATA[etl-tool]]></category>
            <category><![CDATA[etl-pipeline]]></category>
            <category><![CDATA[data-engineer]]></category>
            <category><![CDATA[data-extraction]]></category>
            <dc:creator><![CDATA[Gracevalerie]]></dc:creator>
            <pubDate>Wed, 15 Apr 2026 21:55:34 GMT</pubDate>
            <atom:updated>2026-04-15T21:55:34.712Z</atom:updated>
            <content:encoded><![CDATA[<p>Working with data requires a reliable process for moving the data from the source system to the target. Whether data is used for analysis or to train a machine learning model, having a reliable pipeline will help create quality datasets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e4x8xM_6zonbHV8QWbDYcQ.png" /></figure><p>ETL and ELT are two common approaches for building a data pipeline. The choice between these two methodologies depends on compliance needs, speed and other infrastructure needs.</p><h4>What is ETL?</h4><p>ETL pipelines are the legacy standard for building pipelines. They consist of the following three steps:</p><ol><li>Extraction — collecting raw data from various sources such as APIS, sensors, databases, flat files.</li><li>Transformation — formatting data to meet the target requirements by cleaning data, masking sensitive parts, ensuring data quality.</li><li>Load — storing data in the target system which could be a data warehouse or a database.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*ugl3sh1NOrHO3qKyoD4W2g.png" /><figcaption>ETL Workflow</figcaption></figure><h4>What is ELT?</h4><p>ELT pipelines load raw data into a data warehouse before transforming it. Transformation occurs in the target data store using the store’s compute resources.</p><h4>Key Differences between ETL and ELT</h4><p>The choice between ETL and ELT relies on the infrastructure and data needs and the core business. Understanding their differences helps in deciding which one fits your needs.</p><p><strong>Data Transformation</strong></p><p>The fundamental difference between these two pipelines is the order of operations.</p><p>In ETL, transformation happens in the staging phase using a separate transformation engine before loading to destination. While in ELT, data is loaded to the warehouse where transformation occurs.</p><p><strong>Data Compatibility</strong></p><p>ETL is more suitable for structured data with rows and columns. ELT can easily handle unstructured, semi structured and structured data.</p><p><strong>Security</strong></p><p>Sensitive data in ETL and ELT are handled differently. In ETL transformation phase, sensitive data can be masked, removed or anonymized before it is stored in the warehouse. This structure makes it easier to enforce compliance requirements.</p><p>In ELT, raw data with PII or sensitive information is likely to be stored in the warehouse. In this case, additional security measures such as access control and least privilege rules are required to keep data safe from unauthorized access.</p><p><strong>Speed and Costs</strong></p><p>Transformation in ETL slows down the pipeline as data size increases while transformation in ELT happens in parallel as data is loaded. This makes ELT faster and suitable for near real-time transformations.</p><p>ELT pipelines are more cost efficient since they do not need a separate infrastructure for transformations.</p><p><strong>Volume</strong></p><p>ETL pipelines are more suitable for smaller datasets since they are easier to transform while ELT pipelines fit larger datasets since they may require frequent transformations.</p><h4>When to choose ETL</h4><ol><li>Adhering to strict regulatory and compliance requirements before load</li><li>Ideal for complex business rules which require specialized transformations.</li></ol><h4>Choose ELT when</h4><ol><li>The storage destination is a cloud warehouse which is optimized for compute-heavy transformations.</li><li>You need to preserve raw data for future analysis or training machine learning models.</li><li>You are working with large amounts of streaming data which require elastic scalability.</li></ol><h4>Tools used in ETL and ELT</h4><p>At every stage of the data integration process, there are various tools which make the workflow easier.</p><p><strong><em>Data Warehouse</em></strong></p><p>SQL is used to perform data transformations in the warehouse. Modern data warehouses have additional capabilities like partitioning, incremental logic and materialization.</p><p><strong><em>Data Lakes</em></strong></p><p>Data lakes are cost efficient for storing large amounts of data but lack computing resources for transformations.</p><p><strong><em>Data Lakehouses</em></strong></p><p>They combine aspects of both data lakes and data warehouses for greater flexibility and less cost. Here data can be transformed in PySpark or Spark SQL using Apache Spark.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*4W8A2RLA2mUCEHLxVhxTpg.png" /><figcaption>ETL / ELT Tools</figcaption></figure><h4>Conclusion</h4><p>Choosing between ETL and ELT requires careful consideration for your architectural and business needs. Both approaches solve data integration needs differently. This article outlines their use cases, differences and the tools behind ETL and ELT pipelines.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f502f2714a84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Arrays and Linked Lists Data Structures in Python]]></title>
            <link>https://medium.com/@gracevalerie1/arrays-and-linked-lists-data-structures-in-python-6145cc13604e?source=rss-695c8867011f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6145cc13604e</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[arrays-in-python]]></category>
            <category><![CDATA[python-data-structures]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[linked-lists]]></category>
            <dc:creator><![CDATA[Gracevalerie]]></dc:creator>
            <pubDate>Fri, 03 Apr 2026 14:54:59 GMT</pubDate>
            <atom:updated>2026-04-03T14:54:59.081Z</atom:updated>
            <content:encoded><![CDATA[<p>Data structures and algorithms are the foundation for writing efficient programs and building optimized systems. This article focuses on arrays and linked lists in python, but the concepts cut across all languages.</p><h4>Arrays</h4><p>Arrays in python store a collection of items in sequential memory addresses. They are different from lists because all the elements in an array must be of the same data type. Arrays manage memory more efficiently and use less space compared to lists.</p><pre># list<br>x = [10, &quot;Alice&quot;, 23, True] <br><br># array<br># 1. Import the array module<br>import array as ar<br><br># 2. Create the array<br>var_name = ar.array(typecode, [elements...]) #syntax<br><br># example<br>x = ar.array(&#39;i&#39;,[1,2,3,4,6])<br><br>print(x)<br></pre><p>Python arrays contain the following methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3cjifyuW5GbznHp_sTPzEQ.png" /><figcaption>Python array methods</figcaption></figure><pre>import array as arr<br><br>x = arr.array(&#39;i&#39;, [10, 15, 20, 25])<br><br># acessing items in array using their index<br>print(x[0]) # returns 10<br>print(x[3]) # returns 25<br><br># returning the index of the first occurence of specified element<br>x.index(25) # outputs 3 ~ because the element 25 first occurs at position index 3</pre><p>We can add new elements to the end of the array using the append method or use insert to insert an element into array at a specific index.</p><pre># add element to end of array<br>x.append(30)<br><br># add element before the index position<br>x.insert(1, 11)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gTh22tDdFcVDOH54gc-Dtw.png" /><figcaption>Add elements to python array</figcaption></figure><p>Use count to count the number of occurrences of a particular element.</p><pre># syntax<br>var_name.count(element)<br># example<br>x.count(25)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*3pbidOQ8sOqEMZAvH_szaQ.png" /><figcaption>Using count() in arrays python</figcaption></figure><p>To delete items from the array, use clear to delete all items, pop to delete an item at specific index and remove to delete the first occurrence of the specified element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*vMP-NjGVL6_x78jHP6m7mA.png" /><figcaption>Deleting elements in array</figcaption></figure><h4>Linked Lists</h4><p>Linked lists do not store data in contiguous locations — meaning data is stored at random locations in memory. Because of this they use a tag instead of indexes to refer to the next node in the sequence.</p><p>Individual elements are known as nodes, and they are connected to each other using links.</p><p><strong>How to create a linked list</strong></p><ol><li>Create a node class to store the node value and a reference to the next node.</li></ol><pre><br>class Node:<br># head represents the first element in the linked list<br>  def __init__(self, value):<br>    self.value = value<br>    self.next = None # the next node reference<br></pre><p>2. Create a second class where we can insert or remove nodes from.</p><pre>class Linked:<br>  def __init__(self, head=None): # empty linked list<br>    self.head = head<br></pre><p>3. Add a method to Linked class whose function is to insert new nodes</p><pre>class Linked:<br>    def __init__(self, head=None):<br>        self.head = head<br><br>    #insert new elements at the beginning of the linked list<br>    def insert_node(self, value):<br>        new_node = Node(value)<br>        new_node.next = self.head<br>        self.head = new_node</pre><p>4. Add a method to insert elements at the end of the linked list</p><pre>def insert_node_end(self, value):<br>    new_node = Node(value)<br>    if self.head is None:<br>        self.head = new_node<br>    else:<br>        current = self.head<br>        while current.next:<br>            current = current.next<br>            print(current.value, end=&quot; -&gt; &quot;)<br>        current.next = new_node</pre><p>5. Print the content of the linked list</p><pre>def print_list(self):<br>        current = self.head <br>        while current:<br>            print(current.value, end=&quot; -&gt; &quot;)<br>            current = current.next</pre><p>6. Call the main class and add elements to the linked list.</p><pre>if __name__ == &#39;__main__&#39;:<br>    lnkd = Linked()<br>    lnkd.insert_node(20)<br>    lnkd.insert_node(40)<br>    lnkd.insert_node(24)<br>    lnkd.insert_node_end(35)<br>    lnkd.insert_node(5)<br>    lnkd.insert_node_end(61)<br>    lnkd.print_list()</pre><blockquote>Summary ~ We created two classes -&gt; Node and Linked, added methods to insert nodes and print list inside of Linked class, then called the main class where we added elements to the list.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*S40yzmBn-iv9NVvoL8ZHeA.png" /><figcaption>Linked List class</figcaption></figure><h4>Removing an Element from a Linked List</h4><p>To remove the first node in the list, point the head of the list to the second node.</p><pre>def delete_top_node(self):<br>    if self.head is None:<br>        return None         # empty list<br>    self.head = self.head.next</pre><p>The last node in the list can also be deleted by changing the pointer of the second last node to none.</p><pre>def delete_last_node(self):<br>    if self.head is None:<br>        return &quot;empty linked list&quot;<br>    if self.head.next is None:<br>        self.head = None<br>        return<br>    del_node = self.head<br>    while del_node.next.next:<br>        del_node = delnode.next<br>    del_node.next = None<br>    </pre><h4>Searching for a specific node in a linked list</h4><p>To find a specific node value, iterate through every node from the head of list until you find a match.</p><pre>def search_node(self, value)<br># set current to first element<br>    current = self.head<br># get the position of each element<br>    position = 0<br>    while current:<br>        if current.value == value:<br>            return f&quot;found node value {value} at position {position}&quot;<br>        current = current.next<br>        position += 1<br>    return f&quot;node value {value} does not exist in list&quot;</pre><p>Linked lists come in three types:</p><ul><li><strong>Singly linked list — </strong>each node has a data field to store data and a pointer to the next node in the sequence. The last node points to NULL.</li><li><strong>Doubly linked list —</strong> each node contains a data filed, a pointer to the next node and a pointer to the previous node. This allows for traversal from head to tail and vice versa and efficient insertion and deletion operations.</li><li><strong>Circular linked list —</strong> this type of list forms a loop since the last node has pointer which points back to the first node. This ensures there are no NULL references.</li></ul><h4>Final Thoughts</h4><p>This is a short guide for working with arrays and linked lists in python. Linked lists are more efficient for insertion and deletion operations — O(n) time complexity, since you do not need to shift data to different positions like in lists. Arrays excel in search operations due to use of indexes and efficient memory management.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6145cc13604e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Pivot and Unpivot Operations]]></title>
            <link>https://medium.com/@gracevalerie1/using-pivot-and-unpivot-operations-4841282aaae0?source=rss-695c8867011f------2</link>
            <guid isPermaLink="false">https://medium.com/p/4841282aaae0</guid>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[sql-pivot]]></category>
            <category><![CDATA[dynamic-sql]]></category>
            <category><![CDATA[pivot-tables]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Gracevalerie]]></dc:creator>
            <pubDate>Tue, 31 Mar 2026 09:30:22 GMT</pubDate>
            <atom:updated>2026-03-31T09:30:22.416Z</atom:updated>
            <content:encoded><![CDATA[<p>Organized data is not always structured in a format or shape that you need for analysis. SQL Pivot tables make data more readable and structured for reporting and analysis. The PIVOT() operation rotates a table by transforming distinct rows of data into columns.</p><pre>-- syntax <br>SELECT column_one, pivoted_column_one, pivoted_column_two,...<br>FROM table_name<br>-- specify the pivot operation<br>PIVOT<br>(<br>aggregate_function(agg_column)<br>-- list of unique row values in the pivot column<br>FOR pivot_column_name IN ([row_value_one], [row_value_two], ...)<br>) AS pivot_alias_name;<br></pre><h4>Example</h4><pre>SELECT * FROM (<br> SELECT c.Name, ProductID, Color FROM Production.Product p <br> INNER JOIN Production.ProductSubCategory c <br> on c.ProductSubCategoryID = p.ProductSubCategoryID<br>) t<br>-- Pivot operation<br>PIVOT (<br> COUNT(ProductID) -- aggregation<br> FOR Name IN (<br> [Road Frames],<br> [Helmets],<br> [Socks],<br> [Jerseys],<br> [Caps],<br> [Road Bikes],<br> [Forks])<br> ) AS pivot_table;</pre><p>The above query takes data from the product table, joins it with subcategories, and then <strong>pivots</strong> the result to show number of products for every category and by color as columns instead of rows. This way we turn categorical row values into column headers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AE27fP-NduWgt2uxZDn3Lw.png" /><figcaption>Simple SQL Pivot operation</figcaption></figure><h4>Unpivot in SQL</h4><p>Unpivot carries out the reverse operation of what pivot does. Instead of converting rows to columns, it transforms the columns into rows.</p><pre>-- syntax<br><br>SELECT column_one, ..., unpivot_column,...<br>FROM (<br>  subquery or table) AS alias_table<br>UNPIVOT<br>(<br>  unpivot_column<br>  FOR column IN ([column_a],[column_b]<br>) as alias_unpivot_table</pre><h4>Dynamic SQL</h4><p>In dynamic SQL, queries are constructed and executed at runtime as it depends on user input and variable parameters. Its high flexibility makes it useful for dynamic reporting and performing complex searches and filtering.</p><p>Dynamic queries are executed using commands like EXEC and sp_executesql</p><h4>Steps in Creating a dynamic SQL Statement</h4><ol><li>Declare the dynamic variables.</li></ol><pre>-- syntax<br>DECLARE @variable_name DATATYPE(..)<br><br>-- example<br>DECLARE<br> @table NVARCHAR(100),<br> @pcategory VARCHAR(50),<br> @sql NVARCHAR(1000);</pre><p>2. Set values for the declared variables.</p><pre>-- syntax<br>SET @variable_name = value<br><br>-- example<br>SET @table = N&#39;Products&#39;;<br>SET @pcategory = &#39;Electronics&#39;;<br>SET @sql = N&#39;SELECT * FROM &#39; + QUOTENAME(@table)<br> + N&#39; WHERE category=&#39; +@category; </pre><p>3. Execute the statement. Use parameterized queries to avoid injection.</p><pre>-- the parameter @category is declared here<br>EXEC sp_executesql @sql, N&#39;@category NVARCHAR(50)&#39;, @category = @pcategory;</pre><h4>Creating Dynamic Pivots</h4><p>Dynamic pivots adopt the characteristics of dynamic SQL queries. Data is updated automatically due to changing columns. We can change the previous pivot table example into a dynamic pivot.</p><pre>-- Step 1 : declare variables<br>DECLARE @columnlist NVARCHAR(100),<br>        @sql NVARCHAR(MAX);</pre><p>2. Select the category names dynamically</p><pre>SELECT @columnlist = STRING_AGG(QUOTENAME(Name), &#39;,&#39;)<br>FROM Production.ProductSubCategory;</pre><p>3. Build the dynamic SQL query string</p><pre>-- copy the example pivot query and replace the pivot columns with @columnlist<br>SET @sql = N&#39;SELECT * FROM (<br> SELECT c.Name, ProductID, Color FROM Production.Product p <br> INNER JOIN Production.ProductSubCategory c <br> on c.ProductSubCategoryID = p.ProductSubCategoryID<br>) t<br>-- Pivot operation<br>PIVOT (<br> COUNT(ProductID) -- aggregation<br> FOR Name IN ( &#39; + @columnlist + &#39;)<br>) AS PivotTable;&#39;<br></pre><p>4. Execute the dynamic pivot</p><pre>EXEC sp_executesql @sql;</pre><h4>Final Thoughts</h4><p>Pivot tables are used to organize data by turning rows into columns while unpivot tables convert columns back to rows. In large datasets or where PIVOT operations are not supported, the GROUP BY clause together with CASE expressions are used.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4841282aaae0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Database Transactions and Transaction Isolation Levels]]></title>
            <link>https://medium.com/@gracevalerie1/understanding-database-transactions-and-transaction-isolation-levels-9485a59de0f7?source=rss-695c8867011f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9485a59de0f7</guid>
            <category><![CDATA[transactions]]></category>
            <category><![CDATA[sql-transactions]]></category>
            <category><![CDATA[atomicity]]></category>
            <category><![CDATA[data-integrity]]></category>
            <category><![CDATA[transaction-isolation]]></category>
            <dc:creator><![CDATA[Gracevalerie]]></dc:creator>
            <pubDate>Tue, 24 Mar 2026 08:39:03 GMT</pubDate>
            <atom:updated>2026-03-24T08:39:03.417Z</atom:updated>
            <content:encoded><![CDATA[<h4>What are SQL Transactions?</h4><p>A transaction groups a sequence of SQL operations into a single unit of work. A transaction will only be successful if all the operations in that transaction are successful. This makes sure data remains accurate and reliable by following the ACID properties.</p><h4>ACID Properties of Transactions</h4><p>ACID is an acronym that represents four standard properties, atomicity, consistency, isolation and duration.</p><p><strong>Atomicity (all or nothing)</strong></p><p>This principle ensures that all operations in a transaction succeed or none are applied. If one part of the transaction fails, the who transaction and cancelled and rolled back to its initial state.</p><p><strong>Consistency</strong></p><p>Consistency in ACID principles ensures that only transactions that adhere to established rules are completed. This is different from consistency in the CAP theorem which ensures that all nodes in a distributed database system store and provide the same data.</p><p><strong>Isolation</strong></p><p>Isolation ensures transactions run independently such that a change in one transaction does not impact others. Each transaction is treated as an isolated unit where concurrent transactions behave as if they are the only transaction running in the system.</p><p><strong>Durability</strong></p><p>Any committed transaction should persist its changes even if a system failure occurs. Durability is achieved by using transaction logs to ensure pending operations in a transaction are completed successfully after a system restart.</p><h4>Transaction Control Language (TCL)</h4><p>TCL commands in SQL are used to manage transactions in a database. They control when changes are made permanent or undone to ensure data integrity and consistency. TCL commands include:</p><h4><strong>BEGIN</strong></h4><p>This command indicates the start of an explicit transaction which encloses SQL operations in the transaction. Use the BEGIN keyword to start a transaction.</p><pre>-- syntax<br>BEGIN TRANSACTION;<br><br>-- postgres<br>BEGIN;<br></pre><h4>COMMIT</h4><p>The COMMIT command is used to mark the end of a successful transaction. It ensures that all data modifications in the transaction become a permanent part of the database.</p><pre>-- syntax<br>BEGIN TRANSACTION;<br><br>sql operations here ...;<br><br>COMMIT TRANSACTION;</pre><h4>ROLLBACK</h4><p>ROLLBACK reverts all changes made by a transaction. This command will erase all data modifications made from the beginning of the transaction.</p><pre>-- syntax<br>BEGIN;<br><br>sql operations here ...;<br><br>ROLLBACK;</pre><h4>SAVEPOINT</h4><p>This is a point in the transaction which can be referenced later. The savepoint partitions a single complex transaction into smaller logical subsets of its component SQL statements. This makes it easier to roll back to specific points instead of to the start of the transaction.</p><pre>BEGIN;<br><br>sql operations here ...;<br><br>SAVEPOINT savepoint_name;<br><br>more sql operations ...;<br><br>ROLLBACK TO savepoint_name; <br><br>COMMIT;</pre><p>Savepoints make transactions more flexible and can be used to manage different isolation levels within the same transaction.</p><h4>Transaction Isolation levels</h4><p>Transaction isolation levels define how changes in one transaction are reflected in concurrent transactions. There are four levels of isolation — read uncommitted, read committed, repeatable read, serializable.</p><p><strong>Concurrency anomalies</strong></p><p>Every isolation level offers some level of protection against concurrency anomalies which include phantom reads, dirty reads and non-repeated reads.</p><p><strong>Dirty Reads</strong></p><p>Dirty reads occur when a transaction reads data from another transaction that has not yet been committed.</p><p><strong>Non-Repeatable Read</strong></p><p>Non-repeatable read occurs when data is modified in the middle of a read therefore the transaction reads the same row twice and returns different values.</p><p><strong>Phantom reads</strong></p><p>A phantom read occurs when a query is executed twice but different rows are retrieved because of inserts or deletes.</p><h4><strong><em>Isolation Levels</em></strong></h4><p><strong>READ UNCOMMITTED</strong></p><p>This level allows statements to read rows that were modified by other transactions but not yet committed. This results in phantom reads, non-repeatable reads and dirty reads.</p><pre>-- syntax<br>BEGIN;<br>SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;<br>-- sql operations here ...;<br><br>COMMIT;<br></pre><p><strong>READ COMMITTED</strong></p><p>Restricts statements from reading data that was modified but not committed by other transactions. It can result in non-repeatable or phantom reads when data is modified by other transactions while in the middle of operations in the current transaction.</p><pre>-- syntax<br>BEGIN;<br>SET TRANSACTION ISOLATION LEVEL READ COMMITTED;<br>-- sql operations here ...;<br><br>COMMIT;</pre><p><strong>REPEATABLE READ</strong></p><p>This isolation level restricts statements from reading data that was modified but not yet committed by other transactions. It also restricts other transactions from modifying data read by the current transaction until it is complete.</p><pre>-- syntax<br>BEGIN;<br>SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;<br>-- sql query...;<br><br>-- similar sql query; both return same results<br><br>COMMIT;</pre><p><strong>SERIALIZABLE</strong></p><p>Locks a range of rows affected by the current transaction from being modified by other transactions.</p><pre>BEGIN;<br>SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;<br>-- data in this transaction block cannot be modified by other transactions<br>-- sql query here ...;<br><br>COMMIT;</pre><h4>PRACTICAL EXAMPLE</h4><p>Example of a successful transaction using BEGIN and COMMIT.</p><pre>-- Example transaction to transfer money from one account to another<br>-- start the transaction<br>BEGIN;<br><br>-- deduct funds from account 10<br>UPDATE account <br>SET account_balance = account_balance - 500 <br>WHERE account_id = 10;<br><br>-- debit the funds to account 25<br>UPDATE account<br>SET account_balance = account_balance + 500 <br>WHERE account_id = 25;<br><br>-- Log the transaction<br>INSERT INTO transaction (account_id, amount, transaction_type, status, transaction_date, dest_account)<br>VALUES(10, 500.00, &#39;transfer&#39;, &#39;completed&#39;, CURRENT_TIMESTAMP, 25);<br><br>-- Make the transaction permanent<br>COMMIT;</pre><p>In case this transaction is not successful, send the ROLLBACK command to start over.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9485a59de0f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to import local and cloud PostgreSQL databases to Power BI]]></title>
            <link>https://medium.com/@gracevalerie1/how-to-import-local-and-cloud-postgresql-databases-to-power-bi-792653f37fc2?source=rss-695c8867011f------2</link>
            <guid isPermaLink="false">https://medium.com/p/792653f37fc2</guid>
            <category><![CDATA[aws-rds-instances]]></category>
            <category><![CDATA[aws-ec2]]></category>
            <category><![CDATA[power-bi]]></category>
            <category><![CDATA[aiven]]></category>
            <dc:creator><![CDATA[Gracevalerie]]></dc:creator>
            <pubDate>Thu, 19 Mar 2026 08:07:53 GMT</pubDate>
            <atom:updated>2026-03-19T08:07:53.174Z</atom:updated>
            <content:encoded><![CDATA[<p>The next logical step after designing your database, is to analyze it to gain insights and make informed business decisions. Business intelligence tools like Power BI allow you to transform, analyze and visualize your data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oxdk240Z6M88DwwRHUZb5g.jpeg" /></figure><p>In this guide you will learn how to easily connect your PostgreSQL database to power BI, whether it is running locally or on a cloud platform like Aiven and AWS.</p><h4>What you need</h4><ol><li>Power BI desktop installed</li><li>An existing PostgreSQL data source</li></ol><h4>How to connect local Postgres database to Power BI</h4><ol><li>Open power BI desktop and click on new Blank report to initialize the project.</li><li>On the blank report view page that appears, click on either Get data from another source or Get data from the menu.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*ajOzsZVBOpWj-ya7N2Kr-Q.png" /><figcaption>Get data (postgresql)</figcaption></figure><p>3. From the dropdown click on more … a modal appears with all the sources you can import data from. Click on database, select PostgreSQL database then click on connect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*oZ15biktlhPj8aLO_uw-Bw.png" /><figcaption>Sources to import data from ~ Power BI</figcaption></figure><p>4. In the dialog that appears, provide server name and database. The Postgres server running locally by default is localhost:5432</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*1EeXn8fSYpHq_IggmMddeQ.png" /><figcaption>Connection Details</figcaption></figure><p>In the navigator window, select specific tables to import then select Load to load data or Transform data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SGPt8uHV5yqF9Nwb3xR1vQ.png" /><figcaption>Load or Transform Data</figcaption></figure><h4>How to connect Aiven database to Power BI</h4><p>Aiven is a database as a service platform that makes it easy for developers to spin up cloud databases.</p><ol><li>Once the Postgres instance on Aiven is running, go to overview and copy the host.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BZ_c0v8WomX2V9wpjHRD4g.png" /><figcaption>AIVEN connection string</figcaption></figure><ol><li>Repeat step 1 to 3 from the previous steps.</li><li>Once you reach the dialog window, paste the host as the server and the database name as database.</li><li>You will then be prompted with a dialog to enter Aiven instance user name and password</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n1cqKLo1uBl6fRqwAFwU7Q.png" /></figure><p>You might encounter the following error when trying to connect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*VRhCDA0VxK7hHcqznEp0Bw.png" /><figcaption>Missing CA Certificate</figcaption></figure><p>The Aiven Instance CA certificate is used to encrypt the connection between Power BI and your database, therefore protecting sensitive data.</p><p>4. Go back to the Aiven instance dashboard and download the CA Certificate</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s2b_1PArdpzwdY6yiEtb_A.png" /><figcaption>Aiven CA certificate</figcaption></figure><p>Rename the downloaded file from .pem to .cer</p><p>5. Double click the file and the following dialog box will appear</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*T7lNvIAlLtROnk3GdZYOcA.png" /><figcaption>Download CA Cert Window</figcaption></figure><p>6. Click on open then install certificate.</p><p>7. Change store location from current user to local machine then click next</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*RcWKsWuAnuCj5oRDxJniFA.png" /></figure><p>Choose place all certificates in the following store -&gt; Browse -&gt; Trusted Root certification authorities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*gSEpJSrw3mDU0k1D7RmGZg.png" /><figcaption>e</figcaption></figure><p>Repeat step 2 and 3 and you will be able to connect to instance and load data</p><h4>How to import RDS Postgres on AWS to Power BI</h4><p><strong>Prerequisites</strong></p><ul><li>An EC2 instance to connect to your database</li><li>An RDS Postgres database connected to the instance</li></ul><p>Follow this <a href="https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_GettingStarted.CreatingConnecting.PostgreSQL.html#CHAP_GettingStarted.Deleting.PostgreSQL">guide</a> for instructions on how to create your database.</p><ol><li>After successfully creating the Postgres database and conning to an ec2 instance, you will see a green dialog box which when you click on you get connection details.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*1AYB_pPNBUDVHbNjjmU6lw.png" /><figcaption>AWS postgres connection details</figcaption></figure><p>Copy all the connection details to use in the next steps</p><p>2. Go to the ec2 instance you created and copy the public DNS name and RSA key name</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JRPWUM3vHxtGXoo8cyp6ag.png" /><figcaption>Public DNS address</figcaption></figure><p>Scroll down to instance details and copy the key pair name</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F2Z6V5_Q5KCboU0uUHdGgQ.png" /><figcaption>Key pair name</figcaption></figure><p>3. Now you can connect to your instance using ssh.</p><pre>ssh -i pem_file_location ec2-user@ec2-instance-public-dns-name<br><br># instead or root user use ec2-user </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*l0EIYBZWrIyjiJchabpIqQ.png" /><figcaption>SSH connection</figcaption></figure><p>4. The next step is to install the psql command line utility using the following commands</p><pre># check for bug fixes and security updates<br>sudo dnf update -y<br><br># install psql<br>sudo dnf install postgresql15</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*8_nTB93eDqs3VMpi3dD0HQ.png" /><figcaption>install psql</figcaption></figure><p>5. Connect to the PostgreSQL DB instance using the connection details you copied in step 1.</p><pre>psql --host=endpoint --port=5432 --dbname=postgres --username=postgres</pre><p>You will be prompted to enter user password.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*3KdWVGWvntMkjZL5Cab3jQ.png" /><figcaption>Successful connection to DB instance</figcaption></figure><p><strong>Now you can run SQL commands</strong></p><p>6. To connect to <strong>Power BI</strong>, go to Get Data -&gt; PostgreSQL Database and enter</p><p><strong>Server </strong>— localhost:5432 and <strong>Database</strong> : postgres &lt;database_name&gt; then click <strong><em>connect</em></strong>. You can now load or transform data .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*Ckpoly2MYkAEzsl9oGJv4Q.png" /><figcaption>connected Postgres</figcaption></figure><h4><strong>Optional configuration</strong></h4><p>1. Click on DB identifier name.</p><p>2. Go to the Connectivity &amp; Security section then scroll to Connection Steps.</p><p>3. Scroll down to Security group rules and click on your VPC security group to customize <strong><em>Inbound rules</em></strong>. Inbound rules are used to control incoming traffic to your instance by specifying which ports and sources of traffic are allowed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MVrEFTWElGU9BpL9LEedeQ.png" /></figure><p>4. Select the ec2 security group. Click on Edit Inbound Rule on the inbound rules tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Czf4A5nuEWqLWa3T7DXO3A.png" /><figcaption>Edit inbound rule</figcaption></figure><p>5. Select Add rule and define who can access the database. Set the type to PostgreSQL and the Source as My IP . Click on save rules.</p><h4>Conclusion</h4><p>If you reached this point, you now know how to import a PostgreSQL database which exists locally, in a managed cloud instance and Postgres in AWS.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=792653f37fc2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WITH Common Table Expressions]]></title>
            <link>https://medium.com/@gracevalerie1/with-common-table-expressions-52482437c92a?source=rss-695c8867011f------2</link>
            <guid isPermaLink="false">https://medium.com/p/52482437c92a</guid>
            <category><![CDATA[common-table-expressions]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Gracevalerie]]></dc:creator>
            <pubDate>Sun, 15 Mar 2026 05:38:14 GMT</pubDate>
            <atom:updated>2026-03-15T05:38:14.518Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZjyJF6j-3uX4-i9xmN1Apw.jpeg" /><figcaption>Recursive CTE</figcaption></figure><p><strong><em>What is a common table expression in SQL?</em></strong></p><p>A CTE is a temporary result set that simplifies complex queries by breaking them down into smaller parts. The result of a CTE query is not stored and will be eliminated after query execution.</p><pre>-- syntax<br>WITH cte_name AS (optional arguments) (<br>  SQL statement .... -- accepts INSERT, SELECT, UPDATE, DELETE statements<br>)<br>SELECT * FROM cte_name;</pre><p>To create a CTE, start by writing the main statement or query</p><pre>-- example (Querying details of employees who are engineers)<br><br>SELECT NationalIDNumber, LoginID, JobTitle, MaritalStatus, HireDate <br>FROM HumanResources.Employee <br>WHERE JobTitle LIKE &#39;%Engineer%&#39;</pre><p>Wrap the query inside a WITH clause, name the CTE then follow with the AS keyword.</p><p>After defining the expression, reference it in a subsequent query.</p><pre>WITH engineers AS (<br>  -- wrapped query<br>    SELECT NationalIDNumber, LoginID, JobTitle, MaritalStatus, HireDate <br>    FROM HumanResources.Employee <br>    WHERE JobTitle LIKE &#39;%Engineer%&#39;<br>  )<br>SELECT * FROM engineers;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*NFJqVQdANf4eQytyKYzRiw.png" /><figcaption>Basic Common Table Expression</figcaption></figure><p>A common table expression query can be joined with other tables</p><pre>WITH cte_name AS (optional arguments) (<br>  SQL statement .... <br>)<br>SELECT * FROM cte_name<br>JOIN table_two_name<br>ON condition...;<br><br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*DzlWQx474nWYCGAbbuc8_Q.png" /></figure><p>The above example inner joins the CTE result to two other tables.</p><h4><em>How to create Recursive CTEs</em></h4><p>In a recursive CTE, the initial CTE is repeatedly executed to return subsets of data until the complete result set is obtained. A common use case for recursive CTEs is when you want to return hierarchical data.</p><p><strong><em>Components of a recursive CTE</em></strong></p><ol><li>The base result set query of the CTE structure known as anchor members. The last anchor member is joined to the first recursive member by UNION ALL operator.</li><li>Recursive member invocations which reference the CTE itself.</li><li>A termination condition which stops the recursion when no rows are returned from the last invocation.</li></ol><p>The following is an example of a recursive CTE to return the hierarchy tree for a products table (category — subcategory — product name)</p><p>First step is to prepare the anchor query</p><pre>-- Anchor member: Level 0<br>SELECT<br>    CAST(pc.ProductCategoryID AS VARCHAR(MAX)) AS CategoryID,<br>    CAST(pc.Name AS NVARCHAR(MAX)) AS CategoryName,<br>    CAST(NULL AS VARCHAR(MAX)) AS ParentID,<br>    CAST(pc.Name AS NVARCHAR(MAX)) AS CategoryPath,<br>    0 AS Level<br>FROM Production.ProductCategory pc</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*sd02Ix3-2NeAiFSFjSC8kA.png" /><figcaption>Query to return all categories</figcaption></figure><p>Next is to write the recursion query that will return subcategories</p><pre>WITH CategoryHierarchy AS (<br>    -- Level 0: Categories<br>    SELECT<br>        CAST(pc.ProductCategoryID AS VARCHAR(MAX)) AS CategoryID,<br>        CAST(pc.Name AS NVARCHAR(MAX)) AS CategoryName,<br>        CAST(NULL AS VARCHAR(MAX)) AS ParentID,<br>        CAST(pc.Name AS NVARCHAR(MAX)) AS CategoryPath,<br>        0 AS Level<br>    FROM Production.ProductCategory pc<br><br>    UNION ALL<br><br>    -- Level 1: Subcategories ( Recursive Member)<br>    SELECT<br>-- return the same number of columns as in achor member<br>        CAST(psc.ProductSubcategoryID AS VARCHAR(MAX)),<br>        CAST(psc.Name AS NVARCHAR(MAX)),<br>        CAST(psc.ProductCategoryID AS VARCHAR(MAX)),<br>        -- e.g Bikes -&gt; Mountain Bikes<br>        CAST(ch.CategoryPath + &#39; -&gt; &#39; + psc.Name AS NVARCHAR(MAX)),<br>        ch.Level + 1<br>    FROM Production.ProductSubcategory psc<br>    INNER JOIN CategoryHierarchy ch ON CAST(psc.ProductCategoryID AS VARCHAR(MAX)) = ch.CategoryID<br>    WHERE ch.Level = 0)<br>    SELECT * FROM CategoryHierarchy ORDER BY CategoryPath;</pre><p>For the query to qualify as a recursive member, it must reference the CTE name. The above example references the CTE name through a JOIN to the ProductSubCategory table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MZA2ko-6sxOri_MjT0fbZA.png" /><figcaption>Recursive CTE Results</figcaption></figure><p>A simpler example of a recursive CTE is a Fibonacci sequence (each element is the sum of two preceding elements)</p><pre>WITH Fibonacci AS (<br>-- Anchor Members ( 0 and 1) are the starting point of our sequence<br>    SELECT 0 num, 1 AS next_number, 1 AS iteration<br>    UNION ALL<br>    -- Recursive step<br>    SELECT next_number, num + next_number, iteration + 1<br>    FROM Fibonacci -- CTE Name<br>    WHERE iteration &lt; 24  -- The First 24 numbers of this fibonnaci sequence<br>    )<br>SELECT num FROM Fibonacci;</pre><h4>How to create Multiple CTEs</h4><p>Multiple CTEs combine two or more table expressions in a single SQL query.</p><pre>-- syntax<br>WITH CTE_name AS (<br>  query statement ...<br>),<br>second_CTE_name AS (<br>  query statement ...<br>)<br>SELECT x, y FROM CTE_name, second_CTE_name</pre><h4>Conclusion</h4><p>Recursive CTEs require anchor members and recursive members. They are useful for mapping hierarchical data and generating sequences. In general, common table expressions are meant to simplify complex queries into smaller manageable steps.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52482437c92a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>