<?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 NIRAJAN JHA on Medium]]></title>
        <description><![CDATA[Stories by NIRAJAN JHA on Medium]]></description>
        <link>https://medium.com/@nirajan_DataAnalyst?source=rss-45aeed2491e2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BZBzPqzG7xG2oNknmusr_w.jpeg</url>
            <title>Stories by NIRAJAN JHA on Medium</title>
            <link>https://medium.com/@nirajan_DataAnalyst?source=rss-45aeed2491e2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 16:13:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nirajan_DataAnalyst/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[Most Asked SQL Queries]]></title>
            <link>https://medium.com/@nirajan_DataAnalyst/most-asked-sql-queries-13c5715faa05?source=rss-45aeed2491e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/13c5715faa05</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[mysql-interview-question]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[sql-queries]]></category>
            <category><![CDATA[mysql-queries]]></category>
            <dc:creator><![CDATA[NIRAJAN JHA]]></dc:creator>
            <pubDate>Sat, 15 Mar 2025 15:50:27 GMT</pubDate>
            <atom:updated>2025-03-15T15:50:27.810Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6JRgFIeMRdWD2wxu85WyKA.jpeg" /></figure><p>Structured Query Language (SQL) is the backbone of database management and is widely used for querying, updating, and managing relational databases. Whether you are a beginner or an experienced data analyst, understanding the most commonly asked SQL queries is essential for interviews and day-to-day work. In this article, we will cover some important and basic SQL queries.</p><h4>1. Which query calculates the running total of the sales_amount column from the sales table, ordered by sale_date?</h4><pre>SELECT sale_date, sales_amount, <br>       SUM(sales_amount) OVER (ORDER BY sale_date) AS running_total<br>FROM sales;</pre><h4>2. How do you remove duplicate rows from a table called employees based on the employee_id column?</h4><pre>DELETE FROM employees<br>WHERE employee_id NOT IN (<br>    SELECT MIN(employee_id)<br>    FROM employees<br>    GROUP BY employee_id<br>);</pre><h4>3. Which SQL statement returns the second-highest salary from the employees table?</h4><pre>SELECT MAX(salary) AS second_highest_salary<br>FROM employees<br>WHERE salary &lt; (SELECT MAX(salary) FROM employees);</pre><h4>4. Which query retrieves all rows from tableA that do not have matching rows in tableB?</h4><pre>SELECT *<br>FROM tableA<br>WHERE NOT EXISTS (<br>    SELECT 1<br>    FROM tableB<br>    WHERE tableA.id = tableB.id<br>);</pre><h4>5. How do you rank employees by their salary in descending order, grouping by their department in SQL?</h4><pre>SELECT department_id, employee_id, salary,<br>       RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rank<br>FROM employees;</pre><h4>6. Which SQL query would return the top 3 departments by their total salary?</h4><pre>SELECT department_id, SUM(salary) AS total_salary<br>FROM employees<br>GROUP BY department_id<br>ORDER BY total_salary DESC<br>LIMIT 3;</pre><h4>7. How do you find duplicate rows in a table called orders based on the order_id column?</h4><pre>SELECT order_id, COUNT(*)<br>FROM orders<br>GROUP BY order_id<br>HAVING COUNT(*) &gt; 1;</pre><h4>8. Which query finds the percentage contribution of each employee’s salary to their department’s total salary?</h4><pre>SELECT department_id, employee_id, salary,<br>       (salary * 100.0) / SUM(salary) OVER (PARTITION BY department_id) AS percentage_contribution<br>FROM employees;</pre><h4>9. How can you find the most recent orders for each customer in the orders table?</h4><pre>SELECT customer_id, MAX(order_date) AS most_recent_order<br>FROM orders<br>GROUP BY customer_id;</pre><h4>10. Which query returns the first and last order date for each customer in the orders table?</h4><pre>SELECT customer_id, <br>       MIN(order_date) AS first_order_date,<br>       MAX(order_date) AS last_order_date<br>FROM orders<br>GROUP BY customer_id;</pre><h4>11. How do you calculate the difference in days between two date columns, start_date and end_date, in a table?</h4><pre>SELECT DATEDIFF(end_date, start_date) AS day_difference<br>FROM table_name;</pre><h4>12. Which SQL query finds the total revenue and average order value for each customer?</h4><pre>SELECT customer_id, <br>       SUM(order_value) AS total_revenue, <br>       AVG(order_value) AS average_order_value<br>FROM orders<br>GROUP BY customer_id;</pre><p>The queries covered in this article provide a strong foundation for handling real-world data challenges effectively. By continuously practicing and optimizing queries, you can enhance your SQL proficiency and efficiency.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13c5715faa05" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic Excel Skills Required for a Data Analyst]]></title>
            <link>https://medium.com/@nirajan_DataAnalyst/basic-excel-skills-required-for-a-data-analyst-ced3e1327114?source=rss-45aeed2491e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/ced3e1327114</guid>
            <category><![CDATA[ms-excel]]></category>
            <category><![CDATA[excel-for-data-analysis]]></category>
            <category><![CDATA[excel]]></category>
            <category><![CDATA[data-analyst]]></category>
            <category><![CDATA[excel-tutorial]]></category>
            <dc:creator><![CDATA[NIRAJAN JHA]]></dc:creator>
            <pubDate>Fri, 14 Mar 2025 14:54:29 GMT</pubDate>
            <atom:updated>2025-03-14T14:54:29.988Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*nSL3FIvdNywPwYV8yJdq3w.jpeg" /></figure><p>Microsoft Excel is one of the most essential tools for a data analyst. While advanced analytics and business intelligence tools like Python, R, and SQL are becoming more popular, Excel remains a fundamental skill for organizing, analyzing, and visualizing data efficiently. In this article, we will explore the key Excel functions and features that every data analyst should know.</p><h3>1. Data Cleaning and Preparation</h3><p>Data cleaning is a crucial step in any data analysis process. Excel provides several functions to clean and prepare data effectively:</p><ul><li><strong>Remove Duplicates</strong>: Helps in eliminating redundant data.</li><li><strong>Text-to-Columns</strong>: Splits data into multiple columns based on a delimiter.</li><li><strong>TRIM()</strong>: Removes extra spaces from text.</li><li><strong>CLEAN()</strong>: Removes non-printable characters.</li><li><strong>Find and Replace</strong>: Helps in replacing incorrect or missing values.</li><li><strong>Data Validation</strong>: Restricts user input to predefined criteria to maintain data accuracy.</li></ul><h3>2. Basic Formulas and Functions</h3><p>Excel functions simplify complex calculations and automate tasks. Some of the most important functions include:</p><ul><li><strong>SUM()</strong>: Calculates the total of a range of values.</li><li><strong>SUMIF()</strong>: Adds sum of values that meet a specified condition.</li><li><strong>AVERAGE()</strong>: Finds the mean of a range.</li><li><strong>AVERAGEIF()</strong>: Finds the mean of a range that meet a specified condition.</li><li><strong>COUNT()</strong>: Counts numerical values in a range.</li><li><strong>COUNTA()</strong>: Counts non-empty cells.</li><li><strong>COUNTIF()</strong>: Counts the number of cells that meet a specific condition.</li><li><strong>ISBLANK()</strong>: Checks if a cell is empty.</li><li><strong>IF()</strong>: Performs logical tests and returns values based on conditions.</li></ul><h3>3. Text Functions</h3><p>Text functions are useful for formatting and manipulating textual data:</p><ul><li><strong>LEFT(), RIGHT(), MID()</strong>: Extracts parts of a text string.</li><li><strong>LEN()</strong>: Counts the number of characters in a string.</li><li><strong>CONCATENATE() / CONCAT()</strong>: Joins multiple text values into one.</li><li><strong>TEXT()</strong>: Formats numbers as text with specific formatting.</li><li><strong>SEARCH() / FIND()</strong>: Finds the position of a substring within a text string.</li><li><strong>PROPER(), UPPER(), LOWER()</strong>: Changes text case.</li></ul><h3>4. Data Visualization</h3><p>Visual representation of data is key for analysis and reporting. Excel provides various tools for effective data visualization:</p><ul><li><strong>Charts and Graphs</strong>: Bar charts, line charts, pie charts, and scatter plots.</li><li><strong>Pivot Tables &amp; Pivot Charts</strong>: Summarizes large datasets dynamically.</li><li><strong>Conditional Formatting</strong>: Highlights data based on specific rules.</li></ul><h3>5. Pivot Tables and Power Query</h3><p>Pivot Tables are essential for summarizing and analyzing large datasets. Key aspects include:</p><ul><li><strong>Creating Pivot Tables</strong>: Summarizes large amounts of data quickly.</li><li><strong>Grouping Data</strong>: Helps in organizing data into meaningful categories.</li><li><strong>Using Power Query</strong>: Automates data transformation and cleaning.</li></ul><h3>6. Lookup and Reference Functions</h3><p>Efficient data retrieval is critical in data analysis.</p><ul><li><strong>VLOOKUP() &amp; HLOOKUP()</strong>: Used for searching data in tables.</li><li><strong>INDEX() &amp; MATCH()</strong>: More flexible than VLOOKUP for data lookup.</li><li><strong>XLOOKUP()</strong>: A more advanced lookup function replacing VLOOKUP and HLOOKUP.</li><li><strong>CHOOSE()</strong>: Selects a value from a list based on an index number.</li><li><strong>OFFSET()</strong>: Returns a reference to a range that is offset from a starting cell.</li></ul><h3>7. Error Handling Functions</h3><p>Error handling improves the reliability of reports:</p><ul><li><strong>IFERROR()</strong>: Returns a custom value if an error occurs.</li><li><strong>ISERROR()</strong>: Checks whether a value is an error.</li><li><strong>IFNA()</strong>: Returns a custom value if the error is specifically #N/A.</li></ul><h3>8. Macros and Automation</h3><p>For repetitive tasks, Excel allows automation through:</p><ul><li><strong>Recording Macros</strong>: Automates repetitive tasks without coding.</li><li><strong>VBA (Visual Basic for Applications)</strong>: Advanced automation for complex tasks.</li></ul><h3>Conclusion</h3><p>Excel remains an indispensable tool for data analysts, providing robust capabilities for data management, analysis, and visualization. While more advanced tools are available, Excel continues to be a vital skill for analysts across industries. By leveraging these key Excel features, data analysts can streamline workflows, generate meaningful insights, and contribute to informed business strategies.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ced3e1327114" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top Data Analyst Interview Questions]]></title>
            <link>https://medium.com/@nirajan_DataAnalyst/top-data-analyst-interview-questions-2c63ad82acb3?source=rss-45aeed2491e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c63ad82acb3</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-analyst]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[interview-questions]]></category>
            <dc:creator><![CDATA[NIRAJAN JHA]]></dc:creator>
            <pubDate>Wed, 12 Mar 2025 16:57:54 GMT</pubDate>
            <atom:updated>2025-03-12T16:57:54.362Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*E23YDULpkdp2H41bcu7K-Q.jpeg" /></figure><h3>1. What is data analytics?</h3><p>Data analytics is a process of analyzing, cleaning, transforming and modeling data to extract useful information, draw conclusion and make decisions.</p><h3>2. What is qualitative and quantitative data?</h3><p><strong>Qualitative data</strong> is non-numerical data like text or image.</p><p><strong>Quantitative data</strong> is numerical data like measurements or counts.</p><h3>3. What is data warehouse?</h3><p>Data warehouse is a large storage system where all data from different sources is stored together in an organized way. It helps businesses make better and informed decisions by analyzing historical data.</p><h3>4. What is data wrangling?</h3><p>It is also known as data munging or data cleaning. It means cleaning and organizing raw data so that it is ready for further analysis. This includes removing duplicates, fixing missing values, correcting errors and transforming data into a useful format.</p><h3>5. What is data mining?</h3><p>It is about finding patterns, trends or useful information hidden in large sets of data.</p><h3>6. What is data modeling?</h3><p>It is a process of creating a visual representation or blueprint of how data is organized and structured in system. It shows relationships between different types of data.</p><h3>7. What is data visualization?</h3><p>It is a process of displaying data in a graphical format such as charts, graphs and maps to make it easier to understand, even to non-technical people.</p><h3>8. What is ETL?</h3><p>ETL stands for Extract, Transform and Load. It is a process for retrieving data from various sources, transforming it into a usable format and loading it into a data warehouse for analysis.</p><h3>9. What is the difference between structured and unstructured data??</h3><p><strong>Structured data: </strong>It is organized in a predefined format, such as tables in a relational database. Examples are customer records, sales data.</p><p><strong>Unstructured data: </strong>It lacks a fixed format and stores data in flexible format like documents. Examples are images, videos, emails and social media posts.</p><h3>10. What is the difference between OLAP and OLTP??</h3><p><strong>OLAP (Online Analytical Processing):</strong> It is a tool used in data warehousing for complex queries and analytics on historical data to quickly analyze data such as Sales Analysis Dashboard, Financial Forecasting, and Customer Segmentation.</p><p><strong>OLTP (Online Transaction Processing):</strong> It is a tool designed to handle real-time transactional data such as banking transactions, e-commerce purchases, and airline bookings..</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c63ad82acb3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object-Oriented Programming(OOP)]]></title>
            <link>https://medium.com/@nirajan_DataAnalyst/object-oriented-programming-oop-dd46c6a9d2f6?source=rss-45aeed2491e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd46c6a9d2f6</guid>
            <category><![CDATA[objectorientedprogramming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[class-and-object]]></category>
            <category><![CDATA[oop-concepts]]></category>
            <dc:creator><![CDATA[NIRAJAN JHA]]></dc:creator>
            <pubDate>Mon, 02 Sep 2024 17:10:32 GMT</pubDate>
            <atom:updated>2024-09-02T17:10:32.208Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*GSiZD9FtJjdq98PuK6_-zA.png" /></figure><p>In Python, object-oriented programming (OOP) is a programming paradigm or approach that uses objects and classes to design and organize code. In simpler terms, OOP is a way to structure programs by bundling related properties and behaviors into individual objects, which makes the code more modular, reusable, and easier to understand.</p><p><strong>Key OOP Principles:</strong></p><p><strong>1. Abstraction</strong> — Expose only what is necessary and hide all unnecessary details. This allows us to focus on what an object does instead of how it does it.</p><p><em>Example:</em> When we use a remote control, we don’t need to know how it sends signals to the TV; only thing we care about is pressing the right button to change the channel.</p><p><strong>2. Encapsulation</strong> — Hide all unnecessary complex processing by packing all related data and methods (functions) into a single unit called a class. This helps in keeping the code clean and organized.</p><p><em>Example:</em> Consider a car. Here, we interact with it using pedals and a steering wheel, but the complex internal workings (like the engine) are hidden from us.</p><p><strong>3. Inheritance</strong> — The process by which one class (child class) inherits properties and behaviors (methods) from another class (parent class). This allows for code reusability.</p><p><em>Example:</em> If we have a class called Animal, a Dog class could inherit from it, meaning that Dog would automatically have the basic traits of Animal.</p><p><strong>4. Polymorphism</strong> — The ability of different classes to be treated as instances of the same class through inheritance. It also refers to the ability to use a single method in different ways.</p><p><em>Example:</em> Consider the concept of shape where a Circle and Rectangle are both shapes. A method draw() could be implemented differently for each shape but can be called in the same way.</p><h4>What are Objects and Classes?</h4><p><strong>Class:</strong> A class is a blueprint or template for creating objects. It defines a set of attributes (data) and methods (functions) that the created objects will have.</p><p><em>Example:</em> Suppose we want to create several cakes. We start with a recipe (class) that tells us the ingredients (attributes) and the steps (methods) needed to make a cake.</p><p><strong>Object:</strong> An object is an instance of a class. Each object can have its own unique properties and can use the methods defined by its class.</p><p><em>Example:</em> If Cake is the class, then chocolate_cake and vanilla_cake would be objects created from that class.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd46c6a9d2f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Skills Required To Be Data Analyst]]></title>
            <link>https://medium.com/@nirajan_DataAnalyst/skills-required-to-be-data-analyst-d2b3c78ab087?source=rss-45aeed2491e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2b3c78ab087</guid>
            <category><![CDATA[job-skills]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analyst-skill]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-analytics]]></category>
            <dc:creator><![CDATA[NIRAJAN JHA]]></dc:creator>
            <pubDate>Wed, 03 Jul 2024 14:32:04 GMT</pubDate>
            <atom:updated>2024-07-03T14:32:04.190Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6mYhJTx1-TVNFOaKlQ15Ag.png" /></figure><p>In the age of data-driven decision-making, data analysts have become indispensable assets for companies across various industries. They interpret complex data and provide actionable insights, driving strategic business decisions. To excel as a data analyst, a blend of technical and soft skills is essential. Here, I will explore the crucial skills needed to succeed in this field.</p><h3>A. Technical Skills</h3><p>These skills involve the use of specialized tools, software, and methodologies to manipulate, analyze, and visualize data. Here is a deeper look into the important technical skills for data analysts:</p><p><strong>1. Excel:</strong> Excel is a fundamental tool for data analysis, widely used across industries. Proficiency involves mastering advanced functions, PivotTables, data analysis tools, and VBA (Visual Basic for Applications) for automation. These capabilities enable data analysts to efficiently handle and analyze large datasets.</p><p><strong>2. SQL:</strong> Structured Query Language (SQL) is critical for retrieving and manipulating data in relational databases. Data analysts must be skilled in writing complex queries to extract data, perform data manipulation, and generate reports. Understanding joins, subqueries, window functions, and indexing is essential for optimizing query performance.</p><p><strong>3. Python:</strong> Python’s versatility and powerful libraries make it a staple for data analysts. Key libraries like Pandas and NumPy are vital for data manipulation and analysis, while Matplotlib and Seaborn are used for data visualization. Additionally, Scikit-learn offers robust tools for machine learning.</p><p><strong>4. Data Visualization:</strong> Communicating insights effectively is crucial, and data visualization plays a key role. Proficiency in tools like Tableau and Power BI, along with Python libraries like Matplotlib and Seaborn, allows data analysts to create interactive and insightful visualizations. This helps in transforming complex data into comprehensible information.</p><p><strong>5. Data Cleaning and Preprocessing:</strong> Data analysts often spend significant time cleaning and preprocessing data. Skills in handling missing values, data transformation, and feature engineering are essential to ensure data quality and accuracy before analysis.</p><p><strong>6. Machine Learning:</strong> While not every data analyst specializes in machine learning, having a basic understanding is beneficial. Skills in building and evaluating models such as linear regression, logistic regression, decision trees, and random forests help in making predictive analyses and informed decisions.</p><p><strong>7. Statistical Analysis:</strong> A solid grasp of statistical concepts is vital for data analysis. Skills in hypothesis testing, A/B testing, regression analysis, and probability theory enable data analysts to make informed decisions and validate their findings.</p><h3>B. Soft Skills</h3><p>These skills are less about technical knowledge and more about how you apply that knowledge and interact within a professional environment. Key soft skills for data analysts include:</p><p><strong>1. Analytical Thinking:</strong> Analytical thinking involves breaking down complex problems and identifying patterns and relationships within the data. This skill is crucial for making sense of large datasets and deriving meaningful insights.</p><p><strong>2. Attention to Detail:</strong> Ensuring data accuracy and precision is paramount. Attention to detail helps identify errors, inconsistencies, and anomalies in the data, leading to more reliable results.</p><p><strong>3. Communication:</strong> Effective communication is essential for presenting data insights to stakeholders. Data analysts must explain their findings clearly and concisely to both technical and non-technical audiences, often using visual aids like charts and graphs.</p><p><strong>4. Problem-Solving:</strong> Data analysts are often tasked with solving complex business problems. Strong problem-solving skills involve using data to identify issues, develop solutions, and implement strategies that drive positive outcomes.</p><p><strong>5. Collaboration:</strong> Collaboration is key, as data analysts frequently work in teams. Effective collaboration skills are necessary for working with colleagues from various departments, including IT, marketing, finance, and operations, to gather requirements and deliver actionable insights.</p><p><strong>6. Time Management:</strong> Managing multiple tasks and meeting deadlines is a critical aspect of a data analyst’s role. Time management skills help prioritize tasks, allocate resources efficiently, and ensure timely project delivery.</p><p><strong>7. Adaptability:</strong> The field of data analysis is constantly evolving with new tools and technologies. Adaptability is the ability to learn and apply new skills quickly, keeping up with industry trends and advancements.</p><p><strong>8. Critical Thinking:</strong> Critical thinking involves evaluating data sources and methodologies for validity and reliability. This skill helps data analysts question assumptions, assess the credibility of their analyses, and make informed decisions based on sound reasoning.</p><h3>Conclusion</h3><p>A successful data analyst must possess a diverse skill set that combines technical expertise with strong interpersonal abilities. Mastering these skills enables data analysts to provide valuable insights that drive business success. As the demand for data-driven decision-making continues to grow, so does the need for skilled data analysts who can navigate the complexities of data and turn it into actionable intelligence. Whether you are starting your journey as a data analyst or looking to advance your career, focusing on these key skills will help you thrive in this dynamic and rewarding field.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2b3c78ab087" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MySQL Common Table Expression (CTE)]]></title>
            <link>https://medium.com/@nirajan_DataAnalyst/mysql-common-table-expression-cte-fe25bcd38e61?source=rss-45aeed2491e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe25bcd38e61</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[common-table-expressions]]></category>
            <category><![CDATA[with]]></category>
            <category><![CDATA[cte]]></category>
            <dc:creator><![CDATA[NIRAJAN JHA]]></dc:creator>
            <pubDate>Sun, 09 Jun 2024 12:41:54 GMT</pubDate>
            <atom:updated>2024-06-09T12:41:54.646Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*cTrGlU-fVMmZDhNXqRp4Pw.png" /></figure><p>In MySQL, Common Table Expressions (CTEs) are a powerful feature that enhances query readability and structure. CTEs allow to create temporary result sets that can be referenced within a <strong>SELECT</strong>, <strong>INSERT</strong>, <strong>UPDATE</strong>, or <strong>DELETE</strong> statement. CTEs, which were first introduced in <strong>MySQL 8.0</strong>, make complex queries easier to manage and understand, breaking them down into simpler parts. This article will delve into the concept of CTEs in MySQL, exploring their syntax, benefits, and practical examples to illustrate their utility in real-world scenarios.</p><h3>What is a CTE?</h3><p>A Common Table Expression (CTE) is a named temporary result set that you can reference within a <strong>SELECT</strong>, <strong>INSERT</strong>, <strong>UPDATE</strong>, or <strong>DELETE</strong> statement. CTEs are defined using the <strong>WITH</strong> keyword, followed by a query that generates the result set. CTEs enable user to more easily write &amp; maintain complex queries via increased readability &amp; simplification.</p><h3>Syntax</h3><p>The basic syntax for a CTE is as follows:</p><pre>WITH cte_name (column1, column2, ...)<br>AS<br>(<br>    -- CTE Query<br>    SELECT ...<br>)<br>SELECT ...<br>FROM cte_name;</pre><h3>Benefits of Using CTEs</h3><ul><li><strong>Improved Readability</strong>: CTEs allow you to break down complex queries into simpler, more readable parts.</li><li><strong>Reusability</strong>: A CTE can be referenced multiple times within the same query, reducing redundancy.</li><li><strong>Modularity</strong>: CTEs enable modular query design, making maintenance and updates easier.</li><li><strong>Recursive Queries</strong>: Recursive CTEs simplify writing hierarchical or tree-structured data queries.</li></ul><h3>Types of CTEs</h3><p>There are two types of CTEs i.e. non-recursive and recursive.</p><h4>1. Non-Recursive CTE</h4><p>A non-recursive CTE is a Common Table Expression that does not refer to itself. It is used to simplify complex queries by breaking them down into smaller, more manageable parts.</p><p>Let’s start with a simple example. Suppose we have a table <strong>employees</strong> with the following structure.</p><pre>CREATE TABLE employees (<br>    employee_id INT PRIMARY KEY,<br>    first_name VARCHAR(50),<br>    last_name VARCHAR(50),<br>    department_id INT,<br>    salary DECIMAL(10, 2)<br>);<br><br>INSERT INTO employees (employee_id, first_name, last_name, department_id, salary) VALUES<br>(1, &#39;John&#39;, &#39;Doe&#39;, 1, 5000),<br>(2, &#39;Jane&#39;, &#39;Smith&#39;, 1, 6000),<br>(3, &#39;Jim&#39;, &#39;Brown&#39;, 2, 5500),<br>(4, &#39;Jake&#39;, &#39;White&#39;, 2, 7000),<br>(5, &#39;Jill&#39;, &#39;Green&#39;, 3, 7500);</pre><p>We want to find all employees with a salary greater than <strong>$5500</strong>. Using a CTE, we can write.</p><pre>WITH HighSalaryEmployees AS (<br>    SELECT employee_id, first_name, last_name, salary<br>    FROM employees<br>    WHERE salary &gt; 5500<br>)<br>SELECT *<br>FROM HighSalaryEmployees;</pre><p>This query first creates a CTE named <strong>HighSalaryEmployees</strong> that selects employees with a salary greater than <strong>$5500</strong>. Then, it selects all columns from this CTE.</p><h4>2. Recursive CTE Example</h4><p>A recursive CTE is a Common Table Expression that references itself. It is particularly useful for querying hierarchical or tree-structured data, such as organizational charts or folder structures.</p><p>Consider a table <strong>employees_hierarchy</strong> representing an organizational hierarchy.</p><pre>CREATE TABLE employees_hierarchy (<br>    employee_id INT PRIMARY KEY,<br>    employee_name VARCHAR(50),<br>    manager_id INT<br>);<br><br>INSERT INTO employees_hierarchy (employee_id, employee_name, manager_id) VALUES<br>(1, &#39;John&#39;, NULL),<br>(2, &#39;Jane&#39;, 1),<br>(3, &#39;Jim&#39;, 1),<br>(4, &#39;Jake&#39;, 2),<br>(5, &#39;Jill&#39;, 2);</pre><p>To find all employees reporting to <strong>John</strong>, including indirect reports, we use a recursive CTE.</p><pre>WITH RECURSIVE EmployeeTree AS (<br>    SELECT employee_id, employee_name, manager_id<br>    FROM employees_hierarchy<br>    WHERE manager_id IS NULL<br>    UNION ALL<br>    SELECT e.employee_id, e.employee_name, e.manager_id<br>    FROM employees_hierarchy e<br>    INNER JOIN EmployeeTree et ON e.manager_id = et.employee_id<br>)<br>SELECT *<br>FROM EmployeeTree;</pre><p>In this example, the recursive CTE <strong>EmployeeTree</strong> starts with employees who have no manager (<strong>John</strong>). It then recursively joins the <strong>employees_hierarchy</strong> table to find all employees reporting to <strong>John</strong> directly or indirectly.</p><h3>Advanced Usage of CTEs</h3><h4>1. Multiple CTEs</h4><p>CTEs can be chained together, allowing the results of one CTE to be used in another. This is useful for breaking down complex queries into more manageable steps.</p><pre>WITH<br>HighSalaryEmployees AS (<br>    SELECT employee_id, first_name, last_name, salary<br>    FROM employees<br>    WHERE salary &gt; 5500<br>),<br>DepartmentSalaries AS (<br>    SELECT department_id, AVG(salary) AS avg_salary<br>    FROM employees<br>    GROUP BY department_id<br>)<br>SELECT e.first_name, e.last_name, d.avg_salary<br>FROM HighSalaryEmployees e<br>JOIN DepartmentSalaries d ON e.department_id = d.department_id;</pre><h4>2. CTEs with Aggregate Functions</h4><p>CTEs can simplify the process of using aggregate functions. For instance, you can calculate the total sales per department and then filter departments with total sales above a certain threshold.</p><pre>WITH DepartmentSales AS (<br>    SELECT department_id, SUM(sales) AS total_sales<br>    FROM sales<br>    GROUP BY department_id<br>)<br>SELECT *<br>FROM DepartmentSales<br>WHERE total_sales &gt; 10000;</pre><h4>3. Using CTEs in Data Transformation</h4><p>CTEs are handy for transforming data before using it in further queries. For example, you can format dates or clean up strings within a CTE.</p><pre>WITH FormattedDates AS (<br>    SELECT employee_id, DATE_FORMAT(hire_date, &#39;%Y-%m-%d&#39;) AS formatted_date<br>    FROM employees<br>)<br>SELECT *<br>FROM FormattedDates;</pre><h3>Practical Examples of CTEs</h3><h4>1. Aggregating Data with CTEs</h4><p>CTEs can help aggregate data in a structured way. For example, calculating the average salary by department.</p><pre>WITH DepartmentAvgSalaries AS (<br>    SELECT department_id, AVG(salary) AS avg_salary<br>    FROM employees<br>    GROUP BY department_id<br>)<br>SELECT department_id, avg_salary<br>FROM DepartmentAvgSalaries;</pre><h4>2. Combining CTEs with Window Functions</h4><p>Combining CTEs with window functions can provide powerful analytical capabilities. For example, calculating running totals or moving averages.</p><pre>WITH SalesData AS (<br>    SELECT employee_id, sales, sale_date<br>    FROM sales<br>)<br>SELECT employee_id, sales, sale_date,<br>       SUM(sales) OVER (ORDER BY sale_date) AS running_total<br>FROM SalesData;</pre><h4>3. CTEs for Data Cleansing</h4><p>CTEs can be used to clean data before further processing. For example, removing duplicates or correcting data anomalies.</p><pre>WITH CleanedData AS (<br>    SELECT DISTINCT *<br>    FROM raw_data<br>)<br>SELECT *<br>FROM CleanedData;</pre><h3>Comparison with Derived Tables and Subqueries</h3><h4>1. CTE vs Derived Tables</h4><p>Derived tables are subqueries in the FROM clause. While both derived tables and CTEs can achieve similar results, CTEs offer better readability and reusability.</p><pre>-- Derived Table Example<br>SELECT d.department_id, d.avg_salary<br>FROM (<br>    SELECT department_id, AVG(salary) AS avg_salary<br>    FROM employees<br>    GROUP BY department_id<br>) d;<br><br>-- Equivalent CTE Example<br>WITH DepartmentAvgSalaries AS (<br>    SELECT department_id, AVG(salary) AS avg_salary<br>    FROM employees<br>    GROUP BY department_id<br>)<br>SELECT department_id, avg_salary<br>FROM DepartmentAvgSalaries;</pre><h4>2. CTE vs Subqueries</h4><p>Subqueries can be nested in various parts of a SQL statement. CTEs often provide a clearer and more maintainable alternative.</p><pre>-- Subquery Example<br>SELECT employee_id, first_name, last_name<br>FROM employees<br>WHERE salary &gt; (SELECT AVG(salary) FROM employees);<br><br>-- Equivalent CTE Example<br>WITH AvgSalary AS (<br>    SELECT AVG(salary) AS avg_salary<br>    FROM employees<br>)<br>SELECT employee_id, first_name, last_name<br>FROM employees, AvgSalary<br>WHERE salary &gt; avg_salary;</pre><h4>When to Use CTEs over Subqueries</h4><p>CTEs are preferred when:</p><ul><li>You need to break down complex queries.</li><li>You have reusable query parts.</li><li>You need recursive queries.</li></ul><h3>Conclusion</h3><p>Common Table Expressions (CTEs) in MySQL offer a versatile and powerful way to handle complex queries, making your SQL code more readable and maintainable. By using CTEs, you can break down intricate queries into manageable parts, reuse query logic, and perform recursive operations with ease. Whether you’re filtering data, performing aggregations, or dealing with hierarchical structures, CTEs can significantly enhance your SQL querying capabilities. Embrace CTEs to write cleaner, more efficient, and more understandable SQL queries.</p><h3>Thanks for Reading!</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe25bcd38e61" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Comprehensive Guide On Triggers In MySQL]]></title>
            <link>https://medium.com/@nirajan_DataAnalyst/a-comprehensive-guide-on-triggers-in-mysql-257057e10401?source=rss-45aeed2491e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/257057e10401</guid>
            <category><![CDATA[triggers-in-sql]]></category>
            <category><![CDATA[trigger]]></category>
            <category><![CDATA[triggers-in-mysql]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[NIRAJAN JHA]]></dc:creator>
            <pubDate>Fri, 07 Jun 2024 17:01:17 GMT</pubDate>
            <atom:updated>2024-06-07T17:01:17.301Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*k6Mc3LI2QPdJyjKLGfuUmA.png" /></figure><p>MySQL is one of the most popular relational database management systems. One of its powerful features is the use of triggers, which are special procedures that automatically execute in response to certain events on a table. In this article, I will explore the concept of triggers in MySQL, understand their importance and learn how to create them illustrate their functionality.</p><h3>What are Triggers?</h3><p>Triggers are the SQL codes that are automatically executed in response to the certain events on a particular table. These events can be an INSERT, UPDATE, or DELETE operation on a table. Triggers ensure data integrity and consistency.</p><h3>Importance of Triggers in MySQL</h3><ol><li><strong>Maintaining Data Integrity : </strong>Automatically enforces data validation and consistency rules.</li><li><strong>Automating Routine Tasks</strong>: Reduces manual intervention by automating repetitive database operations.</li><li><strong>Data Synchronization</strong>: Keeps related tables consistent by reflecting changes automatically.</li><li><strong>Consistency Across Applications</strong>: Ensures uniform enforcement of rules and data integrity, regardless of the data source.</li><li><strong>Real-Time Auditing and Logging</strong>: Provides a detailed history of data modifications for auditing purposes.</li></ol><h4>Types of Triggers</h4><p>In MySQL, triggers are classified based on the timing of their execution.</p><p><strong>i. Before Trigger</strong>: Executes before the triggering event occurs.</p><p><strong>ii After Trigger</strong>: Executes after the triggering event occurs.</p><h3>Creating a Trigger</h3><p>To create a trigger, the <strong>Create Trigger</strong> statement is used.</p><p>The basic syntax is as follows:</p><pre>CREATE TRIGGER trigger_name<br>{BEFORE | AFTER} {INSERT | UPDATE | DELETE}<br>ON table_name<br>FOR EACH ROW<br>BEGIN<br>    -- SQL statements<br>END;</pre><p>Let’s explore different examples to understand how triggers work in practice.</p><h3>Example 1: Auditing Changes</h3><p>Suppose we have two tables: <strong>employees</strong> and <strong>employees_audit</strong>. We want to track any changes made to the <strong>employees</strong> table in the e<strong>mployees_audit</strong> table.</p><h4>1. Creating the Tables</h4><pre>CREATE TABLE employees (<br>    id INT AUTO_INCREMENT PRIMARY KEY,<br>    name VARCHAR(100),<br>    position VARCHAR(100),<br>    salary DECIMAL(10, 2)<br>);<br><br>CREATE TABLE employees_audit (<br>    audit_id INT AUTO_INCREMENT PRIMARY KEY,<br>    employee_id INT,<br>    old_salary DECIMAL(10, 2),<br>    new_salary DECIMAL(10, 2),<br>    change_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP<br>);</pre><h4>2. Creating the Trigger</h4><pre>CREATE TRIGGER after_employee_update<br>AFTER UPDATE ON employees<br>FOR EACH ROW<br>BEGIN<br>    INSERT INTO employees_audit (employee_id, old_salary, new_salary)<br>    VALUES (OLD.id, OLD.salary, NEW.salary);<br>END;</pre><h4>Explanation</h4><ul><li>The <strong>CREATE TRIGGER after_employee_update</strong> statement defines a trigger named <strong>after_employee_update</strong>.</li><li>The <strong>AFTER UPDATE ON employees</strong> clause specifies that the trigger activates after an update operation on the <strong>employees</strong> table.</li><li>The <strong>FOR EACH ROW</strong> clause ensures that the trigger runs once for each row affected by the update.</li><li>Inside the trigger, the <strong>INSERT INTO employees_audit</strong> statement records the changes, using <strong>OLD</strong> and <strong>NEW</strong> to refer to the old and new values of the updated row.</li></ul><h4>Testing the Trigger</h4><p>Let’s update an employee’s salary and see the trigger in action.</p><pre>UPDATE employees<br>SET salary = 75000<br>WHERE id = 1;</pre><p>Now, check the <strong>employees_audit</strong> table:</p><pre>SELECT * FROM employees_audit;</pre><p>You should see a new row recording the old and new salaries of the updated employee.</p><h3>Example 2: Preventing Invalid Data</h3><p>Imagine we have a table <strong>products</strong> and we want to ensure that the <strong>price</strong> field is never set to a negative value.</p><h4>1. Creating the Tables</h4><pre>CREATE TABLE products (<br>    product_id INT AUTO_INCREMENT PRIMARY KEY,<br>    product_name VARCHAR(100),<br>    price DECIMAL(10, 2)<br>);</pre><h4>2. Creating the Trigger</h4><pre>CREATE TRIGGER before_product_insert<br>BEFORE INSERT ON products<br>FOR EACH ROW<br>BEGIN<br>    IF NEW.price &lt; 0 THEN<br>        SET NEW.price = 0;<br>    END IF;<br>END;</pre><h4>Explanation</h4><ul><li>The <strong>CREATE TRIGGER before_product_insert</strong> statement defines a trigger named <strong>before_product_insert</strong>.</li><li>The <strong>BEFORE INSERT ON products</strong> clause specifies that the trigger activates before an insert operation on the <strong>products</strong> table.</li><li>Inside the trigger, the <strong>IF NEW.price &lt; 0 THEN SET NEW.price = 0; END IF;</strong> statement ensures that if a new product is inserted with a negative price, it is set to zero instead.</li></ul><h3>Example 3: Synchronizing Tables</h3><p>Consider a scenario where we have two tables: <strong>orders</strong> and <strong>inventory</strong>. We want to decrease the inventory count automatically whenever a new order is placed.</p><h4>1. Creating the Tables</h4><pre>CREATE TABLE inventory (<br>    item_id INT AUTO_INCREMENT PRIMARY KEY,<br>    item_name VARCHAR(100),<br>    stock INT<br>);<br><br>CREATE TABLE orders (<br>    order_id INT AUTO_INCREMENT PRIMARY KEY,<br>    item_id INT,<br>    quantity INT,<br>    FOREIGN KEY (item_id) REFERENCES inventory(item_id)<br>);</pre><h4>2. Creating the Trigger</h4><pre>CREATE TRIGGER after_order_insert<br>AFTER INSERT ON orders<br>FOR EACH ROW<br>BEGIN<br>    UPDATE inventory<br>    SET stock = stock - NEW.quantity<br>    WHERE item_id = NEW.item_id;<br>END;</pre><h4>Explanation</h4><ul><li>The <strong>CREATE TRIGGER after_order_insert</strong> statement defines a trigger named <strong>after_order_insert</strong>.</li><li>The <strong>AFTER INSERT ON orders</strong> clause specifies that the trigger activates after an insert operation on the orders table.</li><li>Inside the trigger, the <strong>UPDATE inventory SET stock = stock - NEW.quantity WHERE item_id = NEW.item_id;</strong> statement decreases the stock of the ordered item by the quantity ordered.</li></ul><h3>Conclusion</h3><p>Triggers in MySQL are a powerful tool for automating tasks, maintaining data integrity, and enforcing business rules at the database level. By automating routine tasks, ensuring data consistency, and enforcing business rules, triggers empower you to maintain a smooth and error-free database environment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=257057e10401" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MongoDB — NoSQL Database]]></title>
            <link>https://medium.com/@nirajan_DataAnalyst/mongodb-nosql-database-5cb0050dc760?source=rss-45aeed2491e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cb0050dc760</guid>
            <category><![CDATA[mongodb-atlas]]></category>
            <category><![CDATA[mongodb-tutorial]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[mongodb]]></category>
            <dc:creator><![CDATA[NIRAJAN JHA]]></dc:creator>
            <pubDate>Mon, 27 May 2024 08:26:43 GMT</pubDate>
            <atom:updated>2024-05-27T08:26:43.937Z</atom:updated>
            <content:encoded><![CDATA[<h3>MongoDB — NoSQL Database</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iWsHU_6Lw7Ss3zTt95gQZg.png" /></figure><p>In this data-driven world, database plays a crucial role in storing and managing information. Traditional databases like MySQL have been around for decades, but the rise of NoSQL databases has introduced new ways to handle data, especially when dealing with large volumes of unstructured or semi-structured data. One of the most popular NoSQL databases is MongoDB. This article will introduce you to MongoDB, explain its key concepts, basic operations, and how it differs from traditional SQL databases like MySQL. By the end of this article, you’ll have a solid understanding of MongoDB and its practical applications.</p><h3>What is NoSQL?</h3><p>NoSQL stands for “Not Only SQL.” It represents a broad category of database management systems that differ from traditional relational databases. NoSQL databases are designed to handle a variety of data models, including key-value pairs, document-based, column-based, and graph formats. They are known for their scalability, flexibility, and performance, making them suitable for modern applications that require fast and efficient data processing.</p><h3>What is MongoDB?</h3><p>MongoDB is a popular NoSQL database that stores data in a flexible, JSON-like format called BSON (Binary JSON). Unlike traditional SQL databases, which use tables and rows, MongoDB uses collections and documents. This makes it highly adaptable to various data structures and ideal for handling large amounts of unstructured data.</p><h3>Installation and Setup</h3><ol><li>You can visit the MongoDB website (<a href="https://www.mongodb.com/try/download/community"><strong>www.mongodb.com</strong></a>) and download the Community Server version suitable for your operating system.</li><li>Follow the installation instructions provided by MongoDB for your specific operating system.</li><li>Once installed, you can now start the MongoDB server by running the appropriate command or service.</li></ol><h3><strong>Terminologies in MongoDB</strong></h3><h4>1. Database</h4><p>A MongoDB database is a container for collections. Each database has its own set of files on the file system. A single MongoDB server can have multiple databases, each independent of the others.</p><h4>2. Collection</h4><p>A collection in MongoDB is a group of documents. It is the equivalent of a table in a relational database. Collections do not enforce a schema, meaning documents within a collection can have different fields. This flexibility allows for easier data storage and retrieval.</p><h4>3. Document</h4><p>A document is a set of key-value pairs. Documents in MongoDB are similar to JSON objects. They are the basic unit of data and are stored in BSON (Binary JSON) format, which allows for the storage of complex data types like arrays and nested documents.</p><h4>4. Field</h4><p>A field is a key-value pair in a document. It is similar to a column in a relational database. Each document can have multiple fields, and fields can store different types of data such as strings, numbers, arrays, and even other documents.</p><h4>5. Index</h4><p>Indexes in MongoDB improve the performance of search operations by creating a data structure that holds a subset of fields from the documents in a collection. Indexes are similar to indexes in relational databases and can significantly speed up query performance.</p><h3>Basic Operations in MongoDB</h3><p>Let’s explore some basic operations in MongoDB using a practical example.</p><h4>1. Install pymongo</h4><p>Make sure you have pymongo installed:</p><pre>pip install pymongo</pre><h4>2. Connecting to MongoDB</h4><p>To connect to a MongoDB database, use the following code:</p><pre>from pymongo import MongoClient<br><br># Connect to the MongoDB server<br>client = MongoClient(&#39;localhost&#39;, 27017)<br><br># Create or connect to a database<br>db = client[&#39;example_db&#39;]</pre><h4>3. Creating a Database</h4><p>MongoDB creates a database automatically when you start inserting data into it.</p><h4>4. Creating a Collection</h4><pre># Create or connect to a collection<br>collection = db[&#39;example_collection&#39;]</pre><h4>5. Inserting Documents</h4><p>To insert a document into a collection, use the following code:</p><pre>document = {&quot;name&quot;: &quot;Alice&quot;, &quot;age&quot;: 25, &quot;city&quot;: &quot;New York&quot;}<br>collection.insert_one(document)</pre><h4>6. Querying Documents</h4><p>To query documents from a collection, use the following code:</p><pre>results = collection.find({&quot;name&quot;: &quot;Alice&quot;})<br>for result in results:<br>    print(result)</pre><h4>7. Updating Documents</h4><p>You can use the “<strong>update_one”</strong> or “<strong>update_many”</strong> commands to modify documents.</p><p>To update a document, use the following code:</p><pre>collection.update_one({&quot;name&quot;: &quot;Alice&quot;}, {&quot;$set&quot;: {&quot;age&quot;: 26}})</pre><h4>8. Deleting Documents</h4><p>You can use the <strong>“delete_one”</strong> or <strong>“delete_many”</strong> commands to remove documents.</p><p>To delete a document, use the following code:</p><pre>collection.delete_one({&quot;name&quot;: &quot;Alice&quot;})</pre><h4>9. Creating an Index</h4><p>Create indexes on fields that are frequently used for querying to improve query performance.</p><p>To create index, use the following code:</p><pre># Create an index on the &quot;name&quot; field<br>collection.create_index(&quot;name&quot;)</pre><h3>Comparing MongoDB Vs MySQL</h3><h4>Data Storage</h4><ul><li>MySQL: Uses tables with rows and columns.</li><li>MongoDB: Uses collections with documents.</li></ul><h4>Example: Storing User Information</h4><p>MySQL:</p><pre>CREATE TABLE users (<br>    id INT AUTO_INCREMENT PRIMARY KEY,<br>    name VARCHAR(100),<br>    age INT,<br>    city VARCHAR(100)<br>);<br><br>INSERT INTO users (name, age, city) VALUES (&#39;Alice&#39;, 25, &#39;New York&#39;);</pre><p>MongoDB:</p><pre>document = {&quot;name&quot;: &quot;Alice&quot;, &quot;age&quot;: 25, &quot;city&quot;: &quot;New York&quot;}<br>collection.insert_one(document)</pre><h4>Querying Data</h4><p>MySQL:</p><pre>SELECT * FROM users WHERE name = &#39;Alice&#39;;</pre><p>MongoDB:</p><pre>results = collection.find({&quot;name&quot;: &quot;Alice&quot;})</pre><h3>Conclusion</h3><p>Understanding these key concepts in MongoDB will help you get started with this powerful NoSQL database. Whether you are working on a small project or a large-scale application, MongoDB’s flexibility and scalability make it a great choice for managing diverse and large datasets. With its document-based data model and support for advanced features, MongoDB provides the tools you need to build robust and efficient applications.</p><p>To get overview on <strong><em>MYSQL</em></strong>, <a href="https://medium.com/@nirajan_DataAnalyst/mysql-for-beginners-4e758fc4cafa"><strong>Click Here</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cb0050dc760" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL Vs NoSQL Databases]]></title>
            <link>https://medium.com/@nirajan_DataAnalyst/sql-vs-nosql-databases-34e39dc3ec3e?source=rss-45aeed2491e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/34e39dc3ec3e</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[nosql-database]]></category>
            <category><![CDATA[sql-vs-nosql]]></category>
            <dc:creator><![CDATA[NIRAJAN JHA]]></dc:creator>
            <pubDate>Sat, 25 May 2024 18:52:46 GMT</pubDate>
            <atom:updated>2024-05-25T18:52:46.197Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OTyvZ_aE6iWWgIm1LfN7RA.jpeg" /></figure><p>In today’s world, where data is everywhere, choosing between SQL (Structured Query Language) databases and NoSQL (Not Only SQL) databases is like picking the right tool for a job. It’s important for everyone, not just tech experts, to grasp the basics of these systems — their strengths, weaknesses, and when to use them. In this guide, I will take you in the journey through SQL and NoSQL, helping you understand how they work and when to use each, so you can make smarter decisions about managing data in your projects and daily life.</p><h3># SQL Databases</h3><p>SQL databases, also known as relational databases, have been the cornerstone of data management for decades. They organize data into structured tables with predefined schemas, using SQL for data manipulation and retrieval.</p><p>A few examples of industries that rely on SQL databases are:</p><ul><li><strong>Finance</strong></li><li><strong>Retail</strong></li><li><strong>Government and Public Sector</strong></li></ul><h4>Example of SQL Query:</h4><pre>SELECT * FROM customers WHERE age &gt; 30;</pre><h4>Common SQL Database Systems:</h4><p><strong>i. MySQL:</strong> An open-source relational database management system known for its reliability, performance, and ease of use. It is widely used in web applications, e-commerce sites, and small to medium-sized databases.</p><p><strong>ii. PostgreSQL:</strong> Another open-source RDBMS known for its advanced features such as support for JSON data, full-text search, and robust transaction management. It is favored for applications requiring complex queries and data integrity.</p><p><strong>iii. Microsoft SQL Server:</strong> A commercial RDBMS developed by Microsoft, offering features like business intelligence, data warehousing, and high availability. It is commonly used in enterprise environments and Windows-based applications.</p><p><strong>iv. Oracle Database:</strong> A robust commercial RDBMS with a wide range of features including scalability, security, and data management tools. It is often used in large-scale enterprise applications and data-driven businesses.</p><p><strong>v. SQLite: </strong>A lightweight, serverless RDBMS that is embedded into applications for local storage. It is suitable for mobile apps, IoT devices, and small-scale projects requiring a compact database solution.</p><h3># NoSQL Databases</h3><p>NoSQL databases emerged to address the limitations of SQL databases, particularly in handling large volumes of unstructured or semi-structured data. They offer flexibility, scalability, and performance optimizations tailored to modern data needs.</p><p>A few examples of industries that rely on NoSQL databases are:</p><ul><li><strong>Social Media</strong></li><li><strong>Logistics and Supply Chain</strong></li><li><strong>Gaming</strong></li></ul><h4>Example of NoSQL Query (MongoDB):</h4><pre>db.customers.find({ age: { $gt: 30 } });</pre><h4>Common NoSQL Database Systems:</h4><p><strong>i. MongoDB:</strong> A popular document-oriented NoSQL database that stores data in flexible JSON-like documents. It is known for its scalability, high performance, and ease of use.</p><p><strong>ii. Redis:</strong> A key-value store that excels in fast data access and caching. It is often used for real-time applications and as a distributed cache.</p><p><strong>iii. Cassandra:</strong> A columnar store designed for handling massive amounts of data and providing high availability. It is widely used for time-series data and analytics.</p><p><strong>iv. Neo4j:</strong> A graph database that focuses on storing and querying complex relationships between data entities. It is commonly used for social networks, recommendation engines, and network analysis.</p><h3>Key Differences Between SQL vs NoSQL</h3><ol><li><strong><em>Data Structure:</em></strong> SQL database uses structured tables, while NoSQL database supports flexible data models like documents, key-value pairs, columns, and graphs.</li><li><strong><em>Scaling:</em></strong> SQL databases scale vertically, adding resources to a single server, whereas NoSQL databases scale horizontally by distributing data across multiple servers.</li><li><strong><em>ACID Transactions:</em></strong> SQL databases guarantee ACID transactions, ensuring data consistency, while NoSQL databases may trade some transactional guarantees for scalability.</li><li><strong><em>Query Language:</em></strong> SQL uses SQL for data manipulation, while NoSQL databases like MongoDB use their query languages (e.g., MongoDB’s query language).</li><li><strong><em>Data Flexibility:</em></strong> SQL databases are better suited for structured data with predefined schemas, whereas NoSQL databases excel at handling diverse, unstructured data.</li></ol><h3>When to Use SQL and NoSQL Database Type</h3><ul><li><strong><em>SQL Databases:</em></strong> Ideal for applications with structured data, strong transactional requirements, and complex querying needs, such as financial systems, ERP (Enterprise Resource Planning) systems, and traditional business applications.</li><li><strong><em>NoSQL Databases:</em></strong> Recommended for projects dealing with unstructured or semi-structured data, high scalability demands, real-time analytics, IoT (Internet of Things) applications, and agile development environments.</li></ul><h3>Conclusion</h3><p>The choice between SQL and NoSQL databases plays a pivotal role in the effectiveness and success of data science and application development. The impact on performance, scalability, and adaptability to data types directly influences the responsiveness of data-driven applications.</p><p>In conclusion, choosing between SQL and NoSQL databases is about knowing what you need. SQL offers structured reliability, great for tasks with fixed patterns like managing finances or inventory. On the other hand, NoSQL provides flexibility, perfect for handling diverse data in dynamic projects like social media analytics or IoT devices. By grasping these differences and knowing when to use each, you are equipped to make informed decisions that optimize data management and you can make smart choices that make your work easier and more effective.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34e39dc3ec3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MYSQL Stored Procedures]]></title>
            <link>https://medium.com/@nirajan_DataAnalyst/mysql-stored-procedures-699a0f3c4005?source=rss-45aeed2491e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/699a0f3c4005</guid>
            <category><![CDATA[sql-stored-procedure]]></category>
            <category><![CDATA[stored-procedure]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[NIRAJAN JHA]]></dc:creator>
            <pubDate>Sat, 25 May 2024 12:52:14 GMT</pubDate>
            <atom:updated>2024-05-25T12:52:14.526Z</atom:updated>
            <content:encoded><![CDATA[<p>A Stored Procedure is a prepared SQL code that the user can save so that the code can be reused over and over again. It can accept input parameters, return output parameters, and include error-handling mechanisms. In this article, I will delve into the details of stored procedures, covering their importance, types, applications, and providing detailed examples to illustrate their utility.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*npfqCtJn5q_VkZEq7-efSA.png" /></figure><p>Imagine you have a favorite recipe that you use frequently. Instead of writing it down every time you cook, you write it once on a recipe card and refer to it whenever you need. A stored procedure in MYSQL works similarly. It’s a saved collection of SQL statements that you can run whenever you need to perform a specific task.</p><p>Here’s how it works step-by-step:</p><ol><li><strong><em>Create the Recipe (Stored Procedure):</em></strong> First, you write down your recipe (SQL statements) and save it in the database. This is called creating a stored procedure.</li><li><strong><em>Follow the Recipe (Execute the Stored Procedure):</em></strong> Whenever you need to perform that task, you simply refer to the recipe by its name and follow the instructions (execute the stored procedure).</li></ol><p><strong>Let’s see how it actually works in MYSQL.</strong></p><h3>1. Creating a Stored Procedure</h3><p>Suppose you manage a database for a company and frequently need to look up employee details. Instead of writing the SQL query every time, you create a stored procedure to do this.</p><p>Here’s the code to create a stored procedure name “<strong><em>GetEmployeeDetails”</em></strong> in MySQL:</p><pre>DELIMITER //<br><br>CREATE PROCEDURE GetEmployeeDetails()<br>BEGIN<br>    SELECT EmployeeID, FirstName, LastName, Department<br>    FROM Employees;<br>END //<br><br>DELIMITER ;</pre><h4>Explanation</h4><ul><li><strong>DELIMITER // </strong>: MySQL uses the semicolon (;) as the default statement delimiter. To define a stored procedure, we temporarily change the delimiter to // so that MySQL understands where the procedure definition ends.</li><li><strong>CREATE PROCEDURE GetEmployeeDetails()</strong> : This tells MySQL that we are creating a new stored procedure named GetEmployeeDetails.</li><li><strong>BEGIN…END :</strong> These keywords define the start and end of the stored procedure’s code block.</li><li><strong>SELECT EmployeeID, FirstName, LastName, Department FROM Employees;</strong> : This is the SQL query that retrieves employee details.</li></ul><h3>2. Using the Stored Procedure</h3><p>Once you have created the stored procedure, you can use it whenever you need to get employee details:</p><pre>CALL GetEmployeeDetails();</pre><h4>Explanation</h4><ul><li><strong>CALL GetEmployeeDetails();</strong> : This command runs the stored procedure named GetEmployeeDetails. MySQL executes the SQL statements inside the procedure and returns the results.</li></ul><h3>3. Adding Parameters</h3><p>Stored procedures can accept parameters to make them more flexible. Let’s modify our example to look up details for a specific employee using an ID.</p><p>Here’s how you create a stored procedure with an input parameter:</p><pre>DELIMITER //<br><br>CREATE PROCEDURE GetEmployeeByID(IN EmployeeID INT)<br>BEGIN<br>    SELECT EmployeeID, FirstName, LastName, Department<br>    FROM Employees<br>    WHERE EmployeeID = EmployeeID;<br>END //<br><br>DELIMITER ;</pre><h4>Explanation</h4><ul><li><strong>IN EmployeeID INT</strong> : This defines an input parameter named EmployeeID of type INT (integer). Input parameters are placeholders for the actual values you’ll use when you call the procedure.</li><li><strong>WHERE EmployeeID = EmployeeID</strong> : This part of the query filters the results to show only the employee with the specified ID.</li></ul><h3>4. Using the Stored Procedure with a Parameter</h3><p>To get details for a specific employee, you provide the employee ID as a parameter when you call the procedure:</p><pre>CALL GetEmployeeByID(1);</pre><h4>Explanation</h4><ul><li><strong>CALL GetEmployeeByID(1);</strong> : This calls the GetEmployeeByID procedure and passes 1 as the value for the EmployeeID parameter.</li></ul><h3>5. Output Parameters</h3><p>Stored procedures can also return output parameters.</p><p>Suppose you want to get an employee’s department based on their ID and return it as an output parameter. Here’s how you can modify the GetEmployeeByID procedure to include an output parameter:</p><pre>DELIMITER //<br><br>CREATE PROCEDURE GetEmployeeDepartment(<br>    IN EmployeeID INT,<br>    OUT Department VARCHAR(50)<br>)<br>BEGIN<br>    SELECT Department INTO Department<br>    FROM Employees<br>    WHERE EmployeeID = EmployeeID;<br>END //<br><br>DELIMITER ;</pre><h4>Explanation</h4><ul><li><strong>OUT Department VARCHAR(50)</strong> : This defines an output parameter named Department of type VARCHAR(50). Output parameters return values to the caller.</li><li><strong>SELECT Department INTO Department</strong> : This query retrieves the department name and stores it in the Department output parameter.</li></ul><h4>6. Executing this stored procedure with an output parameter:</h4><p>To call the stored procedure and retrieve the output parameter value, you use the following code:</p><pre>SET @Dept = &#39;&#39;;<br><br>CALL GetEmployeeDepartment(1, @Dept);<br><br>SELECT @Dept;</pre><h4>Explanation</h4><ul><li><strong>SET @Dept = ‘’;</strong> : This initializes a variable to hold the output parameter value.</li><li><strong>CALL GetEmployeeDepartment(1, @Dept);</strong> : This calls the stored procedure, passing 1 as the employee ID and storing the output in @Dept.</li><li><strong>SELECT @Dept;</strong> : This displays the value of @Dept, which is the employee&#39;s department.</li></ul><h3>7. Error Handling in Stored Procedures</h3><p>Error handling ensures that your stored procedures can manage unexpected issues gracefully. MySQL uses DECLARE ... HANDLER to define error handlers.</p><p>Let’s add error handling to our UpdateEmployeeSalary procedure to manage any potential errors that might occur during the update operation:</p><pre>DELIMITER //<br><br>CREATE PROCEDURE UpdateEmployeeSalary(<br>    IN EmployeeID INT,<br>    IN NewSalary DECIMAL(10, 2),<br>    OUT Message VARCHAR(255)<br>)<br>BEGIN<br>    DECLARE EXIT HANDLER FOR SQLEXCEPTION<br>    BEGIN<br>        -- Handle the error<br>        SET Message = &#39;An error occurred. Please try again.&#39;;<br>    END;<br><br>    UPDATE Employees<br>    SET Salary = NewSalary<br>    WHERE EmployeeID = EmployeeID;<br><br>    IF ROW_COUNT() = 0 THEN<br>        SET Message = &#39;Employee not found.&#39;;<br>    ELSE<br>        SET Message = &#39;Salary updated successfully.&#39;;<br>    END IF;<br>END //<br><br>DELIMITER ;</pre><h4>Explanation</h4><ul><li><strong>OUT Message VARCHAR(255)</strong> : This defines an output parameter named Message of type VARCHAR(255), which will hold the result message.</li><li><strong>DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN … END;</strong> : This defines an error handler for SQL exceptions. If an error occurs, it sets the Message output parameter to an error message.</li><li><strong>UPDATE Employees SET Salary = NewSalary WHERE EmployeeID = EmployeeID;</strong> : This updates the employee’s salary.</li><li><strong>IF ROW_COUNT() = 0 THEN SET Message = ‘Employee not found.’; ELSE SET Message = ‘Salary updated successfully.’; END IF;</strong> : This checks if any rows were updated. If no rows were updated, it sets the Message to indicate that the employee was not found. Otherwise, it sets the Message to indicate success.</li></ul><h4>8. Using the Error-Handled Procedure</h4><p>To update an employee’s salary and handle potential errors, you call the procedure as follows:</p><pre>SET @ResultMessage = &#39;&#39;;<br><br>CALL UpdateEmployeeSalary(1, 75000, @ResultMessage);<br><br>SELECT @ResultMessage;</pre><h4>Explanation</h4><ul><li><strong>SET @ResultMessage = ‘’;<em> </em></strong>: This initializes a variable to hold the output parameter value.</li><li><strong>CALL UpdateEmployeeSalary(1, 75000, @ResultMessage);</strong> : This calls the stored procedure, passing 1 as the employee ID, 75000 as the new salary, and storing the output message in @ResultMessage.</li><li><strong>SELECT @ResultMessage;</strong> : This displays the value of @ResultMessage, which contains the result message from the procedure.</li></ul><h3>Why Use Stored Procedures?</h3><ol><li><strong><em>Simplicity:</em></strong> Instead of writing complex SQL queries repeatedly, you write them once and save them as a stored procedure.</li><li><strong><em>Efficiency:</em></strong> Stored procedures are precompiled, which means they run faster than executing the same SQL statements separately.</li><li><strong><em>Security:</em></strong> You can restrict access to the data by granting permissions to execute the stored procedure without allowing direct access to the tables.</li><li><strong><em>Consistency:</em></strong> Stored procedures ensure that the same operations are performed consistently across different parts of an application.</li></ol><h3>Conclusion</h3><p>Stored procedures are a powerful tool in MYSQL that provide numerous benefits, including improved performance, security, and maintainability. Understanding how to create, execute, and manage stored procedures is essential for any database professional. Whether you are performing basic <strong>CRUD</strong> operations, returning values through output parameters, or implementing error handling, stored procedures offer a robust solution for managing your database tasks. Use the examples and best practices provided in this article to enhance your SQL development skills and build robust database applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=699a0f3c4005" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>