<?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 Farah Ananda on Medium]]></title>
        <description><![CDATA[Stories by Farah Ananda on Medium]]></description>
        <link>https://medium.com/@farahananda?source=rss-e614fc1bcc43------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YA31uwTZkCTepZ0S1AwTyw.jpeg</url>
            <title>Stories by Farah Ananda on Medium</title>
            <link>https://medium.com/@farahananda?source=rss-e614fc1bcc43------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 07:33:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@farahananda/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[Data on Wheels: How I Built a Relational Database for Car Enthusiasts]]></title>
            <link>https://blog.stackademic.com/data-on-wheels-how-i-built-a-relational-database-for-car-enthusiasts-7351712929ea?source=rss-e614fc1bcc43------2</link>
            <guid isPermaLink="false">https://medium.com/p/7351712929ea</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[relational-databases]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Farah Ananda]]></dc:creator>
            <pubDate>Wed, 28 Aug 2024 10:06:43 GMT</pubDate>
            <atom:updated>2024-08-29T00:51:03.367Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SF-vlKPbHS3AklvbBl57Hg.jpeg" /><figcaption>Source: Pinterest</figcaption></figure><p>What is your criteria of perfect ride? Is it the brand? The model? The color? Whatever your criteria is your search for perfect ride will need a seamless user experience! And the key for this seamless user experience lies in the foundation of the platform — the database. In this project, we will design and implement a relational database that not only stores detailed car information but also connects buyers and sellers and enhances the entire online car shopping experience.</p><p>The mission of this project is to design and implement a relational database for an online used car sales platform that allows users to list and search for cars based on various criteria such as location, brand, model, and whether bidding is allowed. The database will store detailed information about the cars, their sellers, and the locations where the cars are available. However, the platform will not manage the bidding process or transactions, as these activities will occur outside the scope of the database.</p><h3>Designing the ERD</h3><p>Based on the mission statement, we can now determine the primary objects for our database. Since the function of this database is to connect users (sellers and buyers) from numerous locations and allow them to bid on cars, our primary objects are:</p><ul><li><strong>Users</strong> : user_id (PK), name, contact, location_id (FK)</li><li><strong>Locations</strong> : location_id (PK), location, latitude, longitude</li><li><strong>Cars</strong> : car_id (PK), brand, model, year, color, mileage, price</li><li><strong>Advertisements</strong> : ad_id (PK), car_id (FK), user_id (FK), date_posted, allow_bidding (Boolean)</li><li><strong>Bids</strong> : bid_id (PK), ad_id (FK), user_id (FK), date_bid, bid_price, bid_status</li></ul><p>From these objects, we can eventually create our database tables.</p><p><strong>Table Relationships</strong></p><ul><li>One location can be associated with multiple users <strong>→ One-to-Many</strong></li><li>Each car can have only one advertisement <strong>→</strong> <strong>One-to-One</strong></li><li>One user can post multiple advertisements <strong>→</strong> <strong>One-to-Many</strong></li><li>One advertisement can have multiple bids <strong>→</strong> <strong>One-to-Many</strong></li><li>One user can place multiple bids <strong>→</strong> <strong>One-to-Many</strong></li></ul><p>With the tables and their relationships defined, the DDL syntax will look like this:</p><pre>CREATE TABLE Locations (<br>    location_id SERIAL PRIMARY KEY,<br>    location_name VARCHAR(255) NOT NULL,<br>    latitude FLOAT NOT NULL,<br>    longitude FLOAT NOT NULL<br>);</pre><p>The <a href="https://github.com/FarahAnanda/online-car-sales-platform-db/blob/main/DDL.sql">full syntax</a> can be found on my GitHub repository for this project. Finally, our ERD will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*Nu_qyqmTRprY7vACPbCsGA.png" /><figcaption>Entity Relationship Diagram</figcaption></figure><h3>Populating the Database</h3><p>To test if our database is working correctly, we need to run some queries on it. But before we can do that, the database needs to be populated with data. To populate our database, we will combine public datasets with dummy datasets. The public datasets we’ll use are the <a href="https://www.kaggle.com/datasets/arnavsmayan/vehicle-manufacturing-dataset">Vehicle Manufacturing Dataset</a> from Kaggle and <a href="https://github.com/plotly/datasets/blob/master/us-cities-top-1k.csv">US Top Cities</a> from GitHub. The dataset from Kaggle will provide data about car brand, model, year, color, mileage, and price, which will populate the cars table in our database. The dataset from GitHub will populate the locations table. For the other tables, we&#39;ll use the Faker library to generate dummy data.</p><p>First, to generate fake users, we will use the Faker library, which allows us to create realistic dummy data. The following code snippet demonstrates how to generate 1,500 users, with 1,000 users being associated with locations derived from the car data, and the remaining 500 users having random locations from the locations table.</p><pre># Initialize Faker<br>fake = Faker()<br><br># Generate location_id for 1,000 users from car data<br>num_users_car_location = 1000<br>car_locations = car_data_with_location_id[&#39;location_id&#39;].sample(n=num_users_car_location, replace=True).tolist()<br><br># Generate location_id for 500 users with random locations<br>num_users_random_location = 500<br>random_locations = random.choices(locations[&#39;location_id&#39;], k=num_users_random_location)<br># Combine both lists of locations<br>all_locations = car_locations + random_locations<br># Generate users data<br>num_users = 1500<br>users_data = {<br>    &#39;user_id&#39;: range(1, num_users + 1),<br>    &#39;name&#39;: [fake.name() for _ in range(num_users)],<br>    &#39;contact&#39;: [fake.email() for _ in range(num_users)],<br>    &#39;location_id&#39;: all_locations<br>}<br>users = pd.DataFrame(users_data)</pre><p>Next, for the advertisements table, we create ads linked to the cars in our database. Each advertisement is associated with a car and a user. The date the ad was posted and whether bidding is allowed are also generated randomly.</p><pre># Generate advertisements data<br>advertisements = pd.DataFrame({<br>    &#39;ad_id&#39;: range(1, len(cars) + 1),<br>    &#39;car_id&#39;: cars[&#39;car_id&#39;],<br>    &#39;user_id&#39;: [random.choice(users[&#39;user_id&#39;]) for _ in range(len(cars))],<br>    &#39;location_id&#39;: car_data_with_location_id[&#39;location_id&#39;],<br>    &#39;date_posted&#39;: [fake.date_between(start_date=&#39;-1y&#39;, end_date=&#39;today&#39;) for _ in range(len(cars))],<br>    &#39;allow_bidding&#39;: [random.choice([True, False]) for _ in range(len(cars))]<br>})</pre><p>Lastly, the bids table will be a bit more complex since we don’t want users to bid on their own ads. The following code ensures this by generating bids only from users who didn&#39;t create the associated ad. It also tracks the status of each bid to determine if it was accepted or not. The loop breaks if a bid is accepted, ensuring no further bids are generated for that ad.</p><pre># Merge advertisements with cars to get the car price<br>ads_with_bidding = advertisements[advertisements[&#39;allow_bidding&#39;]].merge(<br>    cars[[&#39;car_id&#39;, &#39;Price&#39;]], on=&#39;car_id&#39;, how=&#39;left&#39;<br>)<br><br># Generate bids data<br>bids = []<br>bid_id_counter = 1<br>for ad in ads_with_bidding.itertuples():<br>    num_bids = random.randint(0, 10)<br>    last_bid_accepted = False<br>    for _ in range(num_bids):<br>        if last_bid_accepted:<br>            break<br>        bid_date = fake.date_between(start_date=ad.date_posted + timedelta(days=1), end_date=&#39;today&#39;)<br>        bid_price = int(ad.Price * random.uniform(0.8, 0.99))  # Bid price lower than the car price, cast to int<br>        bid_status = random.choice([&#39;Accepted&#39;, &#39;Sent&#39;])<br>        # Ensure user doesn&#39;t bid on their own ad<br>        bidder_id = random.choice([uid for uid in users[&#39;user_id&#39;] if uid != ad.user_id])<br>        bids.append({<br>            &#39;bid_id&#39;: bid_id_counter,<br>            &#39;ad_id&#39;: ad.ad_id,<br>            &#39;user_id&#39;: bidder_id,<br>            &#39;date_bid&#39;: bid_date,<br>            &#39;bid_price&#39;: bid_price,<br>            &#39;bid_status&#39;: bid_status<br>        })<br>        if bid_status == &#39;Accepted&#39;:<br>            last_bid_accepted = True<br>        bid_id_counter += 1<br>bids_df = pd.DataFrame(bids)</pre><p>You can also check out the <a href="https://github.com/FarahAnanda/online-car-sales-platform-db/blob/main/generate_datasets.py">full Python code</a> in my GitHub repository. Once all datasets are generated, we can save them to CSV files and import them into the database we created earlier. To import the datasets, you can run the following SQL commands:</p><pre>-- Advertisements<br>COPY Advertisements(ad_id, car_id, user_id, location_id, date_posted, allow_bidding)<br>FROM &#39;/path/to/advertisements.csv&#39;<br>DELIMITER &#39;,&#39;<br>CSV HEADER;<br><br>-- Bids<br>COPY Bids(bid_id, ad_id, user_id, date_bid, bid_price, bid_status)<br>FROM &#39;/path/to/bids.csv&#39;<br>DELIMITER &#39;,&#39;<br>CSV HEADER;</pre><p>Make sure to replace /path/to/ with the actual path where your CSV files are stored. You can similarly import other tables by changing the column and table names, or you can check the <a href="https://github.com/FarahAnanda/online-car-sales-platform-db/blob/main/input_data.sql">full syntax</a> on my GitHub.</p><h3>Retrieving the Data</h3><p>We can finally test if our database is working properly! To test it out, I created some transactional and analytical queries. Remember that the results of these queries could differ for everyone since we used the random library in our Python code earlier, which generates random values. You can see the datasets I used for this query <a href="https://github.com/FarahAnanda/online-car-sales-platform-db/tree/main/datasets">here</a>.</p><h3>Creating Transactional Queries</h3><p>These queries will allow us to test how our database works in various scenarios. By running different types of queries, we can confirm that our database is not only correctly structured but also capable of efficiently managing the kinds of data retrieval and insertion tasks it was designed for.</p><p><strong>Search for cars that were released in 2019 or later</strong></p><p>Even though this is a used car selling website, as buyers, we still want to search for cars that are not too old. Say we want to search for cars that were released in 2019 or later; to do that, we can run the following query:</p><pre>SELECT car_id, brand, model, year, price<br>FROM cars<br>WHERE year &gt;= 2019;</pre><p>This query will return the following result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*gj_Uk2IEL_yg1x94Yd_N4Q.png" /><figcaption>List of cars that were released in 2019 or later</figcaption></figure><p>Now you can see the list of the latest cars along with their prices! The resulting table gives you a clear view of the car brands, models, years, and prices available, helping potential buyers quickly compare options and make informed decisions based on their budget and preferences.</p><p><strong>Adding a bid to the dataset</strong></p><p>This database also allows us to add a bid to the bids table. To do that you can specify the ad ID of the car being bid on, the user ID of the bidder, the date of the bid, and the bid amount. The following syntax demonstrates how to do this:</p><pre>-- Insert a new bid with the next available bid_id<br>INSERT INTO bids (bid_id, ad_id, user_id, date_bid, bid_price, bid_status)<br>VALUES (<br>    (SELECT MAX(bid_id) + 1 FROM bids), <br>    101, <br>    20, <br>    CURRENT_DATE, <br>    55000, <br>    &#39;Sent&#39;<br>);<br><br>-- View the updated bids table<br>SELECT * FROM bids WHERE ad_id = 101;</pre><p>Great! Now you will get this result</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*IVJ00IDtnsoRGgCrFuG-Xw.png" /><figcaption>The bid we just added</figcaption></figure><p>You can see that our latest bid has been successfully added to the table. As the data has just been inserted, the bid status is set to Sent, indicating that the bid is still active and has not yet been accepted by the seller.</p><p><strong>Check all the cars sold by one seller</strong></p><p>Maybe as a car enthusiast, you already have your trusted seller, so you want to buy a car from them. No worries — this database will allow you to do that! To check all the cars that a particular seller has posted, you can input their user ID, and the query will display all the ads they’ve posted</p><pre>SELECT a.ad_id, c.brand, c.model, c.year, c.price, a.date_posted<br>FROM advertisements a<br>JOIN cars c ON a.car_id = c.car_id<br>WHERE a.user_id = 2<br>ORDER BY a.date_posted DESC;</pre><p>Using my dataset that query will give this result</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*tfbD8jT88_DopKknacTHng.png" /><figcaption>Cars listed for sale by user ID 2</figcaption></figure><p>From the result, we can tell that the seller with user ID 2 is selling two cars: a 2017 Chevrolet Malibu and a 2017 Hyundai Sonata. This query not only helps buyers but also allows sellers to easily review their active listings.</p><p><strong>Search for the cheapest cars using a keyword</strong></p><p>Say you already have a specific car model in mind, and now you want to search for the cheapest car available on the website. You can do just that by running the following query:</p><pre>SELECT car_id, brand, model, year, price<br>FROM cars<br>WHERE model LIKE &#39;%Yaris%&#39;<br>ORDER BY price ASC<br>LIMIT 10;</pre><p>The query will result in this table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*7lx-SJz0t0QJpQ0j_Ix2FA.png" /><figcaption>List of 10 cheapest ‘Yaris’ cars</figcaption></figure><p>From the table, you can see a list of the 10 cheapest cars with the model “Yaris” sorted by price. This will be incredibly useful for budget-conscious buyers who know exactly what they want and are looking for the best deal available. By filtering the results with a specific model keyword and ordering them by price, buyers can quickly identify the most affordable options that meet their criteria.</p><p><strong>Search for the nearest cars for sale</strong></p><p>When buying a car, you’ll probably want to check its condition yourself, right? But traveling long distances can be a hassle, so you might want to see the nearest cars for sale. Since we have location data for both users and cars, we can calculate the Euclidean distance and find the nearest cars to a specific location. The following query demonstrates how to find the closest available cars:</p><pre>SELECT a.ad_id, c.brand, c.model, c.year, c.price, <br>    ROUND(CAST(SQRT(POWER(l.latitude - loc.latitude, 2) + POWER(l.longitude - loc.longitude, 2)) AS NUMERIC), 2) AS distance<br>FROM advertisements a<br>JOIN cars c ON a.car_id = c.car_id<br>JOIN locations l ON a.location_id = l.location_id<br>JOIN locations loc ON loc.location_name = &#39;New Orleans&#39;<br>ORDER BY distance ASC, c.price ASC<br>LIMIT 10;</pre><p>By running that query you will get the following result</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*x8GRjrxvUMmSaaWLHjas5w.png" /><figcaption>List of 10 nearest cars available from the New Orleans</figcaption></figure><p>From this table, you can see the list of the 10 nearest cars available from the New Orleans area sorted by distance. This is incredibly useful for buyers who want to minimize travel time and check the condition of the car in person. By sorting the results based on both distance and price, the query helps users find the best deals within their immediate vicinity, making the car-buying process more convenient and efficient.</p><h3>Creating Analytical Queries</h3><p>As a data analyst, creating analytical queries is an essential part of my role. These queries help me uncover valuable insights from data and helping with informed decision-making processes. By answering specific analytical questions, I can reveal patterns, trends, and anomalies within the data.</p><p><strong>What are the most popular cars based on the number of bids?</strong></p><p>This important to understand consumer demand on the platform. By identifying the most popular cars based on bid activity, the seller can make data-driven decisions about marketing efforts, and promotional strategies. For instance, if a particular model receives significantly more bids than others, it indicates high demand, and the platform might prioritize acquiring more of that model or running targeted promotions.</p><p>The following SQL query will retrieve the top 10 most popular car models based on the number of bids they have received:</p><pre>SELECT c.model,<br>       COUNT(a.ad_id) AS count_product,<br>       COUNT(b.bid_id) AS count_bid<br>FROM cars c<br>JOIN advertisements a ON c.car_id = a.car_id<br>LEFT JOIN bids b ON a.ad_id = b.ad_id<br>GROUP BY c.model<br>ORDER BY count_bid DESC<br>LIMIT 10;</pre><p>Running this query produced the following results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*HATwUzyjbkRfJlmpyUGYiQ.png" /><figcaption>Top 10 most popular cars</figcaption></figure><p>The results reveal that the Honda Civic is the most popular car model on the platform, with 96 bids. This high bid count is likely due to the large number of Civic cars listed on the website (146 advertisements). Understanding which models attract the most bids allows the platform to better cater to user preferences.</p><p><strong>How does a car’s price compare to the average car prices in the city where it is sold?</strong></p><p>Buyers usually want to ensure they are getting a fair deal, while sellers need to price their cars competitively to attract bids. Comparing individual car prices to the average prices in the same city provides valuable context, helping with more informed pricing decisions.</p><p>The query will first calculate the average car price within each city then selects the top two cars from each city (based on the random ranking) and lists their prices alongside the average city price.</p><pre>WITH ranked_cars AS (<br>    SELECT<br>        l.location_name,<br>        c.brand,<br>        c.model,<br>        c.year,<br>        c.price,<br>        ROUND(AVG(c.price) OVER (PARTITION BY l.location_name), 2) AS avg_car_city,<br>        ROW_NUMBER() OVER (PARTITION BY l.location_name ORDER BY RANDOM()) AS rank<br>    FROM cars c<br>    JOIN advertisements a ON c.car_id = a.car_id<br>    JOIN locations l ON a.location_id = l.location_id<br>)<br>SELECT location_name, brand, model, year, price, avg_car_city<br>FROM ranked_cars<br>WHERE rank &lt;= 2<br>ORDER BY location_name;</pre><p>The query returns the following results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*Be7XBaZy67ZeMqWpLfDxwA.png" /><figcaption>Comparison of car prices in each city</figcaption></figure><p>The results show the price of each car alongside the average car price in the same city. For example, a 2018 Honda Civic listed in Atlanta is priced at $27,000, which is significantly higher than the average city price of $19,432.29. This comparison is essential for sellers to understand if their car is priced competitively within the local market. For buyers, it provides insight into whether they are getting a fair deal compared to other listings in the same city.</p><p><strong>How does a user’s first bid compare to their next bid?</strong></p><p>Understanding user behavior in terms of bidding patterns is critical for optimizing the bidding process and user experience on the platform. By comparing a user’s first bid to their next bid, we can identify trends, such as whether users tend to increase their bids when their initial offer is not accepted. The following SQL query compares the first and next bids of a user on a specific car model:</p><pre>WITH bid_pairs AS (<br>    SELECT<br>        c.model,<br>        b.user_id,<br>        b.date_bid AS first_bid_date,<br>        LEAD(b.date_bid) OVER (PARTITION BY c.model, b.user_id ORDER BY b.date_bid ASC) AS next_bid_date,<br>        b.bid_price AS first_bid_price,<br>        LEAD(b.bid_price) OVER (PARTITION BY c.model, b.user_id ORDER BY b.date_bid ASC) AS next_bid_price<br>    FROM bids b<br>    JOIN advertisements a ON b.ad_id = a.ad_id<br>    JOIN cars c ON a.car_id = c.car_id<br>    WHERE c.model = &#39;Camry&#39;<br>)<br>SELECT *<br>FROM bid_pairs<br>WHERE next_bid_date IS NOT NULL;</pre><p>The query produced the following results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*fVJ6JzDcDlcWvhC5A_I7QA.png" /><figcaption>Comparison of user bids for car models</figcaption></figure><p>The results illustrate that user behavior can vary significantly. In some cases, users increase their bid amount when their initial bid is not accepted, as seen with user 906, who raised their bid from $15,834 to $16,324. However, there are also instances where the next bid is lower than the first, as with user 346, who decreased their bid from $21,338 to $14,906. By analyzing these bidding patterns, the platform can improve its algorithms for suggesting bid amounts and enhancing the user experience.</p><p><strong>How does the difference between the model average price and average bid looks like?</strong></p><p>Understanding the difference between the average price of a car model and the average bid price will allow sellers and buyers to identify which models might be overpriced or underbid. The SQL query will calculate the average car price and the average bid price for each model over the last six months. It then computes the difference between these two values and expresses it both as a raw value and a percentage of the average car price.</p><pre>WITH avg_prices AS (<br>    SELECT<br>        c.model,<br>        ROUND(AVG(c.price), 2) AS avg_price,<br>        ROUND(AVG(b.bid_price) FILTER (WHERE b.date_bid &gt; CURRENT_DATE - INTERVAL &#39;6 months&#39;), 2) AS avg_bid_6month<br>    FROM cars c<br>    JOIN advertisements a ON c.car_id = a.car_id<br>    LEFT JOIN bids b ON a.ad_id = b.ad_id<br>    WHERE b.bid_price IS NOT NULL AND b.date_bid &gt; CURRENT_DATE - INTERVAL &#39;6 months&#39;<br>    GROUP BY c.model<br>)<br>SELECT<br>    model,<br>    avg_price,<br>    avg_bid_6month,<br>    ROUND(avg_price - avg_bid_6month, 2) AS difference,<br>    ROUND((avg_price - avg_bid_6month) / avg_price * 100, 2) AS difference_percent<br>FROM avg_prices;</pre><p>After running this query, we get the following results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*2LdXsIXCMZIV9ACp-ne3rw.png" /><figcaption>Difference between the model average price and average bid</figcaption></figure><p>From these results, we can tell that the average bid price ranges from a 2% to 20% difference compared to the average asking price. A smaller difference may suggest that the model is priced competitively, while a larger difference might indicate overpricing or a lack of buyer interest at the listed price.</p><p><strong>What is the average bid price for each car over the past 6 months?</strong></p><p>Analyzing the average bid price for each car model over the past six months helps us understand bidding trends. This information is vital for sellers to adjust their strategies based on how demand changes month to month. Here’s the SQL code that calculates the average bid price for each car in each of the last six months:</p><pre>WITH bid_data AS (<br>    SELECT<br>        c.brand,<br>        c.model,<br>        ROUND(AVG(bid_price) FILTER (WHERE b.date_bid &gt; CURRENT_DATE - INTERVAL &#39;1 month&#39;), 2) AS m_min_1,<br>        ROUND(AVG(bid_price) FILTER (WHERE b.date_bid &gt; CURRENT_DATE - INTERVAL &#39;2 months&#39; AND b.date_bid &lt;= CURRENT_DATE - INTERVAL &#39;1 month&#39;), 2) AS m_min_2,<br>        ROUND(AVG(bid_price) FILTER (WHERE b.date_bid &gt; CURRENT_DATE - INTERVAL &#39;3 months&#39; AND b.date_bid &lt;= CURRENT_DATE - INTERVAL &#39;2 months&#39;), 2) AS m_min_3,<br>        ROUND(AVG(bid_price) FILTER (WHERE b.date_bid &gt; CURRENT_DATE - INTERVAL &#39;4 months&#39; AND b.date_bid &lt;= CURRENT_DATE - INTERVAL &#39;3 months&#39;), 2) AS m_min_4,<br>        ROUND(AVG(bid_price) FILTER (WHERE b.date_bid &gt; CURRENT_DATE - INTERVAL &#39;5 months&#39; AND b.date_bid &lt;= CURRENT_DATE - INTERVAL &#39;4 months&#39;), 2) AS m_min_5,<br>        ROUND(AVG(bid_price) FILTER (WHERE b.date_bid &gt; CURRENT_DATE - INTERVAL &#39;6 months&#39; AND b.date_bid &lt;= CURRENT_DATE - INTERVAL &#39;5 months&#39;), 2) AS m_min_6<br>    FROM bids b<br>    JOIN advertisements a ON b.ad_id = a.ad_id<br>    JOIN cars c ON a.car_id = c.car_id<br>    GROUP BY c.brand, c.model<br>    HAVING COUNT(*) &gt; 0<br>)<br>SELECT *<br>FROM bid_data<br>WHERE m_min_1 IS NOT NULL AND m_min_2 IS NOT NULL AND m_min_3 IS NOT NULL AND m_min_4 IS NOT NULL AND m_min_5 IS NOT NULL AND m_min_6 IS NOT NULL;</pre><p>Here are some of the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*dK6fSJgiqgRxMZksVhvjaA.png" /><figcaption>Past 6 months average bid prices</figcaption></figure><p>We can see that bid prices for certain models can fluctuate significantly from month to month. For example, the Ford Explorer saw a sharp increase from $14,308 in the third month to $22,036.40 in the fourth month. Such fluctuations may reflect changes in demand, external market conditions, or other factors influencing buyers’ willingness to pay.</p><h3>Conclusion</h3><p>And we’re done! We have successfully designed and implemented a relational database for an online used car sales platform. Throughout this project, we identified key tables and relationships to connect buyers and sellers, facilitate car searches, and manage bids. We populated the database with both real and dummy data, then ran various transactional and analytical queries to validate its functionality. Our queries demonstrated that the database can effectively manage typical user interactions.</p><p>Overall, this project highlights that a well-designed database plays an important role in creating a seamless and efficient user experience on an online platform. Whether you’re a buyer searching for the perfect car or a seller looking to reach potential customers, this database lays the groundwork for a smooth and reliable transaction process.</p><h3>References</h3><ul><li><a href="https://github.com/FarahAnanda/online-car-sales-platform-db">GitHub repository for this project</a></li><li><a href="https://www.kaggle.com/datasets/arnavsmayan/vehicle-manufacturing-dataset">Vehicle Manufacturing Dataset from Kaggle</a></li><li><a href="https://github.com/plotly/datasets/blob/master/us-cities-top-1k.csv">US Top Cities dataset from GitHub</a></li></ul><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a> | <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7351712929ea" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/data-on-wheels-how-i-built-a-relational-database-for-car-enthusiasts-7351712929ea">Data on Wheels: How I Built a Relational Database for Car Enthusiasts</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Click to Cart: The Data Magic Behind Online Shopping]]></title>
            <link>https://blog.stackademic.com/from-click-to-cart-the-data-magic-behind-online-shopping-a2187b498abc?source=rss-e614fc1bcc43------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2187b498abc</guid>
            <category><![CDATA[online-shopping]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Farah Ananda]]></dc:creator>
            <pubDate>Tue, 16 Jul 2024 06:24:40 GMT</pubDate>
            <atom:updated>2024-07-17T00:59:41.194Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*4IXtp2CNdDOb-oiuOUpYsw.png" /><figcaption>Source: freepik</figcaption></figure><p>Who doesn’t shop online nowadays? At least you do, right? When you shop online, you click through various products, add items to your cart, and proceed to checkout — all within minutes. This all seems easy enough for you, but behind this effortless experience lies a vast ocean of data. It’s an ocean that I, as a data analyst, will gladly dive into.</p><p>In this article, you’ll join me in diving into transaction and customer history data. Together, we will also design new database tables to support additional features. Whether you’re a data enthusiast or just curious about the behind-the-scenes of online shopping, take a deep breath — we have a long journey ahead!</p><h3>The Dataset</h3><p>Before we dive in, let’s dip our feet first and taste the water. Let’s take a closer look at the datasets I worked with. These datasets provide insight into a simple online shop application, including product details, customer information, and order and sales information. Here are the tables included in the datasets:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*hufIszQWiJdbmPUHCYHcdA.png" /><figcaption>Tables in the database</figcaption></figure><p>Additionally, we have a special table for items stored in the warehouse. This table stores information about items in the warehouse, including item ID, item name, item size in square feet, and whether the item is a prime product or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*Gmm_nO8olomMAEdaLi8E3Q.png" /><figcaption>Example data from the item table</figcaption></figure><p>You can also check the database and all the SQL queries used for the case studies later in <a href="https://github.com/FarahAnanda/Online-Shop-Database">my GitHub repository</a>. With these datasets in hand, we’re ready to dive in!</p><h3>Monthly Total Payment View</h3><p>Let’s begin with an easy task. We need to create a view that stores a query for calculating the monthly total payment. This view will help in summarizing the monthly transactions, providing a clear picture of the total payment amounts for each month and year. Here’s the SQL query to create the view:</p><pre>CREATE VIEW monthly_transaction_summary AS<br>SELECT<br>    EXTRACT(MONTH FROM to_date(order_date, &#39;YYYY-MM-DD&#39;)) AS sale_month,<br>    EXTRACT(YEAR FROM to_date(order_date, &#39;YYYY-MM-DD&#39;)) AS sale_year,<br>    SUM(payment) AS total_transaction_amount<br>FROM<br>    orders<br>GROUP BY<br>    EXTRACT(YEAR FROM to_date(order_date, &#39;YYYY-MM-DD&#39;)),<br>    EXTRACT(MONTH FROM to_date(order_date, &#39;YYYY-MM-DD&#39;))<br>ORDER BY<br>    sale_year, sale_month;</pre><p>To see the table created by this view, you can query:</p><pre>SELECT * FROM monthly_transaction_summary;</pre><p>Running this query will show us the monthly transaction summary:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*ugXxlhmUwBVTltEp5dEZ6A.png" /><figcaption>Monthly total payment</figcaption></figure><p>This view, monthly_transaction_summary, shows the total payment amounts grouped by each month and year. It extracts the month and year from the order_date field, sums up the payment amounts, and groups the results by the extracted year and month. This summary helps in tracking the monthly financial performance of the online shop.</p><h3>Warehouse Management</h3><p>Say our shop has a warehouse, the warehouse manager responsible for stock management, you oversee a warehouse with a total area of 600,000 square feet. There are two types of items: prime items and non-prime items. These items come in various sizes, with priority given to prime items. Your task is to determine the maximum number of prime and non-prime items that can be stored in the warehouse. Prime and non-prime items are stored in their respective containers, with specific quantities required for each type of container.</p><p>To address this task, I made an SQL query to calculate the maximum number of prime and non-prime items that can be stored in the warehouse given its total area and the total area each item occupies. The query calculates the maximum number of prime and non-prime items that can be stored in the warehouse.</p><pre>WITH prime_sqft AS (<br>    SELECT SUM(item_size_sqft) AS total_prime_sqft<br>    FROM item<br>    WHERE is_prime = TRUE<br>),<br>non_prime_sqft AS (<br>    SELECT SUM(item_size_sqft) AS total_non_prime_sqft<br>    FROM item<br>    WHERE is_prime = FALSE<br>),<br>warehouse_capacity AS (<br>    SELECT<br>        600000 AS total_area,<br>        total_prime_sqft,<br>        total_non_prime_sqft,<br>        FLOOR(600000 / total_prime_sqft) AS max_prime_qty,<br>        FLOOR((600000 - (FLOOR(600000 / total_prime_sqft) * total_prime_sqft)) / total_non_prime_sqft) AS max_non_prime_qty<br>    FROM<br>        prime_sqft<br>    CROSS JOIN<br>        non_prime_sqft<br>)<br>SELECT<br>    &#39;prime&#39; AS item_type,<br>    max_prime_qty * 35 AS item_count<br>FROM<br>    warehouse_capacity<br><br>UNION ALL<br><br>SELECT<br>    &#39;non-prime&#39; AS item_type,<br>    max_non_prime_qty * 15 AS item_count<br>FROM<br>    warehouse_capacity;</pre><p>The query results reveal the maximum number of prime and non-prime items that can be stored in the warehouse:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*O2DKmQMKR8WeYRoOo61VyQ.png" /><figcaption>Maximum items that can be stored</figcaption></figure><p>From this query, we discovered that the maximum number of prime items that can be stored in the warehouse is 350, and the maximum number of non-prime items is 15. This insight helps the warehouse manager ensure optimal use of the available space while prioritizing the storage of prime items.</p><h4>Warehouse Planning</h4><p>Next, the warehouse manager is planning to find a new warehouse to store their products. The new warehouse is expected to accommodate 20 containers for each prime and non-prime item. Your task is to determine the minimum required size for the new warehouse.</p><p>To determine the minimum required size for the new warehouse, my SQL query will calculate the total area needed to accommodate 20 containers for each prime and non-prime item.</p><pre>WITH warehouse_capacity AS (<br>    SELECT<br>        (SELECT SUM(item_size_sqft) FROM item WHERE is_prime = TRUE) AS total_prime_sqft,<br>        (SELECT SUM(item_size_sqft) FROM item WHERE is_prime = FALSE) AS total_non_prime_sqft<br>)<br>SELECT<br>    (total_prime_sqft * 20) + (total_non_prime_sqft * 20) AS total_wh_area<br>FROM<br>    warehouse_capacity;</pre><p>The results of the query give us the minimum required size for the new warehouse:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/155/1*fWYNL99qfnD0tqgHsMRVFQ.png" /><figcaption>Minimum required size for the warehouse</figcaption></figure><p>From this query, we discovered that the minimum required size for the new warehouse is 670,800 square feet. The total area needed to accommodate 20 containers for both prime and non-prime items ensures that the warehouse manager can plan for future storage needs.</p><h3>Creating New Tables</h3><p>The online shop application is currently expanding its features, and our task is to add several new tables to the existing schema to support these new functionalities. This involves designing new tables, defining their structures and relationships, and updating the existing database schema.</p><p>To support the new features, I introduced two new tables: shops and carts.</p><ul><li><strong>shops</strong>: This table stores information about each shop, including their ID, name, address, and email. The primary key for this table is shop_id.</li><li><strong>carts</strong>: This table stores information about shopping carts, including their ID, customer ID, date, product ID, and quantity. The primary key for this table is cart_id, and it references the customers and products tables through foreign keys.</li></ul><p>To link products to specific shops, the products table was modified to include a shop_id column. Thus, our DDL syntax will look like this:</p><pre>-- Create shops table<br>CREATE TABLE public.shops (<br>    shop_id SERIAL PRIMARY KEY,<br>    name VARCHAR(100) NOT NULL,<br>    address VARCHAR(255),<br>    email VARCHAR(100)<br>);<br><br>-- Create carts table<br>CREATE TABLE public.carts (<br>    cart_id SERIAL PRIMARY KEY,<br>    customer_id INTEGER REFERENCES customers(customer_id),<br>    cart_date DATE,<br>    product_id INTEGER REFERENCES products(product_id),<br>    quantity INTEGER<br>);<br><br>-- Modify products table to include shop_id<br>ALTER TABLE products<br>ADD COLUMN shop_id INTEGER REFERENCES shops(shop_id);</pre><p>With these new additions, the shops and carts tables, and the modification to the products table, here’s our new ERD:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*deqGooWrsLa8NgoSWeDBrw.png" /><figcaption>Table Relationships</figcaption></figure><h3>Adding New Data</h3><p>We already made new tables! Now let’s try adding new entries to the orders and sales tables and then call the view we made before to see if the monthly total payments update accordingly. To add new data, you can use INSERT INTO and then input the data using VALUES. You are free to add your own data! Or you can see the data I input in <a href="https://github.com/FarahAnanda/Online-Shop-Database/blob/main/queries/w6_2.sql">here</a>.</p><p>After inserting the new data, we call the view to see the updated results:</p><pre>SELECT * FROM monthly_transaction_summary;</pre><p>Running this query will show us the updated view for monthly payment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*H0v8J5Pey_oWFO-T6fzZJw.png" /><figcaption>New view for monthly payment</figcaption></figure><p>In this task, I inserted 5 new records into the orders and sales tables. After adding these records, querying the monthly_transaction_summary view shows the updated total payment amounts, grouped by each month and year. The query results now reflect the additional transactions in June 2024, demonstrating how the view dynamically updates with the new data.</p><h3>Creating an Index</h3><p>As the customer base grows, the volume of data in the customers table increases. Without an index, search queries become slower. To enhance the performance of searches based on the customer name, we can create an index on the customer_name column in the customers table. Later, when we search for a customer by name, the index significantly reduces the amount of data the database needs to scan, leading to a faster query response. Here&#39;s the SQL syntax to create the index:</p><pre>CREATE INDEX idx_customer_name ON customers (customer_name);</pre><h3>Partitioning the Table</h3><p>There’s also another way to speed up the search — partitioning! It allows the database to quickly locate relevant partitions instead of scanning the entire table. For instance, frequent searches often require filtering by date ranges, and partitioning can significantly optimize such queries. Here we are going to try partitioning the products table based on the product_type column:</p><pre>-- Create partitioned table<br>CREATE TABLE products_partitioned (<br>    product_id SERIAL,<br>    product_type VARCHAR(100),<br>    product_name VARCHAR(100) NOT NULL,<br>    size VARCHAR(100),<br>    colour VARCHAR(100),<br>    price INT CHECK (price &gt; 0),<br>    quantity INT,<br>    description VARCHAR(100),<br>    shop_id INT,<br>    PRIMARY KEY (product_id, product_type)<br>)<br>PARTITION BY LIST (product_type);<br><br>-- Create partitions<br>CREATE TABLE trousers PARTITION OF products_partitioned<br>    FOR VALUES IN (&#39;Trousers&#39;);<br><br>CREATE TABLE shirt PARTITION OF products_partitioned<br>    FOR VALUES IN (&#39;Shirt&#39;);<br><br>CREATE TABLE jacket PARTITION OF products_partitioned<br>    FOR VALUES IN (&#39;Jacket&#39;);</pre><p>After creating the partitioned table, we need to insert data from products to our partitioned table.</p><pre>-- Insert data into the partitioned table<br>INSERT INTO products_partitioned (product_id, product_type, product_name, size, colour, price, quantity, description, shop_id)<br>SELECT<br>    product_id,<br>    product_type,<br>    product_name,<br>    size,<br>    colour,<br>    price,<br>    quantity,<br>    description,<br>    shop_id<br>FROM products;</pre><p>And then to test if the table is working, you can try querying that table. You can try this:</p><pre>SELECT * FROM trousers;</pre><h3>Let’s Resurface!</h3><p>After the dive into the data, now you know how a database for an online shop application works! We explored transaction and customer history data, designed new database tables to support additional features, and created SQL queries to gain insights from the data. You also learned how a data analyst speeds up the search using indexing and partitioning. So, next time you shop online, remember that data magic is happening behind the scenes!</p><p>For a deeper dive into the data and SQL queries used in these case studies, check out <a href="https://github.com/FarahAnanda/Online-Shop-Database">my GitHub repository</a>. Happy data diving!</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a> | <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2187b498abc" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/from-click-to-cart-the-data-magic-behind-online-shopping-a2187b498abc">From Click to Cart: The Data Magic Behind Online Shopping</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Are the Most Popular Genres in Digital Music Industry: An SQL Data Analysis]]></title>
            <link>https://medium.com/@farahananda/what-are-the-most-popular-genres-in-digital-music-industry-an-sql-data-analysis-7c16a568ea9a?source=rss-e614fc1bcc43------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c16a568ea9a</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[music]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[digital-marketing]]></category>
            <dc:creator><![CDATA[Farah Ananda]]></dc:creator>
            <pubDate>Wed, 10 Jul 2024 10:02:32 GMT</pubDate>
            <atom:updated>2024-07-10T10:02:32.466Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*6Vx_vzZNt9UtMnlyFqcYlg.png" /><figcaption>Source: Pinterest</figcaption></figure><p>An increasing number of digital music stores have appeared since the 2000s. Through these stores, listeners are enabled to purchase albums digitally, legally allowing them to download the album and own it forever, without the risk of a broken CD. But how do these music stores improve their sales and understand customer preferences? This project aims to explore these questions using data from <a href="https://github.com/lerocha/chinook-database">Chinook Database</a>. The goal is to gain valuable insights that can guide product and marketing strategies. Using PostgreSQL, we will deep dive into transaction histories and customer data to reveal trends, preferences, and opportunities for growth.</p><h3>The Dataset</h3><p>This database provides an insight into the digital music shop, including artist details, album catalogs, album and song sales information, and information on customers and employees associated with a digital media store. This data can be used for various analytical purposes, including understanding sales trends, customer preferences, and developments in the digital music industry. You can see the tables detail information and their relationships in <a href="https://github.com/FarahAnanda/media-store-analysis">here</a>.</p><h3>Diving into the Data</h3><p>To help with decision-making processes, we will need to answer several key objectives: Which countries generate the most sales? What genres are most popular? Who are the highest-spending customers? These questions are crucial for shaping effective marketing strategies and improving the sales. By using SQL queries, we can answer these questions and gain some insights from the data. The full SQL scripts are available on my GitHub. Let’s explore!</p><h4><strong>Which countries have the most number of invoices?</strong></h4><p>Understanding which countries generate the highest number of invoices is important to help finding key markets. This information helps prioritize marketing efforts and tailor products to regional preferences.</p><p>We queried the database to find the top 10 countries by the number of invoices. The SQL code orders the countries by the number of invoices in descending order. If multiple countries have the same number of invoices, they are further sorted by country name in ascending order. The results display the country name along with the total number of invoices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*xUV3GiAI9dGesmG5CbTx2A.png" /><figcaption>Top 10 countries with the most number of invoices</figcaption></figure><p>The query reveals that the USA leads with the highest number of invoices, followed by Canada, Brazil, and several other countries. This insight allows the digital music store to focus on these top-performing markets for targeted marketing campaigns and customer engagement strategies.</p><h4><strong>What are the top 10 genres by total sales?</strong></h4><p>Determining which music genres generate the highest sales will help optimizing the music store’s catalog. This information helps the store understand customer preferences and invest in popular genres.</p><p>To find the top 10 genres by total sales, we calculated the total sales by multiplying the quantity of items sold by their respective prices. The SQL code joins the invoice line, track, and genre tables to obtain the necessary data. The results are grouped by genre name and ordered by total sales in descending order, showing the genre name and total sales.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*CwPlLLlT4_L7bNsG13zwNg.png" /><figcaption>Top 10 genres by total sales</figcaption></figure><p>The query results indicate that Rock has the highest total sales, amounting to $826.65. The table displays the top 10 genres and their total sales, giving valuable insights for marketing strategies.</p><h4><strong>Who are the top 10 highest spending customers?</strong></h4><p>Identifying the highest spending customers helps in understanding the store’s most valuable clients, this information is crucial for developing targeted loyalty programs.</p><p>To find the top 10 highest spending customers, we calculated each customer’s total spending by summing the totals from their invoices. The SQL code joins the customer and invoice tables to obtain the relevant data. The results are grouped by customer ID and ordered by total spending in descending order, displaying the customer name, email, and total spending.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*VfbSlFm1WsNw90z3dg38Og.png" /><figcaption>Top 10 highest spending customers</figcaption></figure><p>The query results show the top 10 highest spending customers, with the highest spender having spent $49. This insight helps the digital music store focus on retaining these valuable customers and enhancing their shopping experience.</p><h4><strong>Which city has the most number of invoices in the top countries?</strong></h4><p>From the first objective we already knew the top 10 countries with the most number of invoices. Next, understanding which cities generate the most invoices within those countries helps the store identify key markets and optimize their marketing strategies for these locations.</p><p>To find the city with the most invoices in each of the top 10 countries, we first identified the top 10 countries by the number of invoices (from the previous task). The query then groups the invoices by city within these top countries, ordering the results by the number of invoices in descending order for each country. The results show the top city for each of the top 10 countries, ranked by the number of invoices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*6DsA_3y5HVXppXfxYNkNzw.png" /><figcaption>Cities with the most number of invoices</figcaption></figure><p>The query results reveal the top city within each of the top 10 countries, along with their respective number of invoices. This insight helps the digital music store pinpoint the most active cities within top countries.</p><p>Next, we can find deeper information to help Product Team</p><h4><strong>Selecting New Tracks for the United Kingdom Market</strong></h4><p>The product team is aiming to introduce new tracks from emerging artists to the store and promote them in the United Kingdom. Given a limited budget for marketing, the team needs to carefully select 4 out of 6 proposed songs. The tracks and their respective genres that <strong>will be added</strong> to the store are:</p><ul><li>“Lalaland”: R&amp;B/Soul</li><li>“Soul Sister”: Pop</li><li>“Good to See You”: Rock</li><li>“Nothing On You”: Jazz</li><li>“Get Ya Before Sunrise”: Reggae</li><li>“Before The Coffee Gets Cold”: Hip Hop/Rap</li></ul><p>To maximize the impact, they intend to choose tracks belonging to genres that are already popular in the UK. To determine which genres are most popular in the UK, the query calculates the total purchases for each genre in the United Kingdom. By joining the Invoice, InvoiceLine, Track, and Genre tables, and filtering for invoices billed in the UK, the query groups the results by genre and orders them by the total number of purchases in descending order.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*CVkPwEHKtQRZfDaRHIa7Gw.png" /><figcaption>Popular Genres in the UK</figcaption></figure><p>The results indicate that the most popular genres in the UK within those choices are Rock, Reggae, Jazz, and Hip Hop/Rap. Therefore, the tracks that the product team should include in the store are:</p><ul><li>“Good to See You”: Rock</li><li>“Nothing On You”: Jazz</li><li>“Get Ya Before Sunrise”: Reggae</li><li>“Before The Coffee Gets Cold”: Hip Hop/Rap</li></ul><h4><strong>Marketing Popular USA Albums Internationally</strong></h4><p>The product team aims to identify and market albums that are popular in the USA to other countries. To assist with this, we need to find the 10 most popular albums in the USA based on the number of units sold.</p><p>To determine the most popular albums, the query calculates the total units sold for each album in the USA. By joining the InvoiceLine, Track, Album, Artist, Invoice, and Customer tables, and filtering for customers located in the USA, the query groups the results by album and artist. It then orders the albums by the total number of units sold in descending order.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*2h4JPomyka49GD0iaMlH5w.png" /><figcaption>Most popular albums in the USA</figcaption></figure><p>The query results show the 10 most popular albums in the USA, including the album title, artist name, and total units sold. This provides a clear picture of which albums are most successful in the USA, allowing the product team to focus their marketing efforts on these popular albums when expanding to other countries.</p><h4><strong>Aggregated Purchase Data by Country</strong></h4><p>To help understand sales distribution globally we need to aggregate purchase data by country, while grouping countries with only one customer into a category labeled ‘Other.’ This aggregation will ensure that countries with minimal data do not skew the results.</p><p>The query first calculates the number of unique customers, total sales value, and total orders (invoices) for each country. It then groups countries with only one customer under ‘Other.’ The final output includes the total number of customers, total sales, average sales per customer, and average order value, sorted by total sales in descending order.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*w-oVwjmOsw6xqdSz4Q5ENg.png" /><figcaption>Purchase data by country</figcaption></figure><p>The results provide a view of the purchase data by country, showing that the USA has the most unique customers. Additionally, 15 countries have only one customer, grouped under ‘Other.’ The table displays the aggregated data, including the total number of customers, total sales, average sales per customer, and average order value, which can be used for strategic decision-making and market analysis.</p><h4><strong>Identifying Low-Sales Genres in the USA</strong></h4><p>The product team aims to boost sales for genres with low performance in the USA by implementing targeted promotions and strategies. Analyzing these genres can help determine where to focus marketing efforts.</p><p>The query will calculate the total quantity of items sold and the total sales for each genre in the USA by multiplying the quantity of items sold by their respective prices. The results are then sorted in ascending order of total sales, highlighting the genres with the lowest sales.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*y0y2Oc0fAcac9cWTqQDMgQ.png" /><figcaption>USA album sales</figcaption></figure><p>The query results reveal that certain genres, such as Science Fiction, have very low sales in the USA, with only one item sold contributing $1.99 to the total sales. These genres could benefit from additional promotional efforts or strategic initiatives to increase their visibility and sales.</p><p>Now, let’s deep dive into the behavior of our customers</p><h4><strong>Analyzing Customer Spending by Genre</strong></h4><p>The marketing team wants to target advertisements based on each customer’s highest spending genre. By identifying the top genre for each customer, they can tailor their marketing efforts to individual preferences.</p><p>The query calculates the total amount spent by each customer on different genres by summing the product of the quantity of items sold and their respective prices. It ranks the genres for each customer based on total spending, then selects the top genre for each customer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*HifSwrAasSmx9OxJ3gehRg.png" /><figcaption>Top genre(s) for each customer</figcaption></figure><p>The results reveal the top genre for each customer based on their total spending. It includes the Customer ID, their name, the top genre, total spending on that genre, and the rank. In cases where customers have multiple top genres due to equal spending, such as a customer with ID 12 spending $15.84 on both Latin and Rock, the marketing team can advertise both genres to them.</p><h4><strong>Identifying Top-Spending Countries</strong></h4><p>The marketing team aims to boost advertising in countries where customers spend the most money. Identifying these top-spending countries will help allocate the advertising budget more effectively.</p><p>In this query we will calculate the total spending for each country by summing the product of the quantity of items sold and their respective prices. The results are then ordered by total spending in descending order, showing the top 10 countries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*zftvirtW23V_qL49goCobw.png" /><figcaption>Top-spending countries</figcaption></figure><p>The results highlight the top 10 countries with the highest-spending customers and the total amount spent by customers in those countries. The USA leads with a total spending of $523.06. This information will assist the marketing team in focusing their advertising efforts on the most lucrative markets.</p><h3>Conclusion</h3><p>In this project, we explored various aspects of sales and customer behavior within a digital music store using data. By writing and executing SQL queries, we answer some objectives and gain meaningful insights. We identified the countries and cities with the highest number of invoices, as well as the top 10 genres by total sales and identified the highest-spending customers. We also supported the product team in selecting tracks for the UK market by identifying popular genres and found the most popular albums in the USA to market them internationally.</p><p>From the queries we know that USA has the highest number of invoices and spending, with specific cities contributing significantly. Rock and other genres were found to be the most popular, generating the highest sales. This data-driven approach enabled the product and marketing teams to make informed decisions about track selection and promotional strategies for different markets. By using SQL queries, we successfully transformed raw data into actionable insights, helping the decision-making for the product and marketing teams.</p><h3>References</h3><ul><li><a href="https://github.com/lerocha/chinook-database">Chinook Database</a></li><li><a href="https://github.com/FarahAnanda/media-store-analysis">GitHub Repository for this project</a></li><li><a href="https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=&amp;ved=2ahUKEwjQ0o7oyJuHAxURU2wGHVatCxkQFnoECAYQAQ&amp;url=https%3A%2F%2Fwww.postgresql.org%2F&amp;usg=AOvVaw0He1mmeTUi_lhXjiRGJtzr&amp;opi=89978449">PostgreSQL: The world’s most advanced open source database</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c16a568ea9a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Behind the Scenes of E-Library Application: Making Its Database!]]></title>
            <link>https://blog.stackademic.com/behind-the-scenes-of-e-library-application-making-its-database-fa7c028db0d5?source=rss-e614fc1bcc43------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa7c028db0d5</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[books]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Farah Ananda]]></dc:creator>
            <pubDate>Thu, 04 Jul 2024 10:54:21 GMT</pubDate>
            <atom:updated>2024-07-08T03:47:14.221Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*g9g9osmVSdaMdJyqJBFMiQ.png" /><figcaption>Source: Pinterest</figcaption></figure><p>Do you like reading books? I do, but I hate spending money, so I usually borrow books from libraries. With 17 library cards, I manage to read over 50 books a year without spending a single cent. There’s an app I use to read and borrow books. It holds all my library cards and manages libraries from around the world. That must involve a lot of data, right? They must store it in a database.</p><p>I wonder what their database looks like. In this project, I’m going to design a MUCH simpler database for an e-library application. The purpose of this e-library database is to store and manage data for multiple libraries and their diverse book collections. This includes keeping track of books, members, loans, and hold requests. The goal is to ensure the data is accurate and easy to access, so it can help members and libraries interact smoothly.</p><h3>Designing the Database</h3><p>To design a database, we need a mission statement to guide us in determining the necessary objects for the database. For this database, the <strong>mission statements</strong> are:</p><ul><li>Members can explore the titles available in the libraries.</li><li>Members can search for books based on genre or type.</li><li>Members can know how many copies the libraries have of a title.</li><li>Members can borrow and place holds on books they want to read.</li><li>Members can check the availability of books.</li></ul><p>Before we jump into creating the database, we need to understand its requirements. Here are the requirements for the e-library database system:</p><p><strong>Manage Multiple Libraries:</strong></p><ul><li>The system should handle data for multiple libraries, each with its own collection of books.</li></ul><p><strong>Book Collection:</strong></p><ul><li>Store information about books, including titles, authors, genres, and copies available for borrowing.</li><li>Books should be categorized for easier searching (e.g., self-help, biography, fantasy, romance, historical).</li></ul><p><strong>Member Data:</strong></p><ul><li>Store member information, allowing them to add their card(s) to the app.</li><li>Registered members should be able to borrow books, place holds, and manage their shelves.</li></ul><p><strong>Loan and Hold System:</strong></p><ul><li>Track borrowing transactions, including loan dates, due dates, and return dates.</li><li>Implement a loan period of 2 weeks, with automatic return of books after the due date.</li><li>Allow members to borrow up to 2 books at a time.</li><li>Enable members to place holds on books that are currently unavailable.</li><li>Maintain a hold queue and release held books if not borrowed within one week.</li><li>Members can hold up to 2 books at a time.</li></ul><h3>Designing the ERD</h3><p>Based on our requirements, this app will manage data from multiple libraries and connect members to their respective libraries. Each library can issue its own cards, and members can add their library cards to the app. This enables them to search and check the availability of a title across all libraries. The primary objects of our database, along with their attributes, are:</p><ul><li>Library : library_id, library_name, library_address</li><li>Book : book_id, title, isbn, type</li><li>Author : author_id, author_name</li><li>Genre : genre_id, genre_name</li><li>Member : member_id, member_name</li><li>Card : card_id, card_number, password</li><li>Loan : loan_id, loan_date, due_date, return_date</li><li>Hold : hold_id, hold_date, available_date, expiry_date</li></ul><p>From these objects we can eventually make our tables for the database.</p><h4>Table Relationships</h4><ul><li>A book can be available in many libraries, and each library can have many books <strong>→ many-to-many</strong></li><li>An author can write many books, but a book can have only one author <strong>→ one-to-many</strong></li><li>A book can belong to multiple genres, and each genre can have many books <strong>→ many-to-many</strong></li><li>A member can have multiple library cards, but each card is associated with only one member <strong>→ one-to-many</strong></li><li>A library can issue many cards, but each card is associated with only one library <strong>→ one-to-many</strong></li><li>A card can borrow multiple books, but each loan belongs to only one card <strong>→ one-to-many</strong></li><li>A library book can only belong to one loan <strong>→ one-to-one</strong></li><li>A library card can place holds on many books, but each hold is associated with only one book <strong>→ one-to-many</strong></li><li>A library book can have multiple holds, but each hold belongs to only one book <strong>→ one-to-many</strong></li></ul><p>With the tables and their relationships defined, after some <a href="https://www.freecodecamp.org/news/database-normalization-1nf-2nf-3nf-table-examples/">normalizations</a> the final ERD will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*kTR9hPDABmw53A-o-bfFvQ.png" /><figcaption>ERD I made using Mermaid</figcaption></figure><h4>Constraints and Additional Column Details</h4><p><strong>LibraryBooks</strong></p><ul><li>quantity NOT NULL, CHECK(quantity &gt;= 0)</li></ul><p><strong>Book</strong></p><ul><li>isbn UNIQUE NOT NULL</li><li>type NOT NULL CHECK(type IN (&#39;book&#39;, &#39;audiobook&#39;))</li></ul><p><strong>LibraryCard</strong></p><ul><li>card_number UNIQUE NOT NULL</li></ul><p><strong>Loan</strong></p><ul><li>return_date CHECK(return_date IS NULL OR return_date &lt;= due_date)</li></ul><p><strong>Hold</strong></p><ul><li>expiry_date CHECK(expiry_date IS NULL OR available_date IS NOT NULL)</li></ul><h3>Implementing the Design</h3><p>Finally, we can create the database based on our ERD design. To implement the design, we need to connect to an SQL database and create a new database. Then, we can write DDL syntax based on the constraints for the required fields. For example, the Library Table has these constraints:</p><ul><li>library_id: PRIMARY KEY, NOT NULL</li><li>library_name: NOT NULL</li><li>library_address: NOT NULL</li></ul><p>Thus, the DDL syntax will look like this:</p><pre>CREATE TABLE Library (<br>    library_id SERIAL PRIMARY KEY,<br>    library_name VARCHAR(255) NOT NULL,<br>    library_address VARCHAR(255) NOT NULL<br>);</pre><p>The full syntax can be found in <a href="https://github.com/FarahAnanda/Elibrary-Database-System/blob/main/DDL.sql">my GitHub repo</a></p><h3>Populating the Database</h3><p>To generate a dummy dataset for the e-library database, I utilized the Faker library, which helps create realistic but fictional data. This allows us to simulate a real-world scenario without needing actual data from an e-library system.</p><p>Before we begin making the dataset, we need to import some Python libraries and define the constants:</p><h4>Libraries</h4><p>Here’s an overview of the constants and the two main functions used for generating dummy data:</p><pre>import pandas as pd<br>import random<br>from faker import Faker</pre><ul><li>Faker: Used to generate random but realistic data.</li><li>pandas: Used for data manipulation and analysis.</li><li>random: Used to generate random values.</li></ul><h4>Constants</h4><pre>fake = Faker()NUM_LIBRARIES = 5<br><br>NUM_AUTHORS = 20<br>NUM_BOOKS = 50<br>NUM_GENRES = 12<br>NUM_MEMBERS = 30<br>NUM_LIBRARY_CARDS = 60<br>NUM_LOANS = 100<br>NUM_HOLDS = 50<br><br>genres = [&#39;fiction&#39;, &#39;nonfiction&#39;, &#39;historical&#39;, &#39;fantasy&#39;, &#39;self-help&#39;, &#39;feminism&#39;, &#39;romance&#39;, &#39;YA&#39;, &#39;mystery&#39;, &#39;contemporary&#39;, &#39;thriller&#39;, &#39;memoir&#39;]<br><br>fiction_genres = [&#39;romance&#39;, &#39;mystery&#39;, &#39;YA&#39;, &#39;thriller&#39;, &#39;contemporary&#39;, &#39;fantasy&#39;, &#39;crime&#39;, &#39;historical&#39;]<br>nonfiction_genres = [&#39;self-help&#39;, &#39;psychology&#39;, &#39;memoir&#39;, &#39;politics&#39;, &#39;crime&#39;, &#39;historical&#39;]</pre><ul><li>fake = Faker(): Initializes the Faker library.</li><li>NUM_LIBRARIES, NUM_AUTHORS, etc.: Constants representing the number of records to generate for each table.</li><li>genres, fiction_genres, nonfiction_genres: Predefined lists of genres that will be used to categorize books.</li></ul><h4>Generating the Datasets</h4><p>Now we can start creating the datasets. For the Library table, we generate a unique library ID for each library to avoid duplication. The table also needs library_name and library_address, so we generate random company names to represent library names and random addresses for the libraries.</p><pre>def generate_libraries(num_libraries):<br>    libraries = []<br>    for _ in range(num_libraries):<br>        libraries.append({<br>            &#39;library_id&#39;: fake.unique.random_int(min=1000, max=9999),<br>            &#39;library_name&#39;: fake.company(),<br>            &#39;library_address&#39;: fake.address()<br>        })<br>    return pd.DataFrame(libraries)</pre><p>Next, we use the generate_books function to create a specified number of books, each with a unique title, author, type (book or audiobook), and associated genres. We combine random words and capitalize them to form book titles, select random author IDs from the author dataset, and randomly assign the type of the book using random.choice([&#39;book&#39;, &#39;audiobook&#39;]).</p><pre>def generate_books(num_books, authors_df):<br>    books = []<br>    for _ in range(num_books):<br>        book_id = fake.unique.random_int(min=1000, max=9999)<br>        author_id = random.choice(authors_df[&#39;author_id&#39;])<br>        title = f&quot;{fake.word().title()} {fake.word().title()}&quot;<br>        book_type = random.choice([&#39;book&#39;, &#39;audiobook&#39;])<br><br>        # Add the book to the list<br>        books.append({<br>            &#39;book_id&#39;: book_id,<br>            &#39;isbn&#39;: fake.isbn13(),<br>            &#39;title&#39;: title,<br>            &#39;author_id&#39;: author_id,<br>            &#39;type&#39;: book_type<br>        })<br>    return pd.DataFrame(books)</pre><p>The full code for generating the dummy dataset can be found in <a href="https://github.com/FarahAnanda/Elibrary-Database-System/blob/main/generate_dummy.py">here</a>. Once we have our datasets, we can save them as CSV files using this:</p><pre># Save to CSV<br>libraries_df.to_csv(&#39;libraries.csv&#39;, index=False)<br>authors_df.to_csv(&#39;authors.csv&#39;, index=False)<br>books_df.to_csv(&#39;books.csv&#39;, index=False)<br>genres_df.to_csv(&#39;genres.csv&#39;, index=False)<br>library_books_df.to_csv(&#39;library_books.csv&#39;, index=False)<br>book_genres_df.to_csv(&#39;book_genres.csv&#39;, index=False)<br>members_df.to_csv(&#39;members.csv&#39;, index=False)<br>library_cards_df.to_csv(&#39;library_cards.csv&#39;, index=False)<br>loans_df.to_csv(&#39;loans.csv&#39;, index=False)<br>holds_df.to_csv(&#39;holds.csv&#39;, index=False)</pre><p>Since we have the CSVs of our dummy dataset, we can finally input it into the SQL database we created earlier. This query will allow you to do that:</p><pre>-- Library<br>COPY Library(library_id, library_name, library_address)<br>FROM &#39;/path/to/libraries.csv&#39;<br>DELIMITER &#39;,&#39;<br>CSV HEADER;<br>-- Author<br>COPY Author(author_id, author_name)<br>FROM &#39;/path/to/authors.csv&#39;<br>DELIMITER &#39;,&#39;<br>CSV HEADER;<br>-- Book<br>COPY Book(book_id, isbn, title, author_id, type)<br>FROM &#39;/path/to/books.csv&#39;<br>DELIMITER &#39;,&#39;<br>CSV HEADER;</pre><p>You will need to replace /path/to/ with the actual path where your CSV files are stored. The full syntax can be found in <a href="https://github.com/FarahAnanda/Elibrary-Database-System/blob/main/input_data.sql">my GitHub repo</a>.</p><h3>Retrieving Data</h3><p>Our e-library database is now ready! To test if it’s working properly, I created some questions. We will use SQL queries to answer these questions and gain insights into how our database works. Remember that the result for this query could be different for anyone, since we use random library in our Python code earlier that will generate random values. You could see the datasets I use for this query in <a href="https://github.com/FarahAnanda/Elibrary-Database-System/tree/main/dummy_datasets">here</a>.</p><h4>1. How many books are available in each library?</h4><p>I have 17 library cards so far, and before registering for a card, I usually check if the library has a vast collection of books. Knowing how many books are available in each library helps members decide which library to join. We can answer this using the following query:</p><pre>SELECT l.library_id, l.library_name, COUNT(lb.book_id) AS total_books<br>FROM LibraryBooks lb<br>JOIN Library l ON lb.library_id = l.library_id<br>GROUP BY l.library_id, l.library_name;</pre><p>Using my dummy dataset, the result is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*KA1o1EpFgr3PWFvsDBWrOg.png" /><figcaption>List of total books available in each library</figcaption></figure><p>From the query result, Barajas, Williams, and Parker Library have the most books among all other libraries. Members should consider getting a library card here to access a diverse collection.</p><h4>2. Which genres are most popular across all libraries?</h4><p>By knowing the most popular genres that members read, libraries can gain insight into which genres they should acquire more of. To answer this, we count how many loans each genre has with this query:</p><pre>SELECT g.genre_name, COUNT(lo.loan_id) AS total_loans<br>FROM Genre g<br>JOIN BookGenre bg ON g.genre_id = bg.genre_id<br>JOIN Loan lo ON bg.book_id = lo.book_id<br>GROUP BY g.genre_name<br>ORDER BY total_loans DESC;</pre><p>Using my dummy dataset, the result is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*lxGc1NwQpo1sd2X1EFvnYg.png" /><figcaption>Most popular genres across all libraries</figcaption></figure><p>Based on the result, nonfiction books are more popular than fiction. Historical is the most popular genre across both fiction and nonfiction. Libraries should consider adding more nonfiction and historical books.</p><h4>3. How many books are currently on loan per library?</h4><p>To help track the availability of books, we can see how many books are currently on loan using the query below:</p><pre>SELECT l.library_id, l.library_name, COUNT(lo.loan_id) AS total_loans<br>FROM Loan lo<br>JOIN Library l ON lo.library_id = l.library_id<br>WHERE lo.return_date IS NULL<br>GROUP BY l.library_id, l.library_name;</pre><p>My dummy dataset results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*zFZF1Qbz35tI47RlW0NP1w.png" /><figcaption>Books that are currently on loan per library</figcaption></figure><p>From the result, we see that Barajas, Williams, and Parker Library have 5 books currently on loan. We know from Question 1 that this library has 26 books in total, meaning 21 books are still available for members to borrow. The same logic applies to other libraries.</p><h4>4. Which books have the highest number of holds?</h4><p>As an e-library user, placing a hold can be frustrating, especially if I want to read the book immediately. Knowing the titles with the highest number of holds can help libraries decide which titles to acquire more copies of.</p><pre>SELECT b.title, COUNT(h.hold_id) AS total_holds<br>FROM Hold h<br>JOIN Book b ON h.book_id = b.book_id<br>GROUP BY b.title<br>ORDER BY total_holds DESC<br>LIMIT 10;</pre><p>The query results using my dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*3S2_hWzXnFtnLDqJlB5eVw.png" /><figcaption>Books with the highest number of holds</figcaption></figure><p>Although the titles look ridiculous due to the dummy dataset, we see that “The Ready Least Book 5” and a few others have the highest number of holds. Libraries should consider adding more copies of these titles.</p><h4>5. What is the average loan duration for returned books?</h4><p>In the e-library app I use, the maximum loan period varies between libraries. Knowing the average loan duration helps libraries set appropriate loan periods. We can get this insight using the query below:</p><pre>SELECT ROUND(AVG(return_date - loan_date)) AS average_loan_duration<br>FROM Loan<br>WHERE return_date IS NOT NULL;</pre><p>The result of the query is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/201/1*A5rxQL7RB-7NaBduHzgRTA.png" /><figcaption>Average loan duration for all libraries</figcaption></figure><p>The result shows that members typically borrow a book for 7 days. Libraries might consider reducing the maximum loan period to speed up the hold queue.</p><h3>Conclusion</h3><p>We’ve gone so far in this project! From making the concept for the database schema using ERD to populating it with realistic yet fictional data using Python’s Faker library. Through SQL queries, we were able to extract meaningful insights such as the number of books available in each library, the most popular genres across all libraries, and the current loan statuses of books. These insights will be useful for library management as well as enhancing the user experience.</p><p>As someone REALLY like both books and data, this project has been particularly fun for me to do! Bonus proof I do have 17 library cards and read more than 50 books this year:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HIYYq18Ebf8u97u5igdFwA.png" /><figcaption>My 17 library cards</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HtbJg4IlApl1LOI-gRi4XQ.png" /><figcaption>I’ve read 59 books this year, although I plan to read 100 books</figcaption></figure><h3>References</h3><ul><li><a href="https://github.com/FarahAnanda/Elibrary-Database-System">GitHub repository for this project</a></li><li><a href="https://www.freecodecamp.org/news/database-normalization-1nf-2nf-3nf-table-examples/">Database Normalization — Normal Forms 1nf 2nf 3nf Table Examples</a></li><li><a href="https://mermaid.js.org/">Mermaid | Diagramming and charting tool</a></li><li><a href="https://faker.readthedocs.io/en/master/">Faker’s documentation</a></li></ul><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a> | <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa7c028db0d5" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/behind-the-scenes-of-e-library-application-making-its-database-fa7c028db0d5">Behind the Scenes of E-Library Application: Making Its Database!</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[High Demand Doesn’t Mean High Revenue: A Supply Chain Data Analysis]]></title>
            <link>https://medium.com/@farahananda/high-demand-doesnt-mean-high-revenue-a-supply-chain-data-analysis-70815a3dfae9?source=rss-e614fc1bcc43------2</link>
            <guid isPermaLink="false">https://medium.com/p/70815a3dfae9</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[supply-chain]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Farah Ananda]]></dc:creator>
            <pubDate>Mon, 10 Jun 2024 03:28:10 GMT</pubDate>
            <atom:updated>2024-06-10T03:28:10.294Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*DHdNcr2rFLdhLiy_IhvS6Q.png" /><figcaption>Source: EdrawMax</figcaption></figure><p>Supply chain management is a complex industry. How can high demand not lead to high revenue? This is where the concept of fill rate comes in. According to <a href="https://dclcorp.com/blog/fulfillment/fill-rate/">DCL’s article</a>, the fill rate refers to the percentage of client orders immediately fulfilled by available stock. A low fill rate indicates that the business often fails to meet client demands, resulting in lost revenue opportunities. Therefore, understanding the dynamics between demand and stock levels is crucial for maximizing revenue and customer satisfaction. In this project, I analyzed supply chain data from a recent workshop and will share key insights from the findings.</p><h3>Purpose of The Analysis</h3><p>The main objectives of this analysis are:</p><ol><li>To evaluate the overall demand trends and their impact on supply chain efficiency.</li><li>To identify the top item categories in demand and how they vary among different client categories.</li><li>To analyze the relationship between stock levels and fill rates to pinpoint inefficiencies.</li><li>To provide actionable recommendations for improving inventory management and fill rate performance.</li></ol><h3>The Dataset</h3><p>I obtained the dataset from Pacmann during a data workshop I attended. It contains the latest year’s transaction data for a supply chain business. Below is the list of features:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*JZH3i4qzrlzyrQbCW6kZWQ.png" /><figcaption>Features of the dataset</figcaption></figure><h3>Into the Visualization</h3><p>To determine the appropriate plots to visualize, I first created these KPI cards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*84JnIifVGJxPcoCiEQ34zg.png" /><figcaption>Key Performance Indicators (KPIs)</figcaption></figure><p>The KPI cards reveal that the total yearly demand is 776,501, showing a 12.93% increase from the previous year. The latest monthly demand is 265,140, which is a 5.73% increase from the previous month. The fill rate stands at 79.66%, indicating a need for improved stock management practices to meet customer demand effectively. The “Latest Stock” feature can help the business track each item’s stock and manage inventory efficiently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*5hunDh4Ym2n_fOBoQqskRg.png" /><figcaption>Top Item Category Demands</figcaption></figure><p>The bar chart displays the top 10 item categories most demanded by clients, with tables and chairs being the most sought-after items. The dashboard allows filtering by client name, enabling the business to prepare and allocate stock based on specific client needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*83vvKG2rpvxFKd4RjbjxBw.png" /><figcaption>Demands by Client Category</figcaption></figure><p>This visualization indicates that the government (pemerintah) and private sectors (swasta) are the largest demand drivers, with total demands of 1,222,718 and 932,166, respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*T41aSCc_Sl_5HKg1NlhK4w.png" /><figcaption>Demand and Stock Trend</figcaption></figure><p>Despite higher stock levels, the fill rate remains low at 79.66%. This discrepancy suggests that while overall stock may be sufficient, the distribution and allocation of specific items are misaligned with demand patterns. Some items are overstocked, while others are understocked, failing to meet customer needs effectively.</p><h3>Conclusion and Recommendations</h3><p>The analysis reveals that high demand does not necessarily mean high revenue due to inefficiencies in inventory management. Regularly updating and monitoring the “Latest Stock” data is crucial to ensure high-demand items are adequately stocked while avoiding overstocking less demanded items. Additionally, utilizing the client filtering option in the dashboard allows for tailoring stock levels according to the specific demands of major client categories, such as government and private sectors. By addressing these areas, businesses can better align their stock levels with demand, improve fill rates, and ultimately enhance revenue generation and customer satisfaction.</p><p>References</p><ul><li><a href="https://public.tableau.com/app/profile/farah.ananda/viz/SupplyChainDashboard_17137855743390/SupplyChainDashboard">Supply Chain Dashboard</a></li><li><a href="https://dclcorp.com/blog/fulfillment/fill-rate/">What Is Fill Rate? (Definition, Types and How To Calculate)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70815a3dfae9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Boosting Retail Revenue: Data-Driven Strategies]]></title>
            <link>https://medium.com/@farahananda/boosting-retail-revenue-data-driven-strategies-b82688b62046?source=rss-e614fc1bcc43------2</link>
            <guid isPermaLink="false">https://medium.com/p/b82688b62046</guid>
            <category><![CDATA[online-shopping]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[retail]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Farah Ananda]]></dc:creator>
            <pubDate>Sun, 09 Jun 2024 03:18:38 GMT</pubDate>
            <atom:updated>2024-06-09T03:18:38.736Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Je63SMUUCcsftF1xeS1nHA.png" /><figcaption>Source: Retail Dogma</figcaption></figure><p>Online shopping has become increasingly popular these years, making the retail industry into a competitive market. Understanding customer behavior, sales trends, and product performance is crucial for developing effective business strategies. In this project, I used a public dataset to see these patterns. This analysis not only helps in understanding the current market dynamics but also helping the business to improve their performance.</p><h3>Objective</h3><p>The primary objectives of this analysis were:</p><ol><li>To gain insights into the current transaction histories, including trends in revenue, customer behavior, and product sales over time.</li><li>To provide recommendations that could help increase the company’s revenue within three months.</li></ol><h3>Data Overview</h3><p>I used a public dataset from UCI which contains all the transactions occurring between 01/01/2011 and 09/12/2011 for a UK-based and registered non-store online retail. The dataset consists of the following features:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*eqhqh2gL4ozxtrgXEy0USg.png" /><figcaption>Features of the dataset</figcaption></figure><h3>Insights from the Data: What We Learned</h3><p>Let’s start by looking at some metrics to understand the scope of the dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3L4rTbUfP8vi_Dnlvvuc9Q.png" /><figcaption>Key metrics</figcaption></figure><p>The dataset revealed a total of 15,294 unique orders made by 3,809 distinct customers. Throughout the analyzed period 3,139 different products were sold. By applying the formula Revenue = Quantity × Unit Price, the total revenue generated in 2011 amounted to £6,767,509.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*TmBugIJmFkc-beqAOkROBg.png" /><figcaption>Month-to-month Revenue Growth</figcaption></figure><p>The plot showing that the revenue fluctuates during January to August. Then there is a sharp increase in September to November. But back to normal in December.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*J0pJ7bI3tbrONLNtb5AsSQ.png" /><figcaption>Month-to-month User Growth</figcaption></figure><p>From the plot we can see that there’s an overall increasing trend from January to November, with a notable peak in November. The decline in December probably due to the data only extends until December 9th. As a result, the data may not accurately reflect the entirety of December’s user count.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*RF-2X9hf0fH4DEwGZviK4A.png" /><figcaption>Number of Transactions per Month</figcaption></figure><p>The plot shows that November’s transaction count significantly exceeds the other months with 2,380 invoice numbers. This suggests that November gives the most number of transactions in 2011, possibly due to holiday shopping or promotional events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*8M6BPemGoqF0BgRx_HsGnA.png" /><figcaption>Proportion of Repeating Customers</figcaption></figure><p>The proportion of repeating customers is notably higher than non-repeating customers with 2.443 customers or approximately 64.14% of all customers, while the non-repeating customers is approximately 35.86% which is 1,366 customers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*5yT8Bpg6BjC-duZFPhn_PA.png" /><figcaption>Top 10 Total Transactions Made by Repeating Customers</figcaption></figure><p>The plot showing that the maximum number of transactions done by repeating customers in 2011 is 171, from a customer with ID 12748.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*xrhF-U3MVKvum6QkE5LgSg.png" /><figcaption>Distribution of Item Quantities for Repeating Customers</figcaption></figure><p>Based on the plot most repeating customers tend to purchase smaller quantities of items. The data indicates that the most commonly purchased quantity per product falls within the range of 20 to 60 units, with the highest frequency observed at 20 units.</p><h3>Utilizing the Insights</h3><p>Based on the insights from the visualizations, the following recommendations are proposed to help increase revenue:</p><ul><li>November has the highest transaction count, there’s a high level of customer activity during this month. → Leverage this increased customer engagement by launching new product releases, special promotions, or limited-time offers</li><li>The sales tend to peak at the end of the year likely due to holiday season → upsell products based on the event like Halloween decoration and candies in October or Christmas decoration and ginger bread in December</li><li>The proportion of repeating customers is notably higher than non-repeating customers → Implement a loyalty program to increase revenue</li><li>Most repeating customers tend to purchase smaller quantities of items, with 20 units being the most common quantity per product → Offer bundle deals or discounts on products sold in multiples of 20</li><li>The decline in December’s revenue and transaction count may be because the data only extend until December 9th → Extend data collection throughout December to accurately see the month’s performance and maximize revenue during the holiday season.</li><li>Conduct a customer satisfaction survey to gather feedback and insights for improvement strategies</li></ul><p>By implementing these recommendations, the company can better align its sales strategies with customer behavior and market trends, thereby driving revenue growth in the coming months.</p><h3>References</h3><ul><li><a href="https://public.tableau.com/app/profile/farah.ananda/viz/OnlineRetailAnalysis_17178976469240/Dashboard1#1">Online Retail Dashboard</a></li><li><a href="https://archive.ics.uci.edu/dataset/352/online+retail">Online Retail Dataset</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b82688b62046" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is Higher Education a Necessity or a Choice: The Economic Impact of Higher Education]]></title>
            <link>https://medium.com/@farahananda/is-higher-education-a-necessity-or-a-choice-the-economic-impact-of-higher-education-4bb116ccc46d?source=rss-e614fc1bcc43------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bb116ccc46d</guid>
            <category><![CDATA[education]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[economics]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Farah Ananda]]></dc:creator>
            <pubDate>Tue, 04 Jun 2024 04:41:32 GMT</pubDate>
            <atom:updated>2024-06-09T03:20:04.101Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LJuP7P6jELSHDr3Y5dsZFw.jpeg" /><figcaption>UNSOED students form of protest regarding the ridiculous increase of their tuition</figcaption></figure><p>“We can see that this tertiary education is an education. So it’s not mandatory to study. This means that not all SLTA graduates, SMKs are required to enter higher education. This is an option,” this statement by the Indonesian Ministry of Education and Culture regarding the ridiculous rise of tuitions in some college really strike a chord with me. Is higher education truly a tertiary need? From what I know, higher education is essential to secure a job and live comfortably, as many vacancies offering decent salaries require higher education as its requirement. But of course, I can’t base my conclusion solely on what I know, right? So, I’ve gathered some data to answer my question: “Is higher education a tertiary need?”</p><h3>How to Answer This Question?</h3><p>In order to answer my question, I need to explore how education relates to economical success. Thus, I’ve set the following objectives:</p><ol><li>How education level relate to poverty?</li><li>Does the unemployment rate vary by education level?</li><li>Does higher education correlate with higher income?</li><li>How does education impact earnings across different age groups?</li><li>What percentage of jobs require higher education?</li></ol><h3>The Datasets</h3><p>The search for data didn’t go as smoothly as anticipated. At first, I want to use Indonesian data since this issue is happening in Indonesia. However, finding the necessary data was indeed challenging. So, I decided to use data from the US. Although it might not be directly relatable to Indonesia, it will still help address my problem. To answer my question thoroughly, I used data from four different sources, as listed below:</p><ul><li><a href="https://data.census.gov/table/ACSDT1Y2022.C17003?q=poverty%20by%20education"><strong>Poverty Status by Educational Attainment</strong></a>: This dataset shows the total number of individuals with income below and above the poverty rate in the US in 2022, categorized by educational attainment. The categories include “Less than high school graduate,” “High school graduate (includes equivalency),” “Some college, associate’s degree,” and “Bachelor’s degree or higher.”</li><li><a href="https://www.bls.gov/emp/tables/unemployment-earnings-education.htm"><strong>Unemployment rates and earnings by educational attainment</strong></a>: This dataset provides median weekly earnings and unemployment rates in the US in 2023 based on educational attainment. The categories include “Doctoral degree,” “Professional degree,” “Master’s degree,” “Bachelor’s degree,” “Associate’s degree,” “Some college, no degree,” “High school diploma,” and “Less than a high school diploma.”</li><li><a href="https://www.census.gov/data/tables/time-series/demo/income-poverty/cps-pinc/pinc-04.html#par_textimage_10"><strong>Person Income in 2022</strong></a> This dataset provides a collection of earnings information from various age groups and education levels. The categories include “Doctorate degree,” “Professional degree,” “Master’s degree,” “Bachelor’s degree,” “Associate’s degree,” “Some college, no degree,” “High school graduate (incl GED)” “9th to 12th nongrad”, and “Less Than 9th Grade.”</li><li><a href="https://www.bls.gov/emp/tables/education-summary.htm"><strong>Employment, wages, and projected change in employment by typical entry-level education</strong></a>: This table shows employment based on education level in the US, along with its distribution and projected percent change. The categories include “Doctoral or professional degree,” “Master’s degree,” “Bachelor’s degree,” “Associate’s degree,” “Postsecondary nondegree award,” “Some college, no degree,” “High school diploma or equivalent,” and “No formal educational credential.” For this data, I focused on the employment distribution column to determine the percentage of jobs requiring higher education.</li></ul><p>To unify the educational attainment labels across different datasets, I made the following adjustments:</p><ul><li>For the poverty data, which has broader categories, I grouped “Doctoral or professional degree,” “Master’s degree,” and “Bachelor’s degree” into “Bachelor’s degree or higher.”</li><li>The categories “Associate’s degree”, “Some college, no degree”, and “Postsecondary nondegree award” were grouped under “Some college, associate’s degree”</li><li>The label “No formal educational credential”, “Less than high school diploma”, “9th to 12th nongrad”, and “Less Than 9th Grade” were counted as “Less than high school graduate”.</li></ul><h3>Visualizing the Insights</h3><p>Firstly I visualize how the poverty looks based on the education level. This bar chart is showing the number of individual that live below or at and above poverty level corelate to their education levels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*49iLDxW0hcJrZHJDAVvm0Q.png" /><figcaption>Impact of Educational Attainment on Poverty Levels</figcaption></figure><p>The plot shows that as the level of education increases, the likelihood of individuals earning an income at or above the poverty line also increases. Conversely, lower educational attainment is associated with a higher likelihood of earning an income below the poverty level. This indicates that education is crucial in improving stability and reducing poverty.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qwBKVzw0BkmmoGnnzBlCbA.png" /><figcaption>Educational Attainment vs. Unemployment and Earnings</figcaption></figure><p>The visualization clearly shows individuals with higher levels of education are more likely to be employed and earn higher earnings. The significant difference in both unemployment rates and median wages between those with a bachelor’s degree or higher and those with less education suggests that higher education is an important need for stability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fl9HaCMzxvn7F1sJQz_YHQ.png" /><figcaption>Earnings Growth by Educational Level and Age</figcaption></figure><p>The plot indicates that higher educational attainment leads to higher earnings. Individuals with a bachelor’s degree or higher have a significant rise in earnings, especially in the prime working years (ages 30 to 54).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*DObWDNbXlH2V8XTLEh8TBQ.png" /><figcaption>Employment Distribution by Education Level</figcaption></figure><p>According to the plot, 29.1% of jobs require a bachelor’s degree or higher. This means nearly one-third of the employment market values higher education. However, the majority of jobs only require a high school diploma or less, showing that higher education is not necessary for most jobs.</p><h3>Conclusion</h3><p>The pie chart of employment distribution shows that if your goal is simply to secure any job, you don’t need higher education. However, without higher education in your prime working years, you will have fewer chances for promotion and earning more income compared to those with higher education.</p><p>Is higher education a tertiary need? For a single person, perhaps yes. Data shows that most high school graduates earn around $45,040 annually, while the living cost for a single person in the USA is approximately $38,266 per year. However, for a family, especially with children, where both parents only have high school diplomas, living comfortably could be a struggle. Higher education significantly boosts earnings and provides better opportunities for raises.</p><p>The claim that “higher education is a tertiary need” originates from the Indonesian government. After some googling, I found that living costs in Indonesia are significantly higher than the average income. This means higher education is a necessity for living comfortably, not a tertiary need. Unfortunately I lack the data to support this, I guess it’s a call for the Indonesian government to conduct proper research to support their own statement.</p><h3>References</h3><ul><li><a href="https://public.tableau.com/app/profile/farah.ananda/viz/EducationvsEconomicalSuccess/Dashboard1?publish=yes">Education vs. Economical Success Dashboard</a></li><li><a href="https://data.census.gov/table/ACSDT1Y2022.C17003?q=poverty%20by%20education">Poverty Status by Educational Attainment dataset</a></li><li><a href="https://www.bls.gov/emp/tables/unemployment-earnings-education.htm">Unemployment rates and earnings by educational attainment dataset</a></li><li><a href="https://www.census.gov/data/tables/time-series/demo/income-poverty/cps-pinc/pinc-04.html#par_textimage_10">Person income in 2022 dataset</a></li><li><a href="https://www.bls.gov/emp/tables/education-summary.htm">Employment, wages, and projected change in employment by typical entry-level education</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bb116ccc46d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When Should You Start Worrying About Heart Problems: Insights from Data Visualization]]></title>
            <link>https://medium.com/@farahananda/when-should-you-start-worrying-about-heart-problems-insights-from-data-visualization-e2cb7c4943ff?source=rss-e614fc1bcc43------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2cb7c4943ff</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[health]]></category>
            <category><![CDATA[heart-disease]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Farah Ananda]]></dc:creator>
            <pubDate>Sat, 30 Mar 2024 13:25:35 GMT</pubDate>
            <atom:updated>2024-07-08T09:33:12.731Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*psQYuBd5r0Qjf2vPsCYUSA.png" /><figcaption>Source: The Heart Foundation</figcaption></figure><p>According to the <a href="https://www.cdc.gov/nchs/fastats/leading-causes-of-death.htm">CDC’s Leading Causes of Death</a>, heart disease remains the top cause of mortality in the United States. It’s even more common than cancer and the recent COVID-19 pandemic. <a href="https://my.clevelandclinic.org/health/diseases/24129-heart-disease">Cleveland Clinic</a> states that heart disease is mainly caused by high blood pressure and cholesterol. Chest pain is often an early warning sign, while aging also contributes to the cause. Understanding the factors that contribute to heart disease risk can help us prevent, diagnose, and treat it. As a data enthusiast, I’m interested in analyzing and visualizing the heart disease dataset to gain insights and understand heart disease more effectively.</p><h3>I’m curious about…</h3><p>Based on that background these are some objectives I want to answer with visualization:</p><ol><li>Do one gender get more heart disease than the other?</li><li>How common is heart disease by age?</li><li>Does certain chest pain associated with heart disease?</li><li>Does fasting blood sugar affect heart disease?</li><li>Does age affect blood pressure?</li><li>How does cholesterol level relate to heart disease in different age groups?</li><li>Does high blood pressure and cholesterol raises the risk of heart disease?</li></ol><h3>Into the Data</h3><p>The dataset contains information related to patients’ medical and behavioral attributes for predicting the risk of heart disease. This dataset was obtained from <a href="https://www.kaggle.com/datasets/winson13/heart-disease-dataset?select=Dataset+Heart+Disease.csv">Kaggle</a> and based on the Cleveland dataset, includes a wide range of carefully selected medical and behavioral elements important for predicting heart disease risk. I chose this specific dataset because it was already cleaned, and I see its potential to give unique insights. Below is the feature list based on <a href="https://ieee-dataport.org/open-access/heart-disease-dataset-comprehensive">IEEE DataPort’s Documentation</a>, I may add or delete some data based the visualization I need:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*KQIUwc20Avq0yKqMu75gWg.png" /><figcaption>Features I used to answer the objectives</figcaption></figure><h3>Visualizing Insights: What the Data Reveals</h3><p>Let’s see the distribution of both normal and heart disease cases across gender and age group first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NcdYlkfhXVSbwujRbQH1VQ.png" /><figcaption>Proportion of Patients by Gender</figcaption></figure><p>Based on the pie chart, we can conclude that men are more likely to have heart disease than women, making up 68.66% of all patients with heart disease. However, the visualization itself also shows a higher representation of both normal and heart disease cases among males, it can be conclude that most patients in the dataset are men. <a href="https://www.tandfonline.com/doi/full/10.1080/14017430600913199">A study</a> shows that men are more likely to report chest pain compared to women. This may explain why the dataset is dominated by male patients.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ouYeqcePUb-b5JqGc4zEWQ.png" /><figcaption>Age Distribution of Patients</figcaption></figure><p>The visualization indicates that heart disease cases tend to increase with age. The peak of heart disease cases appears to be in the 55–59 and 60–64 age groups. However, this doesn’t mean that older people have a lower risk of heart disease, as the overall dataset dominated by patients aged 40–59, this may suggest that individuals in those age range are more likely to seek medical attention.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BkLOT5PEH___u2Eb9Jk_UA.png" /><figcaption>Relationship between Chest Pain Type and Heart Disease</figcaption></figure><p>Among patients with heart disease, type 2 (atypical angina) and type 3 (non-anginal pain) chest pains are mostly experienced. Meanwhile, patients who feel type 4 (asymptomatic) chest pain are more likely to have a normal heart condition. However, it’s important to note that patients with type 1 (typical angina) chest pain are also more likely to have heart disease, as the number is high, though still lower than patients with atypical angina and non-anginal pain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9n74bnnkgzu3jvidxYn7gg.png" /><figcaption>Fasting Blood Sugar Distribution by Heart Disease Status</figcaption></figure><p>Most patients despite their heart condition have normal fasting blood sugar level (&lt;120 mg/dl). Based on the visualization, it appears that fasting blood sugar level may not really affect someone’s heart condition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WQgxGvGxmkj6wlv_SNAg6g.png" /><figcaption>Age vs. Resting Blood Pressure</figcaption></figure><p>From the scatter plot we can see that as the age increases the blood pressure also tends to increase, thus we may conclude that age affect blood pressure, the trend line also strengthen this hypothesis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hGGyV5zFzEJQea7xfJQC-w.png" /><figcaption>Cholesterol and Heart Disease Risk by Age</figcaption></figure><p>As age increases, the median of cholesterol levels also rise. We can also see that heart disease tend to occur more frequently in older age groups. This visualization suggests that age affects cholesterol, which in turn affects the risk of heart disease.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-mix9N06xbn83Hoge9gb0w.png" /><figcaption>Blood Pressure vs Cholesterol Level Risk of Heart Disease</figcaption></figure><p>The scatter plot shows that people with high blood pressure and cholesterol tend to have heart disease compared to those that with normal levels of both factors. However we can also see that are some individuals with normal heart condition despite high blood pressure and cholesterol level, it may suggests the correlation between heart disease and high blood pressure or cholesterol is weak.</p><h3>So, the answers are…</h3><p>Individuals in 40–59 age range are more likely to seek medical attention as the dataset dominated by them. Additionally, the data also dominated by male patients as men are more likely to report chest pain. From the visualizations I made, it indicates that men are more prone to heart disease, especially in older age groups. Certain types of chest pain, such as atypical angina and non-anginal pain, are closely linked to heart disease, while fasting blood sugar levels may not really affect someone’s heart condition. Age positively correlates with blood pressure, and as individuals age, the median of cholesterol levels rise, thus increasing the risk of heart disease. High blood pressure and cholesterol levels are associated with a higher risk of heart disease, although the correlation may seems weak.</p><h3>References</h3><ul><li><a href="https://www.kaggle.com/datasets/winson13/heart-disease-dataset?select=Dataset+Heart+Disease.csv">Heart Disease Dataset</a></li><li><a href="https://ieee-dataport.org/open-access/heart-disease-dataset-comprehensive">IEEE DataPort: Heart Disease Dataset’s Documentation</a></li><li><a href="https://public.tableau.com/app/profile/farah.ananda/viz/HeartDiseaseVisualization_17117887401030/">Tableau Dashboard</a></li><li><a href="https://www.cdc.gov/nchs/fastats/leading-causes-of-death.htm">CDC: Leading Causes of Death</a></li><li><a href="https://my.clevelandclinic.org/health/diseases/24129-heart-disease">Cleveland Clinic: Heart Disease, Symptoms &amp; Causes</a></li><li><a href="https://www.tandfonline.com/doi/full/10.1080/14017430600913199">Scandinavian Cardiovascular Journal: Women with myocardial infarction are less likely than men to experience chest symptoms</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2cb7c4943ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>