<?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 Ibedufranca on Medium]]></title>
        <description><![CDATA[Stories by Ibedufranca on Medium]]></description>
        <link>https://medium.com/@ibedufranca0?source=rss-43ef176dac54------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*opFpoSdUn0AWGZB7</url>
            <title>Stories by Ibedufranca on Medium</title>
            <link>https://medium.com/@ibedufranca0?source=rss-43ef176dac54------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 01:57:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ibedufranca0/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 CLEANING WITH SQL]]></title>
            <link>https://medium.com/@ibedufranca0/data-cleaning-with-sql-32b9a636d43a?source=rss-43ef176dac54------2</link>
            <guid isPermaLink="false">https://medium.com/p/32b9a636d43a</guid>
            <dc:creator><![CDATA[Ibedufranca]]></dc:creator>
            <pubDate>Fri, 05 May 2023 12:21:35 GMT</pubDate>
            <atom:updated>2023-05-05T12:21:35.999Z</atom:updated>
            <content:encoded><![CDATA[<p>DATA CLEANING WITH SQL</p><p>Data obtained from the real world is usually messy, and this can lead to flawed conclusions and a waste of resources. Especially in a world of data-driven decision-making, it’s vital to ensure that your data is clean and prepared for analyses so you are making the most accurate insights to base your business decisions on.</p><p>Important business strategies, such as allocating funds and improving customer service, are often supported by data. When this data is questionable, the insights gathered from it and the consequential decisions can easily steer businesses down the wrong path. Data cleaning is required to improve the quality of information on which you base your decisions</p><p>One important skill in the field of data science is the ability to transform a disordered set of data into a well-organized and structured dataset, which occurs when initiating a new project or when multiple individuals are working on a database at the same time. Prioritized as one of the first steps in the data science life cycle, data cleaning is considered to be a necessity before moving on to the data analysis stage. By cleaning and organizing the data that you are working with, it is much easier to perform exploratory and more complex analyses later on.</p><p><strong>Why you should learn how to clean data with SQL</strong></p><p>Data cleaning can be done in a scripting language such as R or Python. Many BI platforms also have built-in operations for data cleaning.</p><p>The question is, what makes SQL so important even though there are other ways to clean data?</p><p>SQL is known for its uses as a Structured Querying Language. The SQL programming language is used to communicate with a dataset through querying and other forms of searching and manipulating data. SQL is also commonly used to clean and organize a dataset, especially when working within relational database management systems (RDBMS). By using the SQL programming language within a RDBMS, any data scientist can learn how to prepare their dataset for analysis and long-term storage through the execution of a series of tasks and functions which speeds up the process of data cleaning and organization.</p><p><strong>How to clean data with SQL</strong></p><p><strong>With so many methods of cleaning and organizing data, working with SQL and relational database management systems simplifies what could be a complex task.</strong></p><p><strong>Managing Metadata in SQL Databases:</strong> One of the key components of organizing and structuring a dataset is through managing the relevant metadata for your records. Metadata, or data about your data, is used to describe or name different parts of the dataset. Especially when working within a SQL database, which will require you to write queries to search through your data, you can retrieve object ids, names, and other information which is used to describe different parts of the dataset. By retrieving this information, you can also gain a deeper understanding of how the database is structured and where you may need to make modifications or do some data cleaning.</p><p><strong>Another effective way of cleaning data within a SQL database is by identifying the missing values within the dataset: </strong>Missing values are important to find because if there is some type of data that is missing from the dataset, the accuracy of your analysis will be greatly influenced. Data scientists can identify the NULL values in a SQL database to determine what values are missing and how that missing data can be rectified.</p><p><strong>Delete and Edit Records</strong></p><p>One of the methods of fixing missing values or duplicated values within a dataset is through deleting and/or editing the records in the database. While this would be a difficult process to do in a less sophisticated storage system, the process is simplified by using a SQL database that has multiple functions and features which allow you to modify records in the database after the data has already been collected.</p><p><strong>Here is an 8-step data cleaning process that will help you prepare your data:</strong></p><p><strong>Remove irrelevant data</strong>: What’s considered irrelevant data will vary based on the dataset. You need to figure out what data is relevant to your analyses and the questions you’re asking.</p><p>Let’s say I’m only interested in people who prefer to take chocolate ice cream. Data from customers who prefer vanilla will skew my results, and I should remove them from the dataset. I can filter them out with the following statement:</p><p>SELECT * FROM ice-cream_sales WHERE flavor = ‘Chocolate’; (the key word is ‘WHERE’)</p><p>With this statement, we’ll only keep the records where the Ice-cream_sales flavor is listed as “Chocolate”.</p><p>Below is the outcome of the Statement</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*5nPtF8wg1tjD7DNRKdJMXQ.png" /></figure><p>Now as a new bee in Data Analytics, in the course of trying to impress, I end up analyzing almost every detail of the dataset, therefore giving a clustered and confusing dashboard</p><p><strong>Remove duplicate data</strong>: Duplicate data is common to come across, whether your data is scraped, collected from surveys, or gathered from multiple sources. Duplicate data is inefficient to store and can cause your analysis to weigh duplicated records more heavily. Removing duplicate data is an important step in maintaining data quality and accuracy. The first step is to identify all the duplicate data, this can be done using the ‘GROUP BY’ clause, and also the ‘COUNT’ function to check the occurrence of a row</p><p>For example, executing the query below, we got that there are no duplicate records having occurrences greater than 1 in the table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*Hmp0j5D1F9XBQp7NAbpazA.png" /></figure><p>Overall, removing duplicate data is a critical step in maintaining data quality and ensuring that your dataset is accurate and reliable.</p><p><strong>Fix structural errors</strong>: In SQL, structural errors refer to issues with the structure or design of the database schema. Structural errors include strange naming conventions, typos, or incorrect capitalization. They usually arise when you measure or transfer data. This also has to do with incompatible Datatypes. Datatypes are incompatible when source and target table datatypes cannot be mapped to one another. For example, <em>binary-to-datetime</em> transfers are not allowed.</p><p>Here are other structural issues you might encounter:</p><p>● Unnecessary spaces at the beginning or the end of the string. For example, “ Apple “ should be trimmed to be “Apple”. This can be done with TRIM(), LTRIM(), or RTRIM() functions.</p><p>● Incorrect capitalization, such as “apple” as a company name should be “Apple”. This can be fixed with the INITCAP() function. UPPER() and LOWER() can turn texts into all uppercase or lowercase.</p><p>● Remove or replace some of the characters or terms. Suppose you want to turn “Apple Company” into “Apple Inc”. You can use REPLACE() to replace “Company” with “Inc”.</p><p><strong>Do type conversion</strong>: When you define SQL Server database tables, local variables, expressions, or parameters, you should specify what kind of data will be stored in those objects, such as text data, numbers, money, or dates. This attribute is called the SQL Server <strong>Data Type</strong>.</p><p>Type conversion is important to maintain consistency. Numbers, for example, are a common data type you’ll need to convert. They are often imputed as text, but for them to be processed and used for calculations, they need to appear as numerals.</p><p>Data type conversion is a method used <strong>to change the data type of a value into the other type</strong>. SQL Server can convert the data type of a value in two ways: <strong>implicitly or explicitly</strong>. SQL Server performs implicit conversion for their internal needs. <strong>For example,</strong> the following query will implicitly convert the string data type into the number type in <a href="https://www.javatpoint.com/sql-server-tutorial">SQL Server</a>:</p><p><strong>SELECT 5 * ‘5’ AS result;</strong></p><p>Here is the output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*qPriLwose6Hr1HATnKs4xw.png" /></figure><p>SQL Server returns the integer value because it will convert the lower data type into the higher one when using two values with different data types. This process indicates the implicit conversion of data types.</p><p>But you may face other cases, in which you need to manually, aka explicitly, perform a suitable data type conversion, to avoid the combination error. To perform the explicit data conversion, SQL Server provides us with three main conversion functions; <strong>CAST</strong>, <strong>CONVERT</strong>, and <strong>PARSE</strong>.</p><p>But I will concentrate on how to work with the CAST function</p><p>The CAST function enables the user to <strong>explicitly convert a value from one data type to the other type</strong> specified in the expression. The following syntax illustrates the CAST function in SQL Server:</p><p>CAST (expression <strong>AS</strong> data_type ( length ))</p><p>In the syntax, we have used the following parameters:</p><ul><li><strong>expression:</strong> It specifies a literal value or valid expression that we are going to convert into another type.</li><li><strong>data_type:</strong> It defines the target data type in which we want to convert the expression. It can include the following data types as an input: bigint, int, smallint, tinyint, bit, Decimal, numeric, money, float, datetime, char, nchar, varchar, nvarchar, text, ntext, binary, image, etc. We make sure that the input type should not be an alias data type.</li><li><strong>length:</strong> It is an optional parameter for specifying the length of the target data type. By default, its value is 30.</li></ul><p>Let us now understand how the CAST function works in Microsoft SQL Server, now Microsoft SQL Server is my favorite Relational Database Management System and so I mentioned it a lot here</p><p>SELECT CAST (5.25* ‘5’ AS int) AS result;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*McF4tbUFftfZInwoYNs3nw.png" /></figure><p>Another example of type conversion of STRING to a DATETIME with the help of a CAST function</p><p>SELECT CAST (‘2022–3–21’ AS DATETIME) AS result</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*UrNnaWnkW0nWEo1Z9BuG-Q.png" /></figure><p><strong>Handle missing data</strong>: How do you handle missing values in a dataset? Missing value in a dataset is a very common phenomenon in reality, yet a big problem in real-life scenarios. Now the thing is that null values must be distinguished from blank values.</p><p>● A <strong>null </strong>database field means that there is <strong>no value</strong> for a given record. It indicates the absence of a value.</p><p>● A <strong>blank </strong>database field means that there is<strong> a value</strong> for a given record, and this value is empty (for a string value) or 0 (for a numeric value).</p><p>These two cases must not be confused, otherwise, this could lead to misinterpreting the data and handling empty values as null values. I will use a table called ‘pizza_types’</p><p>Here is the raw dataset</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*7iVHQjdLpx9rmZW7bTOLTw.png" /></figure><p>This dataset is about Pizza sales, and from the ‘name’ column we can see that we have some NULL fields, which means that data was not captured for those particular fields</p><p>The first thing we want to do is to identify and visualize those NULL values. Now there are two ways to identify NULL values.</p><p>First, <strong>If you already know in which field or column there may be NULL values </strong>that you want to target, you can just apply the condition WHERE IS NULL on the field of interest. In our table, we can see that there the ‘name’ column has NULL values and so we can apply the WHERE to get the null values</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*MoUxbNGSGXU5nzJ9qMr9Qw.png" /></figure><p>Secondly, <strong>if you do not know the exact fields that contain the null values, </strong>or if you want to get a complete overview of null values in your dataset, you must start by getting a clear idea of the possible existence and the number of NULL values per column. To get this overview, you can use the following code snippet</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*uPULhKKGG2OH-dHJFpwaaQ.png" /></figure><p><strong>Deal with outliers: </strong>Dealing with outliers in a dataset is an important step in data preprocessing to ensure that statistical analyses are not skewed by extreme values. Outliers are observations that fall outside of the normal range of values in a dataset and can be caused by measurement errors, data entry errors, or natural variability.</p><p>Dealing with outliers in a dataset using SQL involves identifying and removing the outliers from the dataset. Here are some ways to do this:</p><ol><li>Identify outliers: Use SQL queries to identify the outliers in the dataset. For example, you can use the following query to identify values that are more than three standard deviations away from the mean:</li></ol><p><strong>SELECT * FROM table_name WHERE column_name &gt; (SELECT AVG(column_name) + 3 * STDDEV(column_name) FROM table_name)</strong></p><ol><li>Remove outliers: Once you have identified the outliers, you can use SQL queries to remove them from the dataset. For example, you can use the following query to remove all rows where the value in the column is an outlier:</li></ol><p><strong>DELETE FROM table_name WHERE column_name &gt; (SELECT AVG(column_name) + 3 * STDDEV(column_name) FROM table_name)</strong></p><ol><li>Replace outliers: Alternatively, you can replace outliers with a more appropriate value. For example, you can replace outliers with the median value of the column:</li></ol><p><strong>UPDATE table_name SET column_name = (SELECT MEDIAN(column_name) FROM table_name) WHERE column_name &gt; (SELECT AVG(column_name) + 3 * STDDEV(column_name) FROM table_name)</strong></p><ol><li>Another way to identify outliers is to sort the relevant values in both ascending and descending order. This allows you to quickly skim through the highest and lowest values. If you have a sense of what you are expecting from your data, this can help you quickly identify any unexpected values.</li></ol><p>To sort our values, we could use the following query.</p><p><strong>SELECT</strong> column_names</p><p><strong>FROM</strong> table_name</p><p><strong>ORDER</strong> <strong>BY</strong> column_name</p><p>By sorting we can easily identify anomalies within the data.</p><p>It is important to note that the specific SQL queries used to deal with outliers will depend on the structure and content of the dataset, as well as the goals of the analysis. Additionally, removing or replacing outliers in the dataset may result in the loss of valuable data, so it is important to carefully consider the potential impact of these actions on the analysis.</p><p><strong>Standardize/Normalize data</strong>: Standardizing or normalizing a dataset is an important step in data preprocessing that helps to prepare the data for analysis. Standardization and normalization are two techniques that are used to transform the values of variables in a dataset to have specific properties.</p><p>Standardization involves rescaling the data so that it has a mean of 0 and a standard deviation of 1. This is done by subtracting the mean of the dataset from each value and then dividing it by the standard deviation. Standardization is useful when the scale of the variables in the dataset is important, and you want to compare the relative differences between them.</p><p>Normalization involves rescaling the data so that it falls within a specific range, typically between 0 and 1. This is done by subtracting the minimum value of the dataset from each value and then dividing it by the range (i.e., the difference between the maximum and minimum values). Normalization is useful when the exact scale of the variables is less important than the relative differences between them.</p><p>And here are some queries on how to standardize and normalize a dataset using SQL:</p><p>— Standardization</p><p>SELECT (column_name — AVG(column_name)) / STDDEV(column_name) AS standardized_value</p><p>FROM table_name;</p><p>— Normalization</p><p>SELECT (column_name — MIN(column_name)) / (MAX(column_name) — MIN(column_name)) AS normalized_value</p><p>FROM table_name;</p><p><strong>Validate data: </strong>The last step is to validate your data. At the end of the data cleaning process, you need to ensure that your data is valid, accurate, complete, consistent, and uniform<strong>. </strong>Some questions you can ask yourself are:</p><p>● Do you have enough data?</p><p>● Does the data follow the constraints for its field?</p><p>● Does your clean data prove or disprove your theory before analysis? Does the data make sense?</p><p>Validating data can prevent false conclusions based on low-quality data.</p><p>There’s no single correct way to clean your data. These 8 steps are a good guideline for what procedure you should follow and what issues to look for in your data. While no data is perfect, monitoring errors and understanding where they’re coming from can make the data-cleaning process much easier in the future.</p><p>There’s no single correct way to clean your data. These 8 steps are a good guideline for what procedure you should follow and what issues to look for in your data. While no data is perfect, monitoring errors and understanding where they’re coming from can make the data-cleaning process much easier in the future.</p><p>Data with fewer errors make for happier clients, less frustrated employees, and more efficient business practices.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32b9a636d43a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>