<?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 Robert O&#39;Brien on Medium]]></title>
        <description><![CDATA[Stories by Robert O&#39;Brien on Medium]]></description>
        <link>https://medium.com/@robertobrien130?source=rss-5cf900dd43d1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6tKBBc2UQlm-OVeJtnhXeg.jpeg</url>
            <title>Stories by Robert O&amp;#39;Brien on Medium</title>
            <link>https://medium.com/@robertobrien130?source=rss-5cf900dd43d1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 23:13:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@robertobrien130/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[Tips And Tricks: How To Fill Null Values in SQL]]></title>
            <link>https://medium.com/data-science/tips-and-tricks-how-to-fill-null-values-in-sql-4fccb249df6f?source=rss-5cf900dd43d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fccb249df6f</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Robert O'Brien]]></dc:creator>
            <pubDate>Sat, 26 Jun 2021 18:08:45 GMT</pubDate>
            <atom:updated>2021-06-26T18:08:45.911Z</atom:updated>
            <content:encoded><![CDATA[<h4>SQL Tips and Tricks</h4><h4>How to utilize nested tables and window functions to fill down over null values</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PNh7hHPK2dYv6mfT" /><figcaption>Photo by <a href="https://unsplash.com/@glenncarstenspeters?utm_source=medium&amp;utm_medium=referral">Glenn Carstens-Peters</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When it comes to data analysis, you often don’t realize what you’re missing until you visualize it. Huge gaps or downward spikes in visualizations will show you exactly where the data is missing, but that’s not a story you want to communicate to your stakeholders.</p><p>While some visualization tools can cover these gaps with ease, it’s often best to handle for this at the data source, and relying on your viz tool to do the work for you won’t come in handy if you need to do further analysis outside of tool. So how do we fill in null or missing values at the source?</p><h4>Filling Down: A Brief Explanation and Example</h4><p>Let’s suppose we have a table that looks like the one below called inventory_log that keeps track of how many widgets your company has in its inventory at the end of each:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*K3aG44nDa351cZRJWd-zng.png" /></figure><p>Since your store is closed on the weekends, there would have been no change of inventory from Friday to Monday, but that also means there was no one to count the inventory and to input that value into the table.</p><p>It would be safe to assume that the inventory number didn’t change from Friday to Monday, so correct values for Saturday and Sunday would be whatever the value for Friday is. To accomplish this, we apply a tool called <strong><em>filling down</em></strong>. Filling down is exactly what it sounds like: whenever there is a null value, we simply grab the most recent non-null value from above it to replace the null value.</p><p>There are many features in Python (including the pandas.DataFrame.ffill() function) that accomplish this, but they are almost always slower than performing the operation directly on the database server.</p><p>Now that we’ve fully examined the problem, let’s understand how to do it in SQL.</p><h4>Filling Down In SQL</h4><p>Using the same table above as our sample data, we can replace the null values utilizing both nested queries and window functions.</p><p>The first thing we want to do is to group the rows with null values with the first non-null value above it. We can do that by utilizing a window function to count the inventory column over the date:</p><pre>select date,<br>       day_of_week,<br>       inventory,<br>       count(inventory) over (order by date) as _grp<br>from inventory_log</pre><p>This query will return us a table that looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*i1RDuVrtqZUw9B6hCLScBw.png" /></figure><p>Okay! That gives us a new column that allows us to group together the null values with the first non-null value preceding them. Now the next step is to return that first value for every row that shares a grouping. Luckily, the first_value window function allows us to do just that.</p><p>Applying this function to what we already have gives us this query:</p><pre>with grouped_table as (<br>   select date,<br>          day_of_week,<br>          inventory,<br>          count(inventory) over (order by date) as _grp<br>   from inventory_log<br>)<br>select date,<br>       day_of_week,<br>       inventory,<br>       _grp,<br>       first_value() over (partition by _grp order by date) as filled_inventory<br>from grouped_table</pre><p>If you want to dive deep into the first_value function, you can <a href="https://docs.microsoft.com/en-us/sql/t-sql/functions/first-value-transact-sql?view=sql-server-ver15">check out the documentation here</a>, but the function simply returns the first value for the partition according to the order.</p><p>The above query gives us the following table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_8BEeyZtEKbkaIp3rf1U8w.png" /></figure><p>That’s it! We now have a column with the null values replaced with the preceding value.</p><p>So let’s put our query all together:</p><pre>with grouped_table as (<br>   select date,<br>          day_of_week,<br>          inventory,<br>          count(inventory) over (order by date) as _grp<br>   from inventory_log<br>), final_table as(<br>   select date,<br>          day_of_week,<br>          inventory,<br>          _grp,<br>          first_value() over (partition by _grp order by date) as<br>              new_inventory<br>    from grouped_table<br>)<br>select date,<br>       day_of_week,<br>       new_inventory<br>from final_table</pre><p>output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*2b_h_D8NpXz6TJdkEZv39w.png" /></figure><p>NOTE: If you have a query where you have multiple dimensions/columns that you need to take into consideration (maybe different store locations in this example), simply add those to the partition clause in the count() window function in the grouped_table sub-query.</p><p>Happy coding!</p><p>If you want to see other data science tips and tricks, check out my article on <a href="https://towardsdatascience.com/upload-your-pandas-dataframe-to-your-database-10x-faster-eb6dc6609ddf">How To Load Your Pandas DataFrame To Your Database 10x Faster</a>. Let me know what you’re working on in the comments below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fccb249df6f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/tips-and-tricks-how-to-fill-null-values-in-sql-4fccb249df6f">Tips And Tricks: How To Fill Null Values in SQL</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top 12 Python Libraries For Data Science In 2021]]></title>
            <link>https://medium.com/data-science/top-12-python-libraries-for-data-science-in-2021-9a3dfbc07430?source=rss-5cf900dd43d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a3dfbc07430</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-lear]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Robert O'Brien]]></dc:creator>
            <pubDate>Fri, 16 Apr 2021 12:39:05 GMT</pubDate>
            <atom:updated>2021-04-16T12:39:05.780Z</atom:updated>
            <content:encoded><![CDATA[<h4>Data Science</h4><h4>These libraries are a great starting point to launch your data science journey.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SeQ0lja9Z1tgiNgo" /><figcaption>Photo by <a href="https://unsplash.com/@cgower?utm_source=medium&amp;utm_medium=referral">Christopher Gower</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Whether you’re a beginner or a seasoned veteran looking to keep up with the trends, these 12 Python libraries are tools you definitely need in your data science toolkit for 2021. Keep in mind that this list isn’t exhaustive, so please add your favorite libraries in the comments below if I’ve left them out!</p><h3>Data Mining</h3><p><em>Note:</em> <em>When scraping data from the web, please check the terms and guidelines of your data sources before scraping. It’s important to follow all licensing and copyright rules that the data source may have.</em></p><h4>1. Scrapy</h4><p><a href="https://docs.scrapy.org/en/latest/">Scrapy</a> is one of the most popular tools for Python developers who are looking to scrape structured data from the web. Scrapy is great for building web crawlers that can gather structured data from web pages of any format, making this an excellent tool for gathering data.</p><h4>2. BeautifulSoup</h4><p>Another great library for gathering and organizing web data, <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/">BeautifulSoup</a> makes scraping websites easy. BeautifulSoup is great for web pages that use special characters as you can easily pass different encoding formats to its functions when gathering web data.</p><h4>3. Requests</h4><p>Call me old fashioned, but there’s nothing like the <a href="https://realpython.com/python-requests/">requests</a> library when it comes to gathering web-based data, especially from APIs. Requests makes it easy to interact with APIs and other HTML sources in simple, one-line solutions.</p><h3>Data Processing</h3><h4>4. Pandas</h4><p><a href="https://pandas.pydata.org/docs/">Pandas</a> is an open-source library that is one of the most widely-used data science libraries, and with over 2300 contributors on their GitHub repo, this library isn’t going away any time soon. Pandas makes data processing and wrangling easy, ingesting data from tons of different sources like CSV, SQL, or JSON, giving you great manipulation features like handling missing data, imputing missing data files, and manipulating columns, and even providing some basic but very useful visualizations.</p><h4>5. Numpy</h4><p>If you’re looking to do any advanced mathematics to any of your datasets, then you need to be importing the <a href="https://numpy.org/">Numpy</a> library. Used heavily in deep learning and machine learning, this is an absolute must for any computationally heavy algorithms and analyses. Numpy’s multi-dimensional arrays also make complex problems infinitely easier than standard lists.</p><h4>6. Scipy</h4><p><a href="https://www.scipy.org/">Scipy</a> is derived from Numpy and can also do tons of different mathematically complex calculations. This library will make your life particularly easier if you’re looking to do multi-dimensional image processing, differential equations, or linear algebra.</p><h3>Machine Learning</h3><h4>7. Keras</h4><p>Now into the deep stuff. <a href="https://keras.io/">Keras</a> has emerged as the go-to library for deep learning, specifically when it comes to neural networks. It’s built on top of TensorFlow but is built to be much more user-friendly, enabling users to do lightweight and quick experiments with their deep learning APIs.</p><h4>8. TensorFlow</h4><p><a href="https://www.tensorflow.org/">TensorFlow</a> is so named because of its use of multi-dimensional arrays, which it calls tensors. There’s a reason that all of the big tech companies are using TensorFlow for their neural network algorithms: this library can do practically anything. Great use cases include sentiment analysis, voice recognition, video detection, time series analysis, and facial recognition, among other things. TensorFlow was developed by Google, so this isn’t going away any time soon.</p><h4>9. PyTorch</h4><p>Whereas TensorFlow uses static graphs, <a href="https://pytorch.org/">PyTorch</a> can define and manipulate graphs on the go, making it a bit more flexible. Despite the more Pythonic approach of PyTorch over TensorFlow, the latter is simply more popular, so it’s easier to find resources on it. If you’re looking for something flexible and a little easier to pick up than TensorFlow, this library (which was developed by Facebook) is a great resource.</p><h3>Visualization</h3><h4>10. Bokeh</h4><p>Some of the most stunning visualizations I’ve seen created by Python code were developed using the <a href="https://docs.bokeh.org/en/latest/index.html">Bokeh</a> library. Bokeh provides interactive visualization options that can easily be displayed in other Python web tools like Flask, making this a great option for sharing visualizations to wide audiences.</p><h4>11. Seaborn</h4><p>The best features for <a href="https://seaborn.pydata.org/">Seaborn</a> (at least when it comes to data science) are the correlation graphs that make it super easy to visually spot correlation across all of the dimensions of your dataset. Seaborn is built on top of MatPlotLib, so it’s easily accessible and a great tool for quickly visualizing your data.</p><h4>12. Plotly</h4><p><a href="https://plotly.com/python/">Plotly</a> is another great tool for creating advanced interactive visualizations that are great for doing exploratory analysis and for displaying results. There’s really nothing that Plotly can’t do, but certain kinds of visualizations are a bit more user friendly in this library rather than other alternatives. Ultimately it just comes down to a matter of taste and familiarity when it comes to choosing the best visualization library for your project.</p><p>This list is by no means exhaustive, but this is a great place to start for anyone on their data science journey. What are your favorite Python libraries for data science? Let me know what you’re working on in the comments below!</p><p>P.S. Do you ever get tired of waiting for Pandas to upload your data to your database? You can load them <a href="https://towardsdatascience.com/upload-your-pandas-dataframe-to-your-database-10x-faster-eb6dc6609ddf"><strong>10x faster</strong> by utilizing native SQL commands</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a3dfbc07430" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/top-12-python-libraries-for-data-science-in-2021-9a3dfbc07430">Top 12 Python Libraries For Data Science In 2021</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Upload Your Pandas DataFrame To Your Database 10x Faster]]></title>
            <link>https://medium.com/data-science/upload-your-pandas-dataframe-to-your-database-10x-faster-eb6dc6609ddf?source=rss-5cf900dd43d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb6dc6609ddf</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Robert O'Brien]]></dc:creator>
            <pubDate>Mon, 14 Dec 2020 12:47:05 GMT</pubDate>
            <atom:updated>2020-12-20T13:37:03.834Z</atom:updated>
            <content:encoded><![CDATA[<h4>Data Science</h4><h3>How To Load Your Pandas DataFrame To Your Database 10x Faster</h3><h4>Speed up your data science pipelines with this simple trick.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ev69uqKf9v0yULcu" /><figcaption>Photo by <a href="https://unsplash.com/@heylagostechie?utm_source=medium&amp;utm_medium=referral">LagosTechie</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When working on data science projects in Python, you’ll inevitably need to load your data into a database, but the most common and simplest way to do this is actually one of the slowest methods you can use.</p><p>Instead of uploading your pandas DataFrames to your PostgreSQL database using the pandas.to_sql() function, you can write the data to a CSV file and COPY the file into PostgreSQL, which is considerably faster, as I’ll demonstrate below. But first, a quick note on the COPY command.</p><h3>Using the COPY command</h3><p>The PostgreSQL COPY command is a native PostgreSQL command that takes the name of a file along with a few arguments and transfers the data into an existing table in the database. You can read more about this command in the <a href="https://www.postgresql.org/docs/12/sql-copy.html">PostgreSQL documentation</a>, which is a helpful tool to have for anyone that uses any kind of ETL with PostgreSQL databases.</p><p>In order to use this command via Python, we’ll need to run it as a query on the database using a library like sqlalchemy or psycopg2. And since COPY requires an existing table, we’ll need to do a little more setup work to create the table, but as you’ll see, the performance boost makes the extra setup worth it.</p><p>To figure out just how much faster the COPY command is, I ran a test on a small DataFrame (1,000 rows) and a large DataFrame (1,000,000 rows) to see how each method performed.</p><h3>Small DataFrame Test</h3><p>For this test, I created a random sample dataset of 1,000 rows, loaded it into a pandas DataFrame, and used each method to upload the DataFrame to a local PostgreSQL database. Here’s the test code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79cbf92a30eb4bbf8a872280e9406c29/href">https://medium.com/media/79cbf92a30eb4bbf8a872280e9406c29/href</a></iframe><p>The results:</p><ul><li>to_sql duration: 0.11182904243469238 seconds</li><li>COPY duration: 0.0103912353515625 seconds</li></ul><p>You can see that the COPY method ran over 10x faster, but at this small scale, there’s not much of a practical speed difference between the two methods. So how do these methods perform with larger DataFrames?</p><h3>Big DataFrame Test</h3><p>This test was identical to the last one, but here I increased the dataset to 1,000,000 rows. The only tweaks to the code below from the code above were small naming changes to denote the difference in the tests:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2dbd84af6547f15721105f6b5992ee30/href">https://medium.com/media/2dbd84af6547f15721105f6b5992ee30/href</a></iframe><p>The results:</p><ul><li>to_sql duration: 69.1165030002594 seconds</li><li>COPY duration: 5.375032186508179 seconds</li></ul><p>The ratio here is actually even better at scale, providing a 12.85x faster performance than the pandas.to_sql() method. For production data science pipelines in enterprise-scale environments, that kind of speed is absolutely crucial in order to be able to keep things running smoothly.</p><p>The only downside to consider for the COPY method is that you’ll have to write a local file, which if left unchecked can easily create memory and storage problems. You can easily add steps to your code to delete the written CSV file to keep your servers happy and clutter-free.</p><p>To try this out yourself, you can download the code and the sample data at my <a href="https://github.com/robertobrien130/upload-data-from-pandas-to-sql/">Github repository here</a>.</p><p>Happy coding!</p><p>Want to see any other Python tutorials or other data science tips and tricks? Let me know what you’re working on in the comments below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb6dc6609ddf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/upload-your-pandas-dataframe-to-your-database-10x-faster-eb6dc6609ddf">How To Upload Your Pandas DataFrame To Your Database 10x Faster</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic Statistical Forecasting in PostgreSQL]]></title>
            <link>https://medium.com/data-science/basic-statistical-forecasting-in-postgresql-c1d38143bb41?source=rss-5cf900dd43d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1d38143bb41</guid>
            <category><![CDATA[editors-pick]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[forecasting]]></category>
            <category><![CDATA[getting-started]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Robert O'Brien]]></dc:creator>
            <pubDate>Thu, 19 Nov 2020 15:08:23 GMT</pubDate>
            <atom:updated>2020-12-04T17:47:57.245Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/getting-started">Getting Started</a>, SQL Tutorials</h4><h3>Basic Statistical Forecasting in SQL</h3><h4>How to employ user-defined functions to create simple time-series forecasts</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*B1LvMXb9tCMHN1GG" /><figcaption>Photo by <a href="https://unsplash.com/@codestorm?utm_source=medium&amp;utm_medium=referral">Safar Safarov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>It’s no secret that forecasting has become a huge part of data analytics. Everyone wants to know not only what the data is saying about the past, but also what it can tell them about the future. While most forecasting methods are accomplished using programming languages like Python or R, sometimes it makes the most sense to do it all at the database level in SQL.</p><p>In this article, we’ll go over one method you can use to harness your data to make predictions, and we’ll use user-defined functions so you can easily share this power across your organization. While this tutorial uses PostgreSQL, the same principles apply across other dialects like MySQL and Oracle.</p><p>Let’s get started.</p><h3>1. Prepare sample data</h3><p>First, let’s <a href="https://www.dropbox.com/s/ol45a4vo1y95hz5/sample_revenue_data.csv?dl=1">download the sample data</a>. This is just a CSV file with two columns, one with months and one with randomly generated revenue numbers. You can also use data from your own datasets later, but for now, let’s upload this CSV into the database.</p><p>After downloading the file, you can easily upload it into your database with these queries to create the table and to insert the data into the table:</p><pre>CREATE TABLE sample_revenue_data (<br>  data_month TIMESTAMP WITHOUT TIME ZONE,<br>  revenue DOUBLE PRECISION<br>);</pre><pre>COPY sample_revenue_data(data_month, revenue)<br>FROM &#39;&lt;PATH_TO_FILE&gt;&#39; -- replace with downloaded file path<br>DELIMITER &#39;,&#39;<br>CSV HEADER;</pre><h3>2. Create and setup the function</h3><p>In order to perform these projections, we’re going to create a user-defined function. We’ll get into why we need that in the next step, but functions are a great way to keep complex queries user-friendly and easily reusable across your database’s users.</p><p>The function that we’re going to build is going to take one parameter: the number of periods into the future that we want to project. We’ll set a default value of 3 periods, but you can make this whatever you like. Here’s how we create our function:</p><pre>CREATE OR REPLACE FUNCTION <em>fn_revenue_projections</em>(<br>    periods INT DEFAULT 3<br>) <br>RETURNS TABLE (<br>    data_month TIMESTAMP WITH TIME ZONE, <br>    revenue DOUBLE PRECISION<br>)</pre><p>Note that it’s a good idea to use the CREATE OR REPLACE FUNCTION syntax so that you can just re-run this block of code should you need to make tweaks to the function, and you won’t have to drop and recreate the function unless you’re making major changes to what the function returns.</p><p>Let’s set up the rest of the Postgres function. You can read more about the syntax and structure of functions in <a href="https://medium.com/@heitorhherzog/postgresql-creating-loop-functions-in-1c724c4b5925">this great post by Heitor Helmer Herzog</a>. For now, we’ll just use this code below:</p><pre>CREATE OR REPLACE FUNCTION <em>fn_revenue_projections</em>(<br>    periods INT DEFAULT 3<br>) <br>RETURNS TABLE (<br>    data_month TIMESTAMP WITH TIME ZONE, <br>    revenue DOUBLE PRECISION<br>) LANGUAGE plpgsql AS $$<br>BEGIN</pre><pre>/*<br>Insert main body of function here.<br>*/</pre><pre>END<br>$$;</pre><h3>3. Create the TEMP TABLE</h3><p>The next thing we need to do is create a TEMP TABLE that we’ll use to store our initial data and to which we’ll append calculated rows. Every period we forecast will need to consider all of the most recent periods, and in order to do that in SQL, we need to have all previous periods in the dataset we’re using.</p><p>That means we’re going to have to calculate one period at a time and insert that period into a table before we can move on to calculating the next period. That’s where our TEMP TABLE is going to come in. This will allow us to return our existing data with our projections later without overwriting anything in our base tables. Here’s the simple SQL we’ll use to create the table:</p><pre>CREATE TEMP TABLE IF NOT EXISTS temp_rev_projection AS<br>    SELECT data_month,<br>           cost<br>    FROM sample_revenue_data<br>    ORDER BY data_month;</pre><p>Put this code between the BEGIN and END of the function we have so far.</p><h3>4. Set up FOR LOOP</h3><p>As we project into future periods, we will inevitably need to consider projection data from near-term periods in order to calculate projection data for farther-term periods. In other words, if it’s currently October, and we want to project for December using a prior 3-month moving average, we will need to have some kind of value for November.</p><p>The only way to do that in SQL is to calculate future periods iteratively, which is where the Postgres FOR LOOP comes in. This will allow us to create projection data for one period at a time, insert that data into our TEMP TABLE, and then use that data to calculate for the next period.</p><p>We already define the number of times we will go through the loop with the variable we pass into the function when we call it, so we just have to include that variable in the FOR LOOP construction.</p><pre>FOR<strong> </strong>i IN 1 .. periods<br>    LOOP<br>        INSERT INTO temp_rev_projection<br>            -- we&#39;ll put our projection calculations here next step<br>    END LOOP;</pre><h3>5. Create projection calculations</h3><p>We’ve finally reached the point where we can calculate the projected value for a future period. We’ll focus on a simple moving average here, but be sure to follow up with Part 2 of this series for examples of more complex projections.</p><h4>Simple Moving Average</h4><p>We can project into future periods simply by calculating the value for each period as the average of the n periods before it. This model is a good, simple solution for short-term predictions, but you should not use this for projections where you’re forecasting more periods into the future than you’re considering in the moving average, as the model will eventually level out.</p><p>Here’s the code for a 3-month moving average:</p><pre>-- 3-month moving average:</pre><pre>INSERT INTO temp_rev_projection<br>    SELECT (<br>              SELECT MAX(data_month) + INTERVAL &#39;1 month&#39;<br>              FROM temp_rev_projection<br>           ) AS data_month,<br>           (<br>               SELECT SUM(revenue) <br>               FROM (<br>                   SELECT * <br>                   FROM temp_rev_projection <br>                   ORDER BY data_month DESC <br>                   LIMIT 3<br>               ) t<br>           ) / 3 AS revenue</pre><h3>6. Run your projections</h3><p>Now that we’ve got all the pieces, let’s put together the completed function, adding a few lines at the end to return the query of the temp table and to drop it so we’re not taking up unnecessary storage in the database:</p><pre>CREATE OR REPLACE FUNCTION fn_revenue_projections(<br>    periods INT DEFAULT 3<br>) </pre><pre>RETURNS TABLE (<br>    data_month TIMESTAMP WITHOUT TIME ZONE, <br>    revenue DOUBLE PRECISION<br>) LANGUAGE plpgsql AS $$</pre><pre>BEGIN</pre><pre>CREATE TEMP TABLE IF NOT EXISTS temp_rev_projection AS<br>    SELECT *<br>    FROM sample_revenue_data<br>    ORDER BY data_month;</pre><pre>FOR i IN 1 .. periods<br>    LOOP<br>        INSERT INTO temp_rev_projection<br>            SELECT (<br>              SELECT MAX(a.data_month) + INTERVAL &#39;1 month&#39;<br>              FROM temp_rev_projection a<br>           ) AS data_month,<br>           (<br>               SELECT SUM(t.revenue) <br>               FROM (<br>                   SELECT * <br>                   FROM temp_rev_projection<br>                   ORDER BY data_month DESC <br>                   LIMIT 3<br>               ) t<br>           ) / 3 AS revenue;<br>    END LOOP;<br> <br> RETURN QUERY EXECUTE &#39;select * from temp_rev_projection&#39;;<br> <br> DROP TABLE temp_rev_projection;</pre><pre>END<br>$$;</pre><p>Now that we have the function fully created, we can select from it just like we would a table since it does, in fact, return a table.</p><p>Remember that our default was three months, so if we don’t pass any parameters to the function when we select from it, we’ll get our projections 3 months into the future. We can also pass an integer into the function’s parentheses to get more or fewer months.</p><p>Here’s two example selections:</p><pre>SELECT *<br>FROM <em>fn_revenue_projections(6);</em></pre><pre>SELECT *<br>FROM <em>fn_revenue_projections(); -- returns 3 months</em></pre><p>It’s that simple!</p><p>Now you and any other users on your database with select permissions can call this simple SQL statement any time you want to project your revenue.</p><p>If you’ve made it this far, thanks for reading! I’m currently working on a second part to this article showing more advanced modeling using seasonality to weight future predictions.</p><p>Want to see any other SQL tutorials? Let me know what you’re working on in the comments below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1d38143bb41" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/basic-statistical-forecasting-in-postgresql-c1d38143bb41">Basic Statistical Forecasting in PostgreSQL</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>