<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Zubair Idris Aweda - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Zubair Idris Aweda - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Thu, 14 May 2026 04:32:19 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/Zubs/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How Relational Database Constraints Work and Why They're Important ]]>
                </title>
                <description>
                    <![CDATA[ Databases are a crucial tool because they store the data that power our day-to-day lives. Databases are designed to match the real world as much as possible, so they store data of different forms, about different things, just as it is in the world. T... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-relational-database-constraints-work-and-why-theyre-important/</link>
                <guid isPermaLink="false">69681d224dcb07c08e435626</guid>
                
                    <category>
                        <![CDATA[ Databases ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Relational Database ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Zubair Idris Aweda ]]>
                </dc:creator>
                <pubDate>Wed, 14 Jan 2026 22:48:02 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1768416017042/66390973-a4cb-4e7a-9161-2d737045bf7b.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Databases are a crucial tool because they store the data that power our day-to-day lives. Databases are designed to match the real world as much as possible, so they store data of different forms, about different things, just as it is in the world.</p>
<p>There are many rules that govern how entities interact with each other, to make things work. For example, a student can’t take a course that the school doesn’t offer. A soccer player can’t have a jersey number less than 1 or greater than 99. And a car must always have a plate number.</p>
<p>Relational databases are also able to represent and enforce these rules using <strong>constraints</strong>. And in this article, I’ll explain how constraints work with practical examples.</p>
<p>Whether you’re a beginner or just looking to refresh your knowledge, this article will help you learn the essentials. If you need some more background, you can read this article on the <a target="_blank" href="https://www.freecodecamp.org/news/learn-relational-database-basics-key-concepts-for-beginners/">basics of relational databases</a> before continuing.</p>
<h3 id="heading-what-well-cover">What We’ll Cover:</h3>
<ol>
<li><p><a class="post-section-overview" href="#heading-what-is-a-relational-database-constraint">What is a Relational Database Constraint?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-types-of-relational-database-constraints">Types of Relational Database Constraints</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-inherent-model-based-constraints-implicit-constraints">Inherent Model-based Constraints (Implicit Constraints)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-schema-based-constraints-explicit-constraints">Schema-based Constraints (Explicit Constraints)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-application-based-constraints-semantic-constraints">Application-based constraints (Semantic constraints)</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-testing-constraints">Testing Constraints</a></p>
<ul>
<li><a class="post-section-overview" href="#heading-how-to-delete-a-record">How to Delete a Record</a></li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-summary">Summary</a></p>
</li>
</ol>
<h2 id="heading-what-is-a-relational-database-constraint">What is a Relational Database Constraint?</h2>
<p>Relational database constraints are a set of database rules that are used to define or determine what set of values are acceptable or valid in a database. They’re usually based on the many rules of the real world.</p>
<p>They are put in place to:</p>
<ul>
<li><p>Ensure data accuracy: only values that would be acceptable in real life should be acceptable in the database. Learn more about data accuracy <a target="_blank" href="https://www.ibm.com/think/topics/data-accuracy">here</a>.</p>
</li>
<li><p>Ensure data integrity: values in the database remain correct, accurate, complete, and valid as long as the database exists. Learn more about data integrity <a target="_blank" href="https://www.fortinet.com/uk/resources/cyberglossary/data-integrity">here</a>.</p>
</li>
<li><p>Ensure data consistency: values always maintain same agreed form throughout their lifetime.</p>
</li>
</ul>
<p>These rules limit what can be entered into a database or what can be deleted from it. They also limit data update to ensure validity after original creation.</p>
<blockquote>
<p>These integrity constraints help enforce business rules on data in the tables to ensure the accuracy and reliability of the data. - <a target="_blank" href="https://aws.amazon.com/rds/what-is-a-relational-database/">AWS</a></p>
</blockquote>
<h2 id="heading-types-of-relational-database-constraints">Types of Relational Database Constraints</h2>
<p>There are many ways to group or categorise database constraints, depending on how they’re applied or what they’re preventing. This article focuses on three popular types:</p>
<ul>
<li><p>Inherent model-based constraints (implicit constraints)</p>
</li>
<li><p>Schema-based constraints (explicit constraints)</p>
</li>
<li><p>Application-based constraints (semantic constraints)</p>
</li>
</ul>
<h3 id="heading-inherent-model-based-constraints-implicit-constraints">Inherent Model-based Constraints (Implicit Constraints)</h3>
<p>These rules are the base rules that come with the database and are enforced by the DMBS. Some of these rules are:</p>
<ul>
<li><p>Each row must be unique. This is with or without a <code>UNIQUE</code> or <code>PRIMARY KEY</code> constraint.</p>
</li>
<li><p>Columns can only store one value at a time. The value of a field like <code>age</code> will always be one value like 23, not 23 and 35.</p>
</li>
<li><p>Each column name in a table must be unique.</p>
</li>
<li><p>Columns exist for all rows. Every row will have the same number of columns. For some of the rows, the data might be empty, but the column will always be there.</p>
</li>
</ul>
<h3 id="heading-schema-based-constraints-explicit-constraints">Schema-based Constraints (Explicit Constraints)</h3>
<p>These constraints are expressed by the developer or database designer on database creation. They’re expressed directly in the database schemas, using the <a target="_blank" href="https://en.wikipedia.org/wiki/Data_definition_language">DDL</a>.</p>
<p>These can be further broken down into:</p>
<ul>
<li><p>Domain constraints</p>
</li>
<li><p>Key constraints</p>
<ul>
<li><p>Entity integrity constraint (Primary key)</p>
</li>
<li><p>Unique constraint (Unique key)</p>
</li>
<li><p>Referential integrity constraint (Foreign key)</p>
</li>
</ul>
</li>
</ul>
<h4 id="heading-1-domain-constraints">1. Domain Constraints</h4>
<p>These are used to define a range or set of possible values for an attribute of a database table. They help ensure that column values are valid and consistent by defining acceptable data types, formats, and ranges for an attribute. This prevents incorrect or illogical data entry and maintains data integrity.</p>
<p>You can define them simply by specifying a data type that the values must follow. For example, the <code>age</code> of a person can only be a number, or could be a number between 18-60 if the database is for a company, or a number between 5-65 if it’s for an amusement park.</p>
<p>The database will enforce this rule by rejecting age values outside of the given range or type. The DDL for the age would look like this:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> people (
    age <span class="hljs-built_in">INT</span>, <span class="hljs-comment">-- Any integer value is allowed</span>
    age <span class="hljs-built_in">INT</span> <span class="hljs-keyword">CHECK</span> (age <span class="hljs-keyword">BETWEEN</span> <span class="hljs-number">18</span> <span class="hljs-keyword">AND</span> <span class="hljs-number">60</span>), <span class="hljs-comment">-- Only allows ages between 18 and 60</span>
    age <span class="hljs-built_in">INT</span> <span class="hljs-keyword">CHECK</span> (age <span class="hljs-keyword">BETWEEN</span> <span class="hljs-number">5</span> <span class="hljs-keyword">AND</span> <span class="hljs-number">65</span>) <span class="hljs-comment">-- Only allows ages between 5 and 65</span>
);
</code></pre>
<p>The <code>INT</code> means only integer values are accepted, and the <code>CHECK</code> is used with the <code>BETWEEN</code> and <code>AND</code> keywords to specify the sub-domain or range of values.</p>
<p>Other <a target="_blank" href="https://www.w3schools.com/sql/sql_datatypes.asp">data types in SQL</a> include: <code>CHAR</code>, <code>BIT</code>, <code>DATE</code>, <code>VARCHAR</code> and so on. You can use all of them to define the acceptable domain for database values.</p>
<pre><code class="lang-sql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> employees (
    employee_id <span class="hljs-built_in">INT</span>,
    <span class="hljs-keyword">name</span> <span class="hljs-built_in">VARCHAR</span>(<span class="hljs-number">100</span>),
    age <span class="hljs-built_in">INT</span> <span class="hljs-keyword">CHECK</span> (age <span class="hljs-keyword">BETWEEN</span> <span class="hljs-number">18</span> <span class="hljs-keyword">AND</span> <span class="hljs-number">60</span>)
);
</code></pre>
<p>As well as defining a range of acceptable values, you can also define the optionality of an attribute using the <code>NOT NULL</code> keyword. You’d use this in cases where the data must exist and must also be within the given range.</p>
<pre><code class="lang-sql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> employees (
    employee_id <span class="hljs-built_in">INT</span> <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>,
    <span class="hljs-keyword">name</span> <span class="hljs-built_in">VARCHAR</span>(<span class="hljs-number">100</span>) <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>,
    age <span class="hljs-built_in">INT</span> <span class="hljs-keyword">CHECK</span> (age <span class="hljs-keyword">BETWEEN</span> <span class="hljs-number">18</span> <span class="hljs-keyword">AND</span> <span class="hljs-number">60</span>)
);
</code></pre>
<p>In this example, every employee record needs to have an <code>employee_id</code> and a <code>name</code> but not an <code>age</code>. This works for real life situations where, although the range of values is known, the actual value is either unknown or doesn’t exist. An example would be the minor course of study of a student at a university – many students only have majors, and as such, the minor course of study will be empty (NULL) for those students.</p>
<h4 id="heading-2-entity-integrity-constraint-primary-key">2. Entity integrity constraint (Primary key)</h4>
<p>This ensures that no primary key is NULL. The primary key is the one attribute or set of attributes that must be unique to each row in the database. It’s the primary value that uniquely identifies the rest of the data. This means that every row in the database will remain uniquely identifiable with a primary key.</p>
<p>A NULL primary key means that rows will not be unique, or identifiable, and the database can contain duplicates. Without the primary key, we can’t have data consistency.</p>
<p>For example, in a school, every student will have a unique student id number with which they can always be distinguished from other students. The government uses methods like passport numbers or tax ids to uniquely identify citizens.</p>
<p>In our example, it’s impossible to be a student without a student id number. You can implement this constraint by using the <code>PRIMARY KEY</code> keyword.</p>
<pre><code class="lang-sql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> employees (
    employee_id <span class="hljs-built_in">INT</span> PRIMARY <span class="hljs-keyword">KEY</span>,
    <span class="hljs-keyword">name</span> <span class="hljs-built_in">VARCHAR</span>(<span class="hljs-number">100</span>),
    age <span class="hljs-built_in">INT</span> <span class="hljs-keyword">CHECK</span> (age <span class="hljs-keyword">BETWEEN</span> <span class="hljs-number">18</span> <span class="hljs-keyword">AND</span> <span class="hljs-number">60</span>)
);
</code></pre>
<h4 id="heading-3-unique-constraint-unique-key">3. Unique constraint (Unique key)</h4>
<p>This is similar to the <strong>Entity integrity constraint</strong> in that it only accepts unique values – but it’s different in that it accepts NULL values.</p>
<p>An example of this would be in a students table, every student must have a student id number that uniquely identifies them. This number cannot be NULL, and it must the unique. Students can also have an email address that the school can reach them on. This email must be unique for each student. But, not every student has to have an email. So the condition is: <strong>“If the value exists, it must be unique”</strong>.</p>
<p>You can implement this constraint using the <code>UNIQUE</code> keyword, like this:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> students (
    student_id <span class="hljs-built_in">INT</span> PRIMARY <span class="hljs-keyword">KEY</span>, <span class="hljs-comment">-- Must exist and must be unique</span>
    email <span class="hljs-built_in">VARCHAR</span>(<span class="hljs-number">255</span>) <span class="hljs-keyword">UNIQUE</span> <span class="hljs-comment">-- Can be NULL, but must be unique if provided</span>
);
</code></pre>
<h4 id="heading-4-referential-integrity-constraint-foreign-key">4. Referential integrity constraint (Foreign key)</h4>
<p>This constraint guards the relationship between two related tables. It is used to maintain consistency in the relationship. It requires that data from one table, A, being referenced in another table, B, must exist in the original table, A. For example, a student can’t register for a course the school doesn’t have.</p>
<p>To enforce this, the <code>FOREIGN KEY</code> keyword is used with the <code>REFERENCES</code> to define the table being referenced, and what attribute is being referred to.</p>
<pre><code class="lang-sql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> courses (
    course_id <span class="hljs-built_in">INT</span> PRIMARY <span class="hljs-keyword">KEY</span>,
    course_name <span class="hljs-built_in">VARCHAR</span>(<span class="hljs-number">100</span>) <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>
);

<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> students (
    student_id <span class="hljs-built_in">INT</span> PRIMARY <span class="hljs-keyword">KEY</span>,
    student_name <span class="hljs-built_in">VARCHAR</span>(<span class="hljs-number">100</span>) <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>,
    course_id <span class="hljs-built_in">INT</span>,
    <span class="hljs-keyword">FOREIGN</span> <span class="hljs-keyword">KEY</span> (course_id) <span class="hljs-keyword">REFERENCES</span> courses(course_id)
);
</code></pre>
<p>In this example, every value provided in the <code>course_id</code> of the <code>students</code> must be in the <code>courses</code> table.</p>
<h3 id="heading-application-based-constraints-semantic-constraints">Application-based constraints (Semantic constraints)</h3>
<p>These can also be called <strong>business rules</strong>. They can’t be directly expressed in the database schema, so they’re often implemented the application layer instead.</p>
<p>These are logical constraints, like saying <strong>“a course cannot have more than 30 students enrolled”</strong> or <strong>“a customer cannot place an order if it would exceed their credit limit”</strong>.</p>
<p>These rules are best implemented in the application, because it would be too complex (or sometimes impossible) to implement them on the database itself.</p>
<h2 id="heading-testing-constraints">Testing Constraints</h2>
<p>To demonstrate the constraints we’ve discussed here, let’s look at this sample school database setup:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> courses (course_id <span class="hljs-built_in">INT</span> PRIMARY <span class="hljs-keyword">KEY</span>, course_name <span class="hljs-built_in">VARCHAR</span>(<span class="hljs-number">100</span>) <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>, max_students <span class="hljs-built_in">INT</span> <span class="hljs-keyword">CHECK</span> (max_students &gt; <span class="hljs-number">0</span>));

<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> students (student_id <span class="hljs-built_in">INT</span> PRIMARY <span class="hljs-keyword">KEY</span>, student_name <span class="hljs-built_in">VARCHAR</span>(<span class="hljs-number">100</span>) <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>, email <span class="hljs-built_in">VARCHAR</span>(<span class="hljs-number">100</span>) <span class="hljs-keyword">UNIQUE</span>, age <span class="hljs-built_in">INT</span> <span class="hljs-keyword">CHECK</span> (age <span class="hljs-keyword">BETWEEN</span> <span class="hljs-number">5</span> <span class="hljs-keyword">AND</span> <span class="hljs-number">25</span>));

<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> enrollments (
    enrollment_id <span class="hljs-built_in">INT</span> PRIMARY <span class="hljs-keyword">KEY</span>,
    student_id <span class="hljs-built_in">INT</span> <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>,
    course_id <span class="hljs-built_in">INT</span> <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>,
    enrollment_date <span class="hljs-built_in">DATE</span> <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>,
    <span class="hljs-keyword">FOREIGN</span> <span class="hljs-keyword">KEY</span> (student_id) <span class="hljs-keyword">REFERENCES</span> students (student_id),
    <span class="hljs-keyword">FOREIGN</span> <span class="hljs-keyword">KEY</span> (course_id) <span class="hljs-keyword">REFERENCES</span> courses (course_id)
);
</code></pre>
<p>This shows the creation of a sample school database with three tables: <code>courses</code>, <code>students</code>, and <code>enrollments</code>.</p>
<p>The <code>courses</code> table includes a primary key for course IDs, course names, and a constraint ensuring that the maximum number of students is greater than zero. The <code>students</code> table contains a primary key for student IDs, student names, unique email addresses, and an age constraint between 5 and 25. The <code>enrollments</code> table links students to courses with primary keys for enrollment IDs and foreign keys referencing the <code>students</code> and <code>courses</code> tables, along with a non-null enrollment date.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1768410057148/ffe42706-4540-4ddb-8394-c157fe999b96.png" alt="DDL to create database tables" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>At this point, the tables are created, and setup with the constraints guiding them.</p>
<p>Now we’ll test a few queries:</p>
<ol>
<li>Insert courses, Mathematics and History, into the <code>courses</code> table:</li>
</ol>
<pre><code class="lang-sql"><span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span> courses (course_id, course_name, max_students) <span class="hljs-keyword">VALUES</span> (<span class="hljs-number">1</span>, <span class="hljs-string">'Mathematics'</span>, <span class="hljs-number">30</span>);
<span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span>
    courses (course_id, course_name, max_students)
<span class="hljs-keyword">VALUES</span>
    (<span class="hljs-number">2</span>, <span class="hljs-string">'History'</span>, <span class="hljs-number">25</span>);
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1768410234586/bb08fb52-9573-4f57-88d2-6383138ddc7f.png" alt="Query to insert courses" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1768410261770/f974693c-25fc-4952-80c7-6db7f4959236.png" alt="Result of insert query" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>The query works perfectly, as the records get inserted.</p>
<ol start="2">
<li>Insert students, Alice and Bob, into the <code>students</code> table:</li>
</ol>
<pre><code class="lang-sql"><span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span>
    students (student_id, student_name, email, age)
<span class="hljs-keyword">VALUES</span>
    (<span class="hljs-number">101</span>, <span class="hljs-string">'Alice'</span>, <span class="hljs-string">'alice@example.com'</span>, <span class="hljs-number">20</span>);

<span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span>
    students (student_id, student_name, email, age)
<span class="hljs-keyword">VALUES</span>
    (<span class="hljs-number">102</span>, <span class="hljs-string">'Bob'</span>, <span class="hljs-literal">NULL</span>, <span class="hljs-number">18</span>);
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1768410360967/92aee819-63fe-4b3c-af2b-b579d66e58a9.png" alt="Query to insert students" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1768410407790/ec9893cf-ded6-4ec2-bac1-c78d430a84fb.png" alt="Result of query" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>The query works perfectly, as the records get inserted.</p>
<ol start="3">
<li>Enroll Alice into Mathematics:</li>
</ol>
<pre><code class="lang-sql"><span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span>
    enrollments (enrollment_id, student_id, course_id, enrollment_date)
<span class="hljs-keyword">VALUES</span>
    (<span class="hljs-number">1001</span>, <span class="hljs-number">101</span>, <span class="hljs-number">1</span>, <span class="hljs-string">'2026-01-14'</span>);
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1768410510198/be229077-028c-4048-836c-fb7796b02f7d.png" alt="Query to insert enrollment" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1768410543235/f546d371-da31-4f42-be3d-20bd2bb1aa3a.png" alt="Result of query" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>The query works perfectly, as the record gets inserted.</p>
<ol start="4">
<li>Insert a new student, Charlie, into the <code>students</code> table:</li>
</ol>
<pre><code class="lang-sql"><span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span>
    students (student_id, student_name, email, age)
<span class="hljs-keyword">VALUES</span>
    (<span class="hljs-number">103</span>, <span class="hljs-string">'Charlie'</span>, <span class="hljs-string">'charlie@example.com'</span>, <span class="hljs-number">30</span>);
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1768410642880/0b9f038d-fb4f-49e1-a92f-3c1fd01c3fae.png" alt="Failed query to insert student" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>This fails because Charlie has an <code>age</code> value of 30, which is outside of the specified range of <code>age INT CHECK (age BETWEEN 5 AND 25)</code>. The record of Charlie never gets added.</p>
<p>Here’s a list of some other queries that will fail:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span>
    students (student_id, student_name, email, age)
<span class="hljs-keyword">VALUES</span>
    (<span class="hljs-number">104</span>, <span class="hljs-string">'David'</span>, <span class="hljs-string">'alice@example.com'</span>, <span class="hljs-number">19</span>); <span class="hljs-comment">-- Fails for duplicate email</span>

<span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span>
    students (student_id, student_name, email, age)
<span class="hljs-keyword">VALUES</span>
    (<span class="hljs-literal">NULL</span>, <span class="hljs-string">'Evra'</span>, <span class="hljs-string">'evra@example.com'</span>, <span class="hljs-number">20</span>); <span class="hljs-comment">-- Fails for NULL primary key</span>

<span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span>
    enrollments (enrollment_id, student_id, course_id, enrollment_date)
<span class="hljs-keyword">VALUES</span>
    (<span class="hljs-number">1002</span>, <span class="hljs-number">999</span>, <span class="hljs-number">1</span>, <span class="hljs-string">'2026-01-14'</span>); <span class="hljs-comment">-- Fails for invalid student reference</span>
</code></pre>
<p>In each case, the DBMS will provide a reason for the rejection or failure.</p>
<ol start="5">
<li>Delete Bob from the <code>students</code> table:</li>
</ol>
<pre><code class="lang-sql"><span class="hljs-keyword">DELETE</span> <span class="hljs-keyword">FROM</span> students
<span class="hljs-keyword">WHERE</span>
    student_id = <span class="hljs-number">102</span>;
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1768411198451/3e33efdb-68e9-4cf5-a809-d2053059c29d.png" alt="Query to delete student" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1768411236739/50b24978-2612-4232-8169-3a24377b39a0.png" alt="Result of query" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>The query works perfectly, as the record gets deleted.</p>
<ol start="6">
<li>Delete Alice from the <code>students</code> table:</li>
</ol>
<pre><code class="lang-sql"><span class="hljs-keyword">DELETE</span> <span class="hljs-keyword">FROM</span> students
<span class="hljs-keyword">WHERE</span>
    student_id = <span class="hljs-number">101</span>; <span class="hljs-comment">-- Fails for referential integrity constraint</span>
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1768411336408/8fc634c2-1f10-41f2-b413-4c6b5af22369.png" alt="Failed query to delete students" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>This fails because Alice, with <code>student_id</code> of 101, has an enrollment record in the <code>enrollments</code> table. Deleting the record would mean there will be an enrollment record for a non-existent student which should not be possible.</p>
<h3 id="heading-how-to-delete-a-record">How to Delete a Record</h3>
<p>In some cases, you do want to delete a record, even though it has records tied to it. There are two main ways to go about this:</p>
<h4 id="heading-cascade">CASCADE</h4>
<p>You can use this to define situations where, when a parent record is deleted, the child records cannot exist. All dependent (child) records in other tables are <strong>automatically deleted</strong>. You can use this to ensure that all enrollment records are deleted when the course is no longer available, or when a student is no longer in the school.</p>
<pre><code class="lang-sql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> enrollments (enrollment_id <span class="hljs-built_in">INT</span> PRIMARY <span class="hljs-keyword">KEY</span>, student_id <span class="hljs-built_in">INT</span> <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>, course_id <span class="hljs-built_in">INT</span> <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>, <span class="hljs-keyword">FOREIGN</span> <span class="hljs-keyword">KEY</span> (course_id) <span class="hljs-keyword">REFERENCES</span> courses (course_id) <span class="hljs-keyword">ON</span> <span class="hljs-keyword">DELETE</span> <span class="hljs-keyword">CASCADE</span>);

<span class="hljs-keyword">DELETE</span> <span class="hljs-keyword">FROM</span> courses
<span class="hljs-keyword">WHERE</span>
    course_id = <span class="hljs-number">1</span>;
</code></pre>
<h4 id="heading-set-null-or-set-default">SET NULL or SET DEFAULT</h4>
<p>You can use these methods to define situations where child records can still exist without the parent. All dependent (child) records in other tables are <strong>automatically set to null</strong> or <strong>automatically set to a defined default.</strong></p>
<p>A useful example is if a school had a mentor assigned to students, when the mentor leaves the school, you don’t want to delete the students – you want to set the mentor to NULL or a default staff.</p>
<pre><code class="lang-sql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> teachers (teacher_id <span class="hljs-built_in">INT</span> PRIMARY <span class="hljs-keyword">KEY</span>, teacher_name <span class="hljs-built_in">VARCHAR</span>(<span class="hljs-number">100</span>) <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>);

<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> students (student_id <span class="hljs-built_in">INT</span> PRIMARY <span class="hljs-keyword">KEY</span>, student_name <span class="hljs-built_in">VARCHAR</span>(<span class="hljs-number">100</span>) <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>, mentor_id <span class="hljs-built_in">INT</span>, <span class="hljs-keyword">FOREIGN</span> <span class="hljs-keyword">KEY</span> (mentor_id) <span class="hljs-keyword">REFERENCES</span> teachers (teacher_id) <span class="hljs-keyword">ON</span> <span class="hljs-keyword">DELETE</span> <span class="hljs-keyword">SET</span> <span class="hljs-literal">NULL</span>);
</code></pre>
<ol start="7">
<li>Update Alice’s details. Change her email to a new one, and increase her age:</li>
</ol>
<pre><code class="lang-sql"><span class="hljs-keyword">UPDATE</span> students
<span class="hljs-keyword">SET</span>
    email = <span class="hljs-string">'alice.new@example.com'</span>,
    age = <span class="hljs-number">22</span>
<span class="hljs-keyword">WHERE</span>
    student_id = <span class="hljs-number">101</span>;
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1768411782761/0fe14052-2bbd-4c44-952d-a13ce30947ce.png" alt="Query to update student" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1768411806702/651e9694-5821-4aa0-b606-98ab361a9637.png" alt="Result of query" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>The query works perfectly, as the record gets updated.</p>
<ol start="8">
<li>Update Alice’s age to 30:</li>
</ol>
<pre><code class="lang-sql"><span class="hljs-keyword">UPDATE</span> students
<span class="hljs-keyword">SET</span>
    age = <span class="hljs-number">30</span>
<span class="hljs-keyword">WHERE</span>
    student_id = <span class="hljs-number">101</span>;
</code></pre>
<p>This fails just like the 4th test for the same reason: the <code>age</code> is out of the stated range.</p>
<p>Here’s another query that will fail:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">UPDATE</span> enrollments
<span class="hljs-keyword">SET</span>
    course_id = <span class="hljs-number">999</span>
<span class="hljs-keyword">WHERE</span>
    enrollment_id = <span class="hljs-number">1001</span>;
</code></pre>
<p>This will fail because the new <code>course_id</code> does not exist in the <code>courses</code> table.</p>
<h2 id="heading-summary">Summary</h2>
<p>Databases are a pivotal part of everyday modern technology, and understanding their fundamental concepts can open doors to building and managing more accurate databases.</p>
<p>This article introduced you to what relational database constraints are, some of the different types, and how they’re enforced and violated. You should now have the essential knowledge to navigate the world of database constraints confidently.</p>
<p>If you’re curious to learn more, connect with me on <a target="_blank" href="https://www.linkedin.com/in/idris-aweda-zubair-5433121a3/">LinkedIn</a>, <a target="_blank" href="https://twitter.com/greatzubs">Twitter</a>, or <a target="_blank" href="https://github.com/Zubs">GitHub</a>. Let’s continue this journey together toward mastering database systems!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Learn Relational Database Basics – Key Concepts for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ In today’s digital world, data is everywhere, and it’s at the heart of most modern applications. Databases are the unsung heroes that keep it all organised and accessible. Many sites use databases, from social media platforms to online shopping retai... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-relational-database-basics-key-concepts-for-beginners/</link>
                <guid isPermaLink="false">67853e7ede435f43fdeb589d</guid>
                
                    <category>
                        <![CDATA[ Databases ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Relational Database ]]>
                    </category>
                
                    <category>
                        <![CDATA[ SQL ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Beginner Developers ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Zubair Idris Aweda ]]>
                </dc:creator>
                <pubDate>Mon, 13 Jan 2025 16:25:34 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1736785487594/67bc81b6-1af8-46a0-8a7a-489896879828.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In today’s digital world, data is everywhere, and it’s at the heart of most modern applications. Databases are the unsung heroes that keep it all organised and accessible. Many sites use databases, from social media platforms to online shopping retailers.  </p>
<p>But what exactly is a database, and how does it work? This article will give you a foundational understanding of core DB concepts like:</p>
<ul>
<li><p>What databases are</p>
</li>
<li><p>Different database models</p>
</li>
<li><p>Database Management Systems (DBMS)</p>
</li>
<li><p>How Relational Database models work</p>
</li>
<li><p>Basics of Structured Query Language (SQL)</p>
</li>
</ul>
<p>Whether you’re a beginner or just looking to refresh your knowledge, this article will help you learn the essentials.</p>
<h2 id="heading-what-is-a-database">What Is A Database?</h2>
<p>A database is a collection of information – information that’s preferably related, and preferably organised. This means that a database can be in any form or shape. It could be a pile of paper records in an office, or a large Excel sheet, or on a computer (most likely in this day and age). But in the most basic terms, a database just helps you store data – so ultimately you can decide what it is.</p>
<p>In the digital world, a database consists of physical files on your computer, or in a cloud computer. These files are installed (or downloaded) when you set up the database software on your computer.</p>
<p>A database allows you to record, organise, manage, retrieve, and update that data efficiently. A database is usually structured, organised, and containing related information, otherwise it will just be a pile of random data.</p>
<p>The structure of a database consists of two main parts, the <strong>data</strong> and the <strong>metadata</strong>.</p>
<ul>
<li><p><strong>data</strong> is the actual information stored in the database. So for example, a database of football players would contain information about players like their names, ages, clubs, and so on.</p>
</li>
<li><p><strong>metadata</strong> is the structural description of the data in a database. It describes the names of <strong>fields</strong> used to store data, the length of those fields (where applicable), and their <strong>datatypes</strong>. metadata gives structure and organisation to raw data.</p>
</li>
</ul>
<h2 id="heading-how-to-update-a-database">How to Update a Database</h2>
<p>You can make changes to the different parts of a database using various commands. There are two general types of commands:</p>
<h3 id="heading-data-definition-language-ddl"><strong>Data Definition Language (DDL)</strong></h3>
<p>First, we have Data Definition Language, or DDL. It’s made up of commands that define or alter the shape or structure of the data in the database. These commands affect the metadata part of a database.</p>
<p>You might make alterations like creating new tables in a relational database, changing the shape of documents in a document-based database by adding new fields, or removing an entire graph in a graph database. DDL might define a field as a specific data type, for example, the "date" type, ensuring only valid dates can be entered.</p>
<h3 id="heading-data-manipulation-language-dml"><strong>Data Manipulation Language (DML)</strong></h3>
<p>We also have Data Manipulation Language, or DML. It’s made up of commands that interact with the data stored in the database. These commands do not affect the structure of the data, but rather the data itself. These command only affect the data part of a database.</p>
<p>Some of the things you can do with DML include reading data from a database, adding new data to the database, editing data, and deleting data.</p>
<p>Applications like <a target="_blank" href="https://tableplus.com">TablePlus</a> let you see the data and the metadata in a database. For example, the data and metadata parts of a football application might look like the images below, respectively:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1735566678439/3f33f183-ebe5-40a3-98d1-d8462dab9dbb.png" alt="database data" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1735566701148/894a87f3-3bc7-43d9-908a-dbb2e92710c3.png" alt="database metadata" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>A <strong>datatype</strong> defines what type of information can be stored in a field. Datatypes help computers understand how to store, process, and use data efficiently.</p>
<p>So a field in a table with a datatype of <code>date</code> will only be able to store date records, and will throw an error if you try to store something else, like a name. The same goes for a field with a <code>number</code> datatype – it will only accept numbers, and can be set to accept values within a range or to a certain number of decimal points.</p>
<p>Common datatypes include <code>varchar</code> for data that might contain different characters (text + numbers), <code>date</code> for date values, <code>int</code> for whole numbers, and so on. You can find other common database datatypes <a target="_blank" href="https://teachcomputerscience.com/database-data-types/">here</a>.</p>
<h2 id="heading-what-is-a-database-model">What Is a Database Model?</h2>
<p>A database model is a concept used to describe the information stored on a database. Think of it as a building’s blueprint designed by an architect. It details all the tables, columns, and datatypes of the database. But it, in itself, is not a physical entity like the database. A database model determines how data is logically represented and accessed.</p>
<p>Database models define if data is stored in tables using rows and columns, or in JSON-like objects. They also define how data relates, how you can query it, and how you manage it. Database models are often chosen (and often developed) to suit specific data/application needs.</p>
<h3 id="heading-popular-database-models">Popular database models:</h3>
<p><strong>Relational Model</strong>: The Relational Model is the most popular database model. This model uses tables with rows and columns to store data. This model uses the SQL language to manage the data.</p>
<p>Examples of some relational databases include MySQL, PostgreSQL, and SQLite. This model is popularly used for general-purpose applications that require structured, and often related, data and complex queries. The rest of the article will focus on this model.</p>
<p><strong>Document Model</strong>: Data is stored as documents, often in JSON or XML format, in this model. Databases like MongoDB and CouchDB use this model. Document DBs promote flexibility with their JSON-like structures, and they’re commonly used in applications dealing with semi-structured data or hierarchical data, where flexibility is key.</p>
<p><strong>Key-Value Model</strong>: In this model, data is stored as simple key-value pairs, like in a map in programming. This model is used by Redis and DynamoDB. Due to the simplicity of this model, it is used in high-performance scenarios for simple lookups or caching.</p>
<p><strong>Graph Model</strong>: this model uses nodes (entities) and edges (relationships) to manage data. Neo4j and Amazon Neptune are examples of databases using this model. The shape of the nodes and edges in the graph model make it a common choice in applications involving relationships or connections between data points.</p>
<p>There are many more database models. You can find and study them <a target="_blank" href="https://www.lucidchart.com/pages/database-diagram/database-models">here</a> if you’d like more info.</p>
<h2 id="heading-how-do-relational-databases-work">How Do Relational Databases Work?</h2>
<blockquote>
<p>A relational database has the ability to establish links – or relationships – between information by joining tables, which makes it easy to understand and gain insights about the relationship between various data points. - <a target="_blank" href="https://cloud.google.com/learn/what-is-a-relational-database?hl=en">Google</a></p>
</blockquote>
<p>The relational database model was developed as an improvement to an older database model, the Hierarchical Database model. Relational databases build on it and improve some of its restrictions and relationships. The tables in a relational DB model are often called <strong>relations</strong>.</p>
<p>Each row in a database table represents a single <strong>record</strong> in the table. The row tells the full story of the data. It contains data for all the columns in that table for one specific entity.</p>
<p>For example, in a table storing information about football players, each row represents one player and will include player details like name, age, country, and so on. Rows are also sometimes referred to as <strong>records</strong> or <strong>tuples</strong> in database terminology.</p>
<p>Each column lists an attribute of the record in question, such as name, age, or country. The column only tells a small part of the story. Each column has a name and a datatype, and it applies to all rows in the table. These columns could also have constraints in addition to their datatypes. These constraints could be as simple as the <strong><em>NOT NULL</em></strong> constraint that says that the column can not be empty on any row, or as complex as you define it.</p>
<p>For example, in a table of football players, columns might include “name”, “age”, and “country”. All rows in the table will have values under these columns for their respective attributes. In some contexts, <strong>columns</strong> are also referred to as <strong>fields</strong>.</p>
<p>The “relational” part of the name Relational Databases is often attributed to the fact that this model focuses on how data relates with other data, and how tables relate to each other. For example, tables can be linked (related) together. Tables can also be independent.</p>
<p>Despite this flexibility with relationships, the data in a table can be accessed directly without having knowledge of related or unrelated tables. You can easily access <strong>records</strong> as long as you know what you’re looking for. <strong>Primary</strong> and <strong>Foreign</strong> keys are used in the relational model to manage these relationships.</p>
<h2 id="heading-what-is-a-database-management-system-dbms">What Is a DataBase Management System (DBMS)?</h2>
<p>A DataBase Management System (DBMS) is a collection of programs for managing and communicating with an underlying database engine. In simpler terms, a DBMS is the database engine coupled with whatever additional tools that come with it.</p>
<p>A DBMS helps you create, manage, and use databases. It provides an abstraction over the database engine and lets you more easily store, update, and retrieve data in a secure way.</p>
<p>The tools that come in a DBMS can include, but are not always limited to:</p>
<ul>
<li><p>frontend tools (like a query interface, or an administration panel) that help you run queries and visualise the resulting data in the database</p>
</li>
<li><p>backup and recovery tools that work in the background with little to no user interaction</p>
</li>
<li><p>security tools for user access management (roles and permissions)</p>
</li>
<li><p>and data import or export tools.</p>
</li>
</ul>
<p>And as you would imagine, DBMS are usually model-specific, so there are DBMS focused on the Relational Database Model called RDBMS, where the <strong>“R”</strong> is for Relational. Examples of popular RDBMS include MySQL, PostgreSQL, Oracle, and Microsoft SQL Server. RDBMS use <strong>SQL</strong> (Structured Query Language) to interact with the data.</p>
<h2 id="heading-sql-basics">SQL Basics</h2>
<blockquote>
<p>Structured query language (SQL) is a programming language for storing and processing information in a relational database. You can use SQL statements to store, update, remove, search, and retrieve information from a database. You can also use SQL to maintain and optimise database performance. - <a target="_blank" href="https://aws.amazon.com/what-is/sql/">Amazon</a></p>
</blockquote>
<p>It serves as the primary interface for interacting with databases, allowing users to perform various operations such as creating, modifying, querying, and deleting data and database structures. It’s the base upon which RDBMS like MySQL, PostgreSQL, and SQLite are built, with their own optimisations and extensions.</p>
<p>In this section, we’ll take a look at some basic SQL commands, with practical examples.</p>
<h3 id="heading-ddl-commands">DDL Commands</h3>
<h4 id="heading-1-create">1. <code>CREATE</code></h4>
<p>This is the SQL command used to create and define new database objects. It's a part of the <strong>Data Definition Language (DDL)</strong>, and its primary function is to establish the structure or schema of the database.</p>
<p>You can use this command to do the following (amongst many other uses):</p>
<ul>
<li><p>Create new databases</p>
</li>
<li><p>Create new tables</p>
</li>
<li><p>Create a new index in a table</p>
</li>
<li><p>Create views</p>
</li>
<li><p>Create a user with specific access rights</p>
</li>
</ul>
<p><code>CREATE</code> is most commonly used however to create a table in a database, or to create the database itself (although you usually do this using the GUI options the RDBMS provides).</p>
<p>This command has the following structure:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">CREATE</span> OBJECT_TYPE object_name (optional_further_arguments)
</code></pre>
<p>The <code>ENTITY_TYPE</code> is a placeholder and could be <code>DATABASE</code>, <code>TABLE</code>, <code>VIEW</code>, and so on from the list of database objects. The <code>entity_name</code> defines the name for the object being created. And finally, the <code>optional_further_arguments</code> is used to show that some of the objects only need a name to be created, while others like tables need more context about the columns of the table.</p>
<p>So based on our example of a football application, creating the <code>football_db</code> database above would involve first creating the database, like this:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">DATABASE</span> football_db;
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1736520482758/7231e225-2dcc-407a-95b4-0684eca078d6.png" alt="CREATE DATABASE" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>This command creates a new database with the provided name, <code>football_db</code>. Next up, using the <code>CREATE</code> command followed by the object type <code>TABLE</code>, you can create a <code>players</code> table, like this:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> <span class="hljs-string">`players`</span> (
    <span class="hljs-string">`id`</span> <span class="hljs-built_in">int</span> PRIMARY <span class="hljs-keyword">KEY</span> AUTO_INCREMENT,
    <span class="hljs-string">`name`</span> <span class="hljs-built_in">varchar</span>(<span class="hljs-number">100</span>) <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>,
    <span class="hljs-string">`age`</span> <span class="hljs-built_in">int</span> <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>,
    <span class="hljs-string">`country`</span> <span class="hljs-built_in">varchar</span>(<span class="hljs-number">100</span>) <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>,
    <span class="hljs-string">`level`</span> enum(<span class="hljs-string">'Academy'</span>, <span class="hljs-string">'Amateur'</span>, <span class="hljs-string">'SemiPro'</span>, <span class="hljs-string">'Professional'</span>) <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>,
    <span class="hljs-string">`position`</span> enum(<span class="hljs-string">'Goalkeeper'</span>, <span class="hljs-string">'Defender'</span>, <span class="hljs-string">'Midfielder'</span>, <span class="hljs-string">'Striker'</span>) <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>,
    <span class="hljs-string">`foot`</span> <span class="hljs-built_in">varchar</span>(<span class="hljs-number">6</span>) <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>,
    <span class="hljs-string">`club`</span> <span class="hljs-built_in">varchar</span>(<span class="hljs-number">100</span>) <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>,
    <span class="hljs-string">`scores`</span> <span class="hljs-keyword">json</span> <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>,
    <span class="hljs-string">`jerseyNumber`</span> <span class="hljs-built_in">int</span> <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>
);
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1736522720503/57b09674-8058-4d86-80ea-4d942276bba0.png" alt="CREATE players TABLE" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>The command creates a table called <code>players</code>, and defines the columns (<code>id</code>, <code>name</code>, <code>age</code>, <code>country</code>, <code>level</code>, <code>position</code>, <code>foot</code>, <code>club</code>, <code>scores</code>, <code>jerseyNumber</code>) with their datatypes (<code>int</code>, <code>varchar</code>, <code>enum</code>, <code>json</code>). It also defines their constraints (<code>PRIMARY KEY</code>, <code>AUTO_INCREMENT</code>, <code>NOT NULL</code>).</p>
<h4 id="heading-2-alter">2. <code>ALTER</code></h4>
<p>This command modifies the structure of an existing table. This command is versatile and allows for a wide range of table modifications. These include adding, removing, modifying, and renaming columns, and managing constraints and indexes.</p>
<p>To add a new <code>height</code> column to the newly created <code>players</code> table, you can use the <code>ALTER</code> command like this:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">ALTER</span> <span class="hljs-keyword">TABLE</span> players
<span class="hljs-keyword">ADD</span> height <span class="hljs-built_in">INT</span> <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>;
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1736523536743/e45d03ec-af8c-463f-ac2c-e34e36939ea1.png" alt="ALTER players TABLE" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>The command runs successfully and the new column, defined as an integer column, gets added.</p>
<h4 id="heading-3-drop">3. <code>DROP</code></h4>
<p>This command deletes an existing table or database. When you use the <code>DROP</code> command, it completely removes the object from the database, and this action is irreversible. You can use us to remove databases, tables, and indexes.</p>
<p>If you ever stop using the <code>players</code> table, you can easily delete it using the <code>DROP</code> command like this:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">DROP</span> <span class="hljs-keyword">TABLE</span> players;
</code></pre>
<h4 id="heading-4-truncate">4. <code>TRUNCATE</code></h4>
<p>This command removes all data from a table while preserving its structure. This same result can be achieved using the <code>DELETE</code> DML command.</p>
<h3 id="heading-dml-commands">DML Commands</h3>
<p>These DML commands are foundational for <strong>CRUD operations</strong>, which stand for <strong>Create, Read, Update, and Delete</strong> – the basic actions you perform with data in a database.</p>
<h4 id="heading-1-insert">1. <code>INSERT</code></h4>
<p>Adds a new record to the database. This is the Create part of CRUD.</p>
<p>The command has the structure like this:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span> table_name (column1, column2, column3, ...)
<span class="hljs-keyword">VALUES</span> (value1, value2, value3, ...);
</code></pre>
<p>The <code>INSERT INTO</code> is the first part of the query, it is mandatory and followed by the name of the table to insert into. The name of the table to insert into is represented by the <code>table_name</code> placeholder. The name can then be followed by a list of columns to populate, or the <code>VALUES</code> keyword. In case when the columns to populate are listed, the list of values has to have the same length as the length of the columns provided, as each entry in both lists will be mapped. In case when the columns to populate are not listed, the items in the values list are mapped to the database columns, and every column will have to be provided. The command also allows for the insertion of multiple records at the same time, following same rules as singe insertions, just with comma-separated multiple lists of values to insert.</p>
<p>To add a few players to the <code>players</code> table to achieve a similar result as in the first screenshot, you can use a couple of insert commands like this:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span>
    <span class="hljs-string">`players`</span> (<span class="hljs-string">`id`</span>, <span class="hljs-string">`name`</span>, <span class="hljs-string">`age`</span>, <span class="hljs-string">`country`</span>, <span class="hljs-string">`level`</span>, <span class="hljs-string">`position`</span>, <span class="hljs-string">`foot`</span>, <span class="hljs-string">`club`</span>, <span class="hljs-string">`scores`</span>, <span class="hljs-string">`jerseyNumber`</span>, <span class="hljs-string">`height`</span>)
<span class="hljs-keyword">VALUES</span>
    (<span class="hljs-number">1</span>, <span class="hljs-string">'Christiano Ronaldo'</span>, <span class="hljs-number">36</span>, <span class="hljs-string">'Portugal'</span>, <span class="hljs-string">'Professional'</span>, <span class="hljs-string">'Striker'</span>, <span class="hljs-string">'Right'</span>, <span class="hljs-string">'Manchester United'</span>, <span class="hljs-string">'\"4, 3, 5, 2, 4\"'</span>, <span class="hljs-number">7</span>, <span class="hljs-number">187</span>),
    (<span class="hljs-number">2</span>, <span class="hljs-string">'Alisson Becker'</span>, <span class="hljs-number">31</span>, <span class="hljs-string">'Brazil'</span>, <span class="hljs-string">'Professional'</span>, <span class="hljs-string">'Goalkeeper'</span>, <span class="hljs-string">'Right'</span>, <span class="hljs-string">'Liverpool'</span>, <span class="hljs-string">'\"5, 6, 7, 8, 9\"'</span>, <span class="hljs-number">1</span>, <span class="hljs-number">193</span>),
    (<span class="hljs-number">3</span>, <span class="hljs-string">'John Stones'</span>, <span class="hljs-number">30</span>, <span class="hljs-string">'England'</span>, <span class="hljs-string">'Professional'</span>, <span class="hljs-string">'Defender'</span>, <span class="hljs-string">'Right'</span>, <span class="hljs-string">'Manchester City'</span>, <span class="hljs-string">'\"4, 5, 6, 7, 8\"'</span>, <span class="hljs-number">5</span>, <span class="hljs-number">188</span>),
    (<span class="hljs-number">4</span>, <span class="hljs-string">'Kevin DeBruyne'</span>, <span class="hljs-number">33</span>, <span class="hljs-string">'Belgium'</span>, <span class="hljs-string">'Professional'</span>, <span class="hljs-string">'Midfielder'</span>, <span class="hljs-string">'Right'</span>, <span class="hljs-string">'Manchester City'</span>, <span class="hljs-string">'\"9, 8, 7, 6, 5\"'</span>, <span class="hljs-number">17</span>, <span class="hljs-number">181</span>),
    (<span class="hljs-number">5</span>, <span class="hljs-string">'Erling Haaland'</span>, <span class="hljs-number">24</span>, <span class="hljs-string">'Norway'</span>, <span class="hljs-string">'Professional'</span>, <span class="hljs-string">'Striker'</span>, <span class="hljs-string">'Right'</span>, <span class="hljs-string">'Manchester City'</span>, <span class="hljs-string">'\"10, 9, 8, 7, 6\"'</span>, <span class="hljs-number">9</span>, <span class="hljs-number">194</span>),
    (<span class="hljs-number">6</span>, <span class="hljs-string">'Chris Waddle'</span>, <span class="hljs-number">20</span>, <span class="hljs-string">'England'</span>, <span class="hljs-string">'SemiPro'</span>, <span class="hljs-string">'Midfielder'</span>, <span class="hljs-string">'Left'</span>, <span class="hljs-string">'Tow Law Town'</span>, <span class="hljs-string">'\"3, 4, 5, 6, 7\"'</span>, <span class="hljs-number">11</span>, <span class="hljs-number">183</span>),
    (<span class="hljs-number">7</span>, <span class="hljs-string">'Ian Wright'</span>, <span class="hljs-number">25</span>, <span class="hljs-string">'England'</span>, <span class="hljs-string">'SemiPro'</span>, <span class="hljs-string">'Striker'</span>, <span class="hljs-string">'Right'</span>, <span class="hljs-string">'Greenwich Borough'</span>, <span class="hljs-string">'\"4, 5, 6, 7, 8\"'</span>, <span class="hljs-number">8</span>, <span class="hljs-number">175</span>),
    (<span class="hljs-number">8</span>, <span class="hljs-string">'Charlie Austin'</span>, <span class="hljs-number">34</span>, <span class="hljs-string">'England'</span>, <span class="hljs-string">'SemiPro'</span>, <span class="hljs-string">'Striker'</span>, <span class="hljs-string">'Right'</span>, <span class="hljs-string">'Poole Town'</span>, <span class="hljs-string">'\"5, 6, 7, 8, 9\"'</span>, <span class="hljs-number">9</span>, <span class="hljs-number">188</span>),
    (<span class="hljs-number">9</span>, <span class="hljs-string">'Troy Deeney'</span>, <span class="hljs-number">33</span>, <span class="hljs-string">'England'</span>, <span class="hljs-string">'SemiPro'</span>, <span class="hljs-string">'Striker'</span>, <span class="hljs-string">'Right'</span>, <span class="hljs-string">'Chelmsley Town'</span>, <span class="hljs-string">'\"6, 7, 8, 9, 10\"'</span>, <span class="hljs-number">9</span>, <span class="hljs-number">183</span>),
    (<span class="hljs-number">10</span>, <span class="hljs-string">'Rickie Lambert'</span>, <span class="hljs-number">39</span>, <span class="hljs-string">'England'</span>, <span class="hljs-string">'SemiPro'</span>, <span class="hljs-string">'Striker'</span>, <span class="hljs-string">'Right'</span>, <span class="hljs-string">'Macclesfield Town'</span>, <span class="hljs-string">'\"7, 8, 9, 10, 11\"'</span>, <span class="hljs-number">9</span>, <span class="hljs-number">187</span>);
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1736525270444/ce1739aa-7fef-48d0-b61a-6cee1267ab1a.png" alt="INSERT INTO players TABLE" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<h4 id="heading-2-select">2. <code>SELECT</code></h4>
<p>The <code>SELECT</code> command has the basic syntax:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> column1, column2, ...
<span class="hljs-keyword">FROM</span> table_name
<span class="hljs-keyword">WHERE</span> condition;
</code></pre>
<p>The command has the following parts:</p>
<ul>
<li><p><code>SELECT</code> is the mandatory keyword that begins every query,</p>
</li>
<li><p><code>column1, column2, …</code> is a placeholder for the list of columns to be retrieved. This is especially useful when dealing with large tables as you do not always want to display all columns every time. To display all columns, replace the list with the <code>*</code> character.</p>
</li>
<li><p><code>FROM</code> is another mandatory keyword that is followed by the name of the table to fetch the data from,</p>
</li>
<li><p><code>table_name</code> is the name of the table the data should come from.</p>
</li>
<li><p><code>WHERE condition</code> is one of the optional commands that can be attached to the <code>SELECT</code> command. It is used to filter the records by specific conditions.</p>
</li>
</ul>
<p>This is the Read part of CRUD. The simplest form of the <code>SELECT</code> command is used to view all records in a table (all columns and rows):</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> players;
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1736526168218/a8b4c51c-afb6-4228-885b-2620bd99cf93.png" alt="SELECT ALL players" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<h4 id="heading-3-update">3. <code>UPDATE</code></h4>
<p>The <code>UPDATE</code> command modifies existing records in the database. This is the Update part of CRUD.</p>
<p>To update the details of Christiano Ronaldo to be more accurate, you can use the <code>UPDATE</code> command like this:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">UPDATE</span> <span class="hljs-string">`players`</span>
<span class="hljs-keyword">SET</span>
    <span class="hljs-string">`name`</span> = <span class="hljs-string">'Cristiano Ronaldo'</span>,
    <span class="hljs-string">`age`</span> = <span class="hljs-number">38</span>,
    <span class="hljs-string">`club`</span> = <span class="hljs-string">'Al Nassr'</span>
<span class="hljs-keyword">WHERE</span>
    <span class="hljs-string">`id`</span> = <span class="hljs-number">1</span>;
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1736526962015/55dd1f1d-a755-40fe-90d2-9975b8df7ba1.png" alt="UPDATE player record" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>This command changes his name slightly, his club from Manchester United to his current club of Al Nassr, and updates his age to 38.</p>
<h4 id="heading-4-delete">4. <code>DELETE</code></h4>
<p>The <code>DELETE</code> command removes records from the database. This is the Delete part of CRUD.</p>
<p>It is syntactically similar to the <code>SELECT</code> command, having a basic syntax like this:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">DELETE</span> <span class="hljs-keyword">FROM</span> table_name
<span class="hljs-keyword">WHERE</span> condition;
</code></pre>
<p>In this structure,</p>
<ul>
<li><p>The <code>DELETE FROM</code> keyword is the mandatory start of any delete queries,</p>
</li>
<li><p>It is followed by the name of the table to be deleted, represented by the <code>table_name</code>.</p>
</li>
<li><p>The <code>WHERE condtion</code> is optional where all the rows of the table are to be deleted. But otherwise, it is used to specify the rows to be deleted by matching a condition.</p>
</li>
</ul>
<p>To remove players not playing at the professional level from the table, you can use a command like this:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">DELETE</span> <span class="hljs-keyword">FROM</span> <span class="hljs-string">`players`</span>
<span class="hljs-keyword">WHERE</span> <span class="hljs-string">`level`</span> != <span class="hljs-string">'Professional'</span>;
</code></pre>
<p>These are the basic commands you’ll use to interact with databases. You can learn more about them <a target="_blank" href="https://www.freecodecamp.org/news/learn-sql-in-10-minutes/">in this SQL command cheatsheet</a>.</p>
<h2 id="heading-summary"><strong>Summary</strong></h2>
<p>Databases are a cornerstone of modern technology, and understanding their fundamental concepts can open doors to building and managing efficient, data-driven systems.</p>
<p>This article introduced you to the basics of what a database is and how relational database models work. You should now have the essential knowledge to navigate the world of databases confidently.</p>
<p>To deepen your understanding, consider exploring the following:</p>
<ul>
<li><p><strong>Hands-On Practice</strong>: Use tools like <a target="_blank" href="https://tableplus.com/">TablePlus</a> to interact with relational databases.</p>
</li>
<li><p><strong>Learning SQL</strong>: Start with beginner-friendly SQL tutorials like <a target="_blank" href="https://www.freecodecamp.org/news/learn-sql-full-course/">this course on freeCodeCamp’s YouTube channel</a> or <a target="_blank" href="https://www.freecodecamp.org/news/learn-sql-in-10-minutes/">this SQL command cheatsheet</a>.</p>
</li>
<li><p><strong>Experiment with Non-Relational Databases</strong>: Try <a target="_blank" href="https://www.freecodecamp.org/news/how-to-start-using-mongodb/">MongoDB</a> or <a target="_blank" href="https://www.freecodecamp.org/news/learn-neo4j-database-course/">Neo4j</a> to explore how other database models work.</p>
</li>
</ul>
<p>If you’re curious to learn more, connect with me on <a target="_blank" href="https://www.linkedin.com/in/idris-aweda-zubair-5433121a3/">LinkedIn</a>, <a target="_blank" href="https://twitter.com/AwedaIdris">Twitter</a>, or <a target="_blank" href="https://github.com/Zubs">GitHub</a>. Let’s continue this journey together toward mastering database systems!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Collect.js Tutorial – How to Work with JavaScript Arrays and Objects ]]>
                </title>
                <description>
                    <![CDATA[ JavaScript arrays are one of the most important data structures in the language, since everything is already an object in JavaScript. They're useful in so many applications, and many other data structures build on top of JavaScript arrays and objects... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/work-with-javascript-arrays-objects-with-collect-js/</link>
                <guid isPermaLink="false">66c4c6b6744830ebca763795</guid>
                
                    <category>
                        <![CDATA[ arrays ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ object ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Zubair Idris Aweda ]]>
                </dc:creator>
                <pubDate>Mon, 08 Jan 2024 22:38:20 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/01/zub.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>JavaScript arrays are one of the most important data structures in the language, since everything is already an object in JavaScript.</p>
<p>They're useful in so many applications, and many other data structures build on top of JavaScript arrays and objects. While the language provides a lot of helpful array and object methods, you can take it even a step further using Collect.js.</p>
<p>This article takes you through:</p>
<ul>
<li><a class="post-section-overview" href="#heading-what-is-collectjs">What is Collect.js</a>?</li>
<li><a class="post-section-overview" href="#heading-how-to-install-collectjs">How to install Collect.js</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-collectjs">How to Use Collect.js</a></li>
<li><a class="post-section-overview" href="#heading-some-collectjs-methods">Some Collect.js Methods</a></li>
</ul>
<h2 id="heading-what-is-collectjs">What Is Collect.js?</h2>
<p>The official docs of Collect.js describes it as a "Convenient and dependency free wrapper for working with arrays and objects."</p>
<p>A simpler way to explain this is that Collect.js is a JavaScript library for working with arrays and objects. It provides a layer on top of the built-in functions to make working with them easier.</p>
<p>Collect.js works how <a target="_blank" href="https://laravel.com/docs/10.x/collections">Laravel collections</a> (where the inspiration came from) work. It makes it very easy for Laravel developers, when working with JavaScript, to develop as fast as they would if they were using PHP. But this doesn't mean a native JavaScript developer wouldn't find it really helpful, too.</p>
<p>Collect.js is growing gradually, as it currently has over 6k stars on GitHub and about 200k weekly downloads on NPM at the time of this writing.</p>
<h2 id="heading-how-to-install-collectjs">How to Install Collect.js</h2>
<p>To start using Collect.js in your projects, you have to install it first. Like other JavaScript libraries, you can easily install Collect.js using <code>npm</code> or <code>yarn</code>. You can also install it using a CDN. For this tutorial, we will install it using npm like this:</p>
<pre><code class="lang-bash">npm i collect.js
</code></pre>
<p>After installation, you can import it into the modules where you need it, like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> collect <span class="hljs-keyword">from</span> <span class="hljs-string">'collect.js'</span>;
</code></pre>
<p>And once it has been imported, you can begin making magic with Collect.js.</p>
<p>You can read about other installation methods on the <a target="_blank" href="https://collect.js.org/installation.html">official documentation website</a>.</p>
<h2 id="heading-how-to-use-collectjs">How to Use Collect.js</h2>
<p>After installation and importation, to use Collect.js in your projects you'll need to convert your required data to a Collect.js <strong>collection</strong>.</p>
<p>A Collect.js collection is a JavaScript object that has functions not natively available to regular JavaScript arrays and objects. </p>
<p>To create a collection, simply use the <code>collect</code> method imported earlier on any array or object. It's that simple – here's an example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> students = [<span class="hljs-string">'John'</span>, <span class="hljs-string">'James'</span>, <span class="hljs-string">'Ian'</span>, <span class="hljs-string">'David'</span>];

<span class="hljs-keyword">const</span> studentsCollection = collect(students);
</code></pre>
<p>Now, using an IDE like WebStorm, you can see methods available to the simple collection you just created:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-04-at-17.10.21.png" alt="Image" width="600" height="400" loading="lazy">
<em>List of available methods</em></p>
<p>This article does not cover all of these functions, but you can see that you now have more than JavaScript originally offers through Collect.js.</p>
<h2 id="heading-some-collectjs-methods">Some Collect.js Methods</h2>
<p>To help understand how much Collect.js simplifies common array and object methods, we'll now look at how to use some very useful Collect.js methods.</p>
<h3 id="heading-the-average-method-or-avg">The <code>average</code> method (or avg)</h3>
<p>This method, as you may assume, calculates an average of a collection of numbers. Here's how you use it:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>, <span class="hljs-number">10</span>];
<span class="hljs-keyword">const</span> average = collect(numbers).avg();

<span class="hljs-built_in">console</span>.log(average); <span class="hljs-comment">// 5.5</span>
</code></pre>
<p>In this example, we've create an array of numbers between 1 and 10, inclusive. Then we get the average of these numbers using Collect.js. </p>
<p>To do this in vanilla JavaScript, you would have to first sum the numbers using <code>array.reduce</code> or a loop, then get the length of the original array, and divide the sum by this length. See the below example implementation:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> sum = <span class="hljs-function"><span class="hljs-params">arr</span> =&gt;</span> arr.reduce( <span class="hljs-function">(<span class="hljs-params"> p, c </span>) =&gt;</span> p + c, <span class="hljs-number">0</span> );
<span class="hljs-keyword">const</span> size = numbers.length;
<span class="hljs-keyword">const</span> average = sum(numbers) / size;

<span class="hljs-built_in">console</span>.log(average); <span class="hljs-comment">// 5.5</span>
</code></pre>
<p>You can see that it's way easier and more elegant using Collect.js.</p>
<p>You can also use the average method directly on more complex structures like an array of objects. Here's an example where the average score of a class of students, stored in an array of students details with a <code>scores</code> key, is calculated using Collect.js:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> studentsDetails = [
    { <span class="hljs-attr">name</span>: <span class="hljs-string">'John'</span>, <span class="hljs-attr">score</span>: <span class="hljs-number">40</span>, <span class="hljs-attr">subject</span>: <span class="hljs-string">'Maths'</span> },
    { <span class="hljs-attr">name</span>: <span class="hljs-string">'James'</span>, <span class="hljs-attr">score</span>: <span class="hljs-number">70</span>, <span class="hljs-attr">subject</span>: <span class="hljs-string">'Science'</span> },
    { <span class="hljs-attr">name</span>: <span class="hljs-string">'Ian'</span>, <span class="hljs-attr">score</span>: <span class="hljs-number">50</span>, <span class="hljs-attr">subject</span>: <span class="hljs-string">'Maths'</span> },
    { <span class="hljs-attr">name</span>: <span class="hljs-string">'David'</span>, <span class="hljs-attr">score</span>: <span class="hljs-number">60</span>, <span class="hljs-attr">subject</span>: <span class="hljs-string">'Science'</span> },
];

<span class="hljs-keyword">const</span> studentsCollection = collect(studentsDetails);
<span class="hljs-keyword">const</span> averageScore = studentsCollection.avg(<span class="hljs-string">'score'</span>);
<span class="hljs-built_in">console</span>.log(averageScore); <span class="hljs-comment">// 55</span>
</code></pre>
<p>Here the average is gotten in a very straightforward approach and takes less effort than doing it in vanilla JavaScript. And it uses the short hand <code>avg</code> instead of the longer <code>average</code>.</p>
<h3 id="heading-the-chunk-method">The <code>chunk</code> method</h3>
<p>This method breaks an array into smaller bits based on a given size. This is a common operation when dealing with JavaScript arrays in real life. A common use case would be in pagination of records.</p>
<p>Using the same <code>studentsDetails</code> array created in the last example, I could break down the collection into groups of two using the <code>chunk</code> method, like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> studentsCollection = collect(studentsDetails);
<span class="hljs-keyword">const</span> studentGroups = studentsCollection.chunk(<span class="hljs-number">2</span>);
</code></pre>
<p>This breaks down the original <code>studentsCollection</code> array into two sub collections that look like this:</p>
<pre><code class="lang-js">Collection {
  <span class="hljs-attr">items</span>: [
    { <span class="hljs-attr">name</span>: <span class="hljs-string">'John'</span>, <span class="hljs-attr">score</span>: <span class="hljs-number">40</span>, <span class="hljs-attr">subject</span>: <span class="hljs-string">'Maths'</span> },
    { <span class="hljs-attr">name</span>: <span class="hljs-string">'James'</span>, <span class="hljs-attr">score</span>: <span class="hljs-number">70</span>, <span class="hljs-attr">subject</span>: <span class="hljs-string">'Science'</span> }
  ]
}
Collection {
  <span class="hljs-attr">items</span>: [
    { <span class="hljs-attr">name</span>: <span class="hljs-string">'Ian'</span>, <span class="hljs-attr">score</span>: <span class="hljs-number">50</span>, <span class="hljs-attr">subject</span>: <span class="hljs-string">'Maths'</span> },
    { <span class="hljs-attr">name</span>: <span class="hljs-string">'David'</span>, <span class="hljs-attr">score</span>: <span class="hljs-number">60</span>, <span class="hljs-attr">subject</span>: <span class="hljs-string">'Science'</span> }
  ]
}
</code></pre>
<p>To achieve a similar result in vanilla JavaScript takes more effort as you would require a loop:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> chunkedArray = [];
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; studentsDetails.length; i += <span class="hljs-number">2</span>) {
    <span class="hljs-keyword">const</span> chunk = studentsDetails.slice(i, i + <span class="hljs-number">2</span>);
    chunkedArray.push(chunk);
}

<span class="hljs-built_in">console</span>.log(chunkedArray);
</code></pre>
<h3 id="heading-the-contains-method">The <code>contains</code> method</h3>
<p>You can use this method to check whether some key or value exists in a collection. This function allows you to check regardless of the shape or structure of the data.</p>
<p>For example, to check the existing <code>studentDetails</code> for the subject <code>Physics</code>, you can do this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> studentsDetailsCollection = collect(studentsDetails);

<span class="hljs-built_in">console</span>.log(studentsDetailsCollection.contains(<span class="hljs-string">'Physics'</span>)); <span class="hljs-comment">// false</span>
</code></pre>
<p>To check if we have a student named <code>Science</code> instead of the subject, we could specify what field to check by passing in the field name as a first parameter before the search value:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> studentsDetailsCollection = collect(studentsDetails);

<span class="hljs-built_in">console</span>.log(studentsDetailsCollection.contains(<span class="hljs-string">'name'</span>, <span class="hljs-string">'Science'</span>)); <span class="hljs-comment">// false</span>
</code></pre>
<p>You can even check to see if the collection contains values that match a certain condition. Like to see if any student scored more than 50:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> studentsDetailsCollection = collect(studentsDetails);

<span class="hljs-built_in">console</span>.log(studentsDetailsCollection.contains(<span class="hljs-function">(<span class="hljs-params">value, key</span>) =&gt;</span> value.score &gt; <span class="hljs-number">50</span>)); <span class="hljs-comment">// true</span>
</code></pre>
<p>To perform any of these checks in vanilla JavaScript would involve using a loop to check each object in the array. You could also do it using the <code>some</code> method.</p>
<h3 id="heading-the-diff-method">The <code>diff</code> method</h3>
<p>This method is used to get the difference between two collections. The collections could be plain arrays or array of objects. </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> numbers = collect([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>, <span class="hljs-number">10</span>]);
<span class="hljs-keyword">const</span> primeNumbers = collect([<span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">5</span>, <span class="hljs-number">7</span>]);

<span class="hljs-built_in">console</span>.log(numbers.diff(primeNumbers).all()); <span class="hljs-comment">// [ 1, 4, 6, 8, 9, 10 ]</span>
</code></pre>
<p>Here we get the numbers that are not prime between 1 and 10 inclusive by removing the array of primeNumbers from the array of those numbers using the <code>diff</code> method.</p>
<h3 id="heading-the-get-method">The <code>get</code> method</h3>
<p>This method is used to get values from a collection. If the collection was created from an array, it can accept the array index to return the value at that position. </p>
<p>If the collection was created from an object, it can accept a key and return the value for that key. It returns <code>null</code> when no value is found. You can pass in a default value to prevent it from returning <code>null</code>.</p>
<p>Using the <code>numbers</code> collection created in the last example, you can get the first and twelfth elements, and return 10 if it doesn't exist, like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> firstNumber = numbers.get(<span class="hljs-number">0</span>);
<span class="hljs-keyword">const</span> twelfthNumber = numbers.get(<span class="hljs-number">11</span>, <span class="hljs-number">10</span>);

<span class="hljs-built_in">console</span>.log(firstNumber); <span class="hljs-comment">// 1</span>
<span class="hljs-built_in">console</span>.log(twelfthNumber); <span class="hljs-comment">// 10</span>
</code></pre>
<p>The <code>firstNumber</code> returns 1 as expected, but the <code>twelfthNumber</code> returns 10, instead of returning <code>null</code> or throwing an error. This is very useful when dealing with user inputs and having optional parameters.</p>
<h3 id="heading-the-all-method">The <code>all</code> method</h3>
<p>This method has already been used in a few examples, so you can probably guess it's usage already. You use it to get the object or array under the collection.</p>
<p>Using this method on the <code>numbers</code> collection just returns the original array of numbers:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(numbers.all()); <span class="hljs-comment">// [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]</span>
</code></pre>
<h3 id="heading-the-groupby-method">The <code>groupBy()</code> method</h3>
<p>If you have any SQL experience, this method name will sound familiar. It works similarly to the SQL function, too: it groups data in a collection by a given key. </p>
<p>Using this method, we can group the students by the subject offered, like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> studentsGroupedBySubject = collect(studentsDetails).groupBy(<span class="hljs-string">'subject'</span>);
<span class="hljs-built_in">console</span>.log(studentsGroupedBySubject.all());
</code></pre>
<p>This will create two subcollections for the two subjects, maths and physics.</p>
<pre><code class="lang-js">{
  <span class="hljs-attr">Maths</span>: Collection { <span class="hljs-attr">items</span>: [ [<span class="hljs-built_in">Object</span>], [<span class="hljs-built_in">Object</span>] ] },
  <span class="hljs-attr">Science</span>: Collection { <span class="hljs-attr">items</span>: [ [<span class="hljs-built_in">Object</span>], [<span class="hljs-built_in">Object</span>] ] }
}
</code></pre>
<h3 id="heading-the-isempty-and-isnotempty-methods">The <code>isEmpty</code> and <code>isNotEmpty</code> methods</h3>
<p>The <code>isEmpty</code> method checks is a collection is empty, and the <code>isNotEmpty</code> checks otherwise. These methods help prevent the <a target="_blank" href="https://learn.snyk.io/lesson/prototype-pollution/">object spoofing</a> vulnerability.</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(numbers.isEmpty()) <span class="hljs-comment">// false</span>
<span class="hljs-built_in">console</span>.log(numbers.isNotEmpty()) <span class="hljs-comment">// true</span>
</code></pre>
<h3 id="heading-the-first-and-last-methods">The <code>first</code> and <code>last</code> methods</h3>
<p>These method names are as descriptive as they can be. The <code>first</code> method gets the first element of a collection. It can also be used to get the first that matches a condition.</p>
<p>For example, to get the first student that scores more than 40 in the <code>subject</code> maths, you can use the <code>first</code> method like this:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(studentsDetailsCollection.first(<span class="hljs-function">(<span class="hljs-params">student</span>) =&gt;</span> student.score &gt; <span class="hljs-number">40</span> &amp;&amp; student.subject === <span class="hljs-string">'Maths'</span>));
</code></pre>
<p>The <code>last</code> method is also very similar to the <code>first</code> method. It gets the last element of a collection when called with no condition. When a condition is specified, it gets the last element that matches that condition. </p>
<p>For example, to get the last student that fails maths in the <code>studentsDetailsCollection</code>, use this code:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(studentsDetailsCollection.last(<span class="hljs-function">(<span class="hljs-params">student</span>) =&gt;</span> student.score &lt; <span class="hljs-number">40</span> &amp;&amp; student.subject === <span class="hljs-string">'Maths'</span>));
</code></pre>
<p>This last example returns <code>undefined</code> as no student fails maths.</p>
<p>To acheive these same results using vanilla JavaScript would involve a loop that checks each element and keeps track of the first and last that match the condition, like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> getFirstStudentThatPassesMaths = <span class="hljs-function">(<span class="hljs-params">studentDetails</span>) =&gt;</span> {
    <span class="hljs-keyword">let</span> firstStudentThatPassesMaths = <span class="hljs-literal">undefined</span>;

    studentDetails.forEach(<span class="hljs-function">(<span class="hljs-params">student</span>) =&gt;</span> {
        <span class="hljs-keyword">if</span> (student.subject === <span class="hljs-string">'Maths'</span> &amp;&amp; student.score &gt; <span class="hljs-number">40</span>) {
            firstStudentThatPassesMaths = student;
            <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
        }
    });

    <span class="hljs-keyword">return</span> firstStudentThatPassesMaths;
}

<span class="hljs-keyword">const</span> getLastStudentThatFailsMaths = <span class="hljs-function">(<span class="hljs-params">studentDetails</span>) =&gt;</span> {
    <span class="hljs-keyword">let</span> lastStudentThatFailsMaths = <span class="hljs-literal">undefined</span>;

    studentDetails.forEach(<span class="hljs-function">(<span class="hljs-params">student</span>) =&gt;</span> {
        <span class="hljs-keyword">if</span> (student.subject === <span class="hljs-string">'Maths'</span> &amp;&amp; student.score &lt; <span class="hljs-number">40</span>) {
            lastStudentThatFailsMaths = student;
        }
    });

    <span class="hljs-keyword">return</span> lastStudentThatFailsMaths;
}

<span class="hljs-built_in">console</span>.log(getFirstStudentThatPassesMaths(studentsDetails));
<span class="hljs-built_in">console</span>.log(getLastStudentThatFailsMaths(studentsDetails));
</code></pre>
<p>See how much simpler the Collect.js implementations are.</p>
<h3 id="heading-the-macro-method">The <code>macro</code> method</h3>
<p>This method is very useful, as it allows you even extend Collect.js further by adding your own methods. It has the following structure:</p>
<pre><code class="lang-js">collect().macro(<span class="hljs-string">'functionName'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">// function body</span>
});
</code></pre>
<p>Here, <code>functionName</code> is the name of the new function you're adding, and the function body is where your new logic goes.</p>
<p>For example, to assign grades to students using our <code>studentsDetailsCollection</code>, we can create a new method called <code>grade</code>. We can make it a bit more complex and have the function modify the collection by adding the calculated grade to each student object.</p>
<pre><code class="lang-js">collect().macro(<span class="hljs-string">'grade'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.map(<span class="hljs-function"><span class="hljs-params">item</span> =&gt;</span> {
        <span class="hljs-keyword">if</span> (item.score &gt;= <span class="hljs-number">70</span>) item.grade = <span class="hljs-string">'A'</span>;
        <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (item.score &gt;= <span class="hljs-number">60</span>) item.grade = <span class="hljs-string">'B'</span>;
        <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (item.score &gt;= <span class="hljs-number">50</span>) item.grade = <span class="hljs-string">'C'</span>;
        <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (item.score &gt;= <span class="hljs-number">45</span>) item.grade = <span class="hljs-string">'D'</span>;
        <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (item.score &gt;= <span class="hljs-number">40</span>) item.grade = <span class="hljs-string">'E'</span>;
        <span class="hljs-keyword">else</span> item.grade = <span class="hljs-string">'F'</span>;

        <span class="hljs-keyword">return</span> item;
    });
});
</code></pre>
<p>You can then call the method on the collection like any other built-in method like this:</p>
<pre><code class="lang-js">studentsDetailsCollection.grade();
</code></pre>
<p>After modification, your collection will look like this:</p>
<pre><code class="lang-js">[
  { <span class="hljs-attr">name</span>: <span class="hljs-string">'John'</span>, <span class="hljs-attr">score</span>: <span class="hljs-number">40</span>, <span class="hljs-attr">subject</span>: <span class="hljs-string">'Maths'</span>, <span class="hljs-attr">grade</span>: <span class="hljs-string">'E'</span> },
  { <span class="hljs-attr">name</span>: <span class="hljs-string">'James'</span>, <span class="hljs-attr">score</span>: <span class="hljs-number">70</span>, <span class="hljs-attr">subject</span>: <span class="hljs-string">'Science'</span>, <span class="hljs-attr">grade</span>: <span class="hljs-string">'A'</span> },
  { <span class="hljs-attr">name</span>: <span class="hljs-string">'Ian'</span>, <span class="hljs-attr">score</span>: <span class="hljs-number">50</span>, <span class="hljs-attr">subject</span>: <span class="hljs-string">'Maths'</span>, <span class="hljs-attr">grade</span>: <span class="hljs-string">'C'</span> },
  { <span class="hljs-attr">name</span>: <span class="hljs-string">'David'</span>, <span class="hljs-attr">score</span>: <span class="hljs-number">60</span>, <span class="hljs-attr">subject</span>: <span class="hljs-string">'Science'</span>, <span class="hljs-attr">grade</span>: <span class="hljs-string">'B'</span> }
]
</code></pre>
<h2 id="heading-summary"><strong>Summary</strong></h2>
<p>I hope you now understand how to simplify your JavaScript development using simple Collect.js functions. This article only covers some of the most useful methods, but there are more available. To learn more, refer to the <a target="_blank" href="https://collect.js.org/api.html">official documentation</a>.</p>
<p>If you have any questions or relevant advice, please get in touch with me.</p>
<p>To read more of my articles or follow my work, you can connect with me on <a target="_blank" href="https://www.linkedin.com/in/idris-aweda-zubair-5433121a3/">LinkedIn</a>, <a target="_blank" href="https://twitter.com/AwedaIdris">Twitter</a>, and <a target="_blank" href="https://github.com/Zubs">Github</a>. It’s quick, it’s easy, and it’s free!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is Cloud Computing? Introduction to the Cloud for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ As the digital landscape continues to evolve and technology marches forward, cloud computing has remained an important topic for developers to learn. You've probably encountered cloud requirements in job listings, heard people talk about it in conver... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-cloud-computing/</link>
                <guid isPermaLink="false">66c4c6b3744830ebca763793</guid>
                
                    <category>
                        <![CDATA[ Cloud Computing ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Zubair Idris Aweda ]]>
                </dc:creator>
                <pubDate>Wed, 03 Jan 2024 21:40:31 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/05/cloud-sky.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>As the digital landscape continues to evolve and technology marches forward, cloud computing has remained an important topic for developers to learn.</p>
<p>You've probably encountered cloud requirements in job listings, heard people talk about it in conversations, or seen ads by companies offering cloud services – and now you're interested in learning more about it.</p>
<p>In this article, I'll demystify the cloud for you, breaking down complex concepts into easy-to-understand bits. </p>
<p>Here's what we'll cover in this article:</p>
<ul>
<li><a class="post-section-overview" href="#heading-the-world-before-cloud-computing">The World Before Cloud Computing</a></li>
<li><a class="post-section-overview" href="#heading-what-is-cloud-computing">What Is Cloud Computing?</a></li>
<li><a class="post-section-overview" href="#heading-cloud-service-providers">Cloud Service Providers</a></li>
<li><a class="post-section-overview" href="#heading-different-cloud-services">Different Cloud Services</a></li>
<li><a class="post-section-overview" href="#heading-challenges-that-cloud-computing-helps-solve">Challenges that Cloud Computing Helps Solve</a></li>
<li><a class="post-section-overview" href="#heading-how-can-cloud-computing-help-you">How Can Cloud Computing Help You?</a></li>
<li><a class="post-section-overview" href="#heading-cloud-deployment-models">Cloud Deployment Models</a></li>
</ul>
<p>So let's dive in and learn cloud computing basics so you can start your journey into this growing field.</p>
<h2 id="heading-the-world-before-cloud-computing">The World Before Cloud Computing</h2>
<p>To understand cloud computing, it is important to understand the problem cloud computing tries to solve. This will help you understand its history and appreciate the convenience it brings into the world of technology.</p>
<p>Before the cloud, deploying web services was a very expensive process. To deploy a web application, you had to purchase servers with the correct amount of storage and memory, keep them on-site, setup these servers, and use them to host your application. </p>
<p>This comes with many additional costs, other than the original server costs, like electricity and the data required to keep your server up and online every time. There are also security concerns, as you'll need to prevent your server from being damaged or stolen by bad actors. </p>
<p>Beyond all this, many developers are not exactly server specialists. So you would either have to train your developers to become system admins or hire system admins to setup and configure the servers to work with your applications. Then to deploy a new application, you'd have to repeat the whole process with new costs.</p>
<p>Scaling applications wasn't easy before the cloud. If you tried to manage costs and not buy too many servers, or hire many system engineers, you might end up with insufficient compute power and you'd need to scale. Scaling means buying more servers (or replacing existing ones with better ones), configuring them to match existing configurations, and deploying your applications on them. </p>
<p>These are some of the issues we faced before cloud computing. Now, you might wonder, "how does cloud computing solve these?". Let's find out.</p>
<h2 id="heading-what-is-cloud-computing">What Is Cloud Computing?</h2>
<blockquote>
<p><strong>Cloud computing</strong> is the on-demand availability of computer system resources, especially data storage (cloud storage) and computing power, without direct active management by the user.   </p>
<p>Cloud computing relies on sharing of resources to achieve coherence and typically uses a pay-as-you-go model, which can help in reducing capital expenses but may also lead to unexpected operating expenses for users. – <a target="_blank" href="https://en.wikipedia.org/wiki/Cloud_computing">Wikipedia</a></p>
</blockquote>
<p>Think of Cloud Computing like renting a computer from a cybercafe. In a cybercafe, they have the computers ready for use – you just come in, pay for your desired time, and use the computer for that period. </p>
<p>In the case of cloud computing, you don't have to worry about buying the computer, or protecting it, or covering the running costs. The cloud provider covers all these worries. You rarely ever have to worry about software issues, or the absence of specific software on these computers. And the best part? You only pay for the computer you use, and only for the time you use it.</p>
<p>So in more relatable terms, say you have a web application to deploy. You go to a cloud service provider, select specific server requirements your application requires, select software dependencies, and deploy your application, with zero worries.</p>
<p>Cloud computing as explained to a five year old is <em>"letting someone else manage your computing needs"</em>. You have some website that you need to put online, or maybe a mobile app, or some other piece of technology, and instead of having to buy servers to deploy it, someone else buys and sets up the servers. You simply upload your files. Its almost the same as renting an apartment, but now you are renting compute space on another computer.</p>
<h2 id="heading-cloud-service-providers">Cloud Service Providers</h2>
<p>Companies that provide these cloud services are called cloud services providers. These companies already have many servers, and system engineers. They're concerned with all the stuff you don't have to worry about like server costs and running costs. They provide a web interface where you can access their servers and use them when you need. </p>
<p>Currently, the most popular cloud service providers are Google (Google Cloud Platform), Amazon AWS (Amazon Web Services), and Microsoft (Azure). These companies offer similar services, but with various different price models, features, and so on. </p>
<p>Here's a summary of what each of them offers:</p>
<h3 id="heading-google">Google</h3>
<p>They offer IaaS (Compute Engine), Containers As A Service, CaaS, (Kubernetes Engine), and PaaS (App Engine) services. They also offer data storage services, with tools like Google Cloud Storage, Cloud SQL, and Cloud Bigtable. </p>
<h3 id="heading-aws">AWS</h3>
<p>This is the first cloud services provider. They offer IaaS (Elastic Compute, EC2), CaaS (Elastic Kubernetes Service, EKS)  and PaaS (Elastic Beanstalk) services. They also offer data storage services, with tools like Amazon S3, and DynamoDb.</p>
<h3 id="heading-microsoft">Microsoft</h3>
<p>They offer IaaS (Virtual Machine), CaaS (Kubernetes Service, AKS), and PaaS (App Service) services. They also offer data storage services, with tools like Cosmos DB.</p>
<p>To maximise resources, cloud service providers have their clients sharing servers. The clients don't have to know or worry about this allocation.</p>
<p>Now let's understand what some of the above acronyms/terms mean so you have a better idea of what these cloud services are.</p>
<h2 id="heading-different-cloud-services">Different Cloud Services</h2>
<p>Cloud service providers offer plenty of different computing services. Here are the most common services:</p>
<h3 id="heading-saas-software-as-a-service">SaaS (Software As A Service)</h3>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/05/saas-778x445.jpeg" alt="Image" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fgeeksuper.com%2Fadvantages-of-saas-platforms-for-online-courses%2F&amp;psig=AOvVaw0J54lC0WsxXAoS0L2czE27&amp;ust=1652833369985000&amp;source=images&amp;cd=vfe&amp;ved=0CA0QjhxqFwoTCIDvwOio5fcCFQAAAAAdAAAAABAO">Geek Super</a></em></p>
<p>This service involves you just using some software without any knowledge of its source code or host environment or development details. You just use it and trust that it's being managed and updated properly.</p>
<h3 id="heading-paas-platform-as-a-service">PaaS (Platform As A Service)</h3>
<p>Here, you focus only on your application development as everything has been handled (the hardware, computing environments, and required software).</p>
<h3 id="heading-iaas-infrastructure-as-a-service">IaaS (Infrastructure As A Service)</h3>
<p>This is the most flexible of all cloud services. Here you have the most control over things. You can customise and change things as you see fit. </p>
<p>But you don't own the servers. The cloud service provider only provides you with the infrastructure you need, and you are responsible for creating your own computing environments and installing required software for your application to work.</p>
<p>The idea here is similar to buying hardware. The only difference is that now, you're renting it and it's virtual (to you).</p>
<h2 id="heading-challenges-that-cloud-computing-helps-solve">Challenges that Cloud Computing Helps Solve</h2>
<p>Cloud computing removes the need to purchase and setup servers on-site every time a new application needed to be developed. This is a great advantage as it saves companies a lot of money – both on servers, as well as on the engineers who would setup and configure the servers to work for your applications.</p>
<p>Scaling isn't usually easy as it often involves a lot of setup and configuration. For example, to provide more storage for an application, you could get an external data store and connect to the current server. This definitely has its limits, though. </p>
<p>A point will likely come when you need a better server, or an additional server. Either way, every software that you installed to get it running on the former server would have to be installed again on the new server. Application files would have to be moved, and so on.</p>
<p>Also, these applications are often underutilising these hardware resources. This, from the business perspective, is a loss. An initial fix to this was virtualisation. This basically meant creating virtual (contained) environments where the application has all of its required software and can function well on the servers. These led to better utilisation of resources. But it definitely wasn't the perfect solution. </p>
<h2 id="heading-how-can-cloud-computing-help-you">How Can Cloud Computing Help You?</h2>
<p>Cloud computing offers plenty benefits, some of which are highlighted here:</p>
<ul>
<li>It is cheaper to pay a subscription than to build a whole datacenter. You have plans that let you use only what you use.</li>
<li>Scaling and management are responsibilities of the cloud service provider.</li>
<li>Easy setup. Developers get to just focus on the code as all the actual server and hardware setup can be done using a user interface provided by the cloud service provider. This leads to faster development time, and applications are shipped faster.</li>
<li>Accessibility. Cloud service providers tend to have multiple datacenters around the world, making sure your users always get access to your services as fast as possible.</li>
<li>Data security. Because your data is not stored in your physical space anymore, it's more difficult for bad actors to come in and damage or steal your servers.</li>
</ul>
<h2 id="heading-cloud-deployment-models">Cloud Deployment Models</h2>
<p>A cloud deployment model determines where your data (and applications) is stored and how your customers interact with it.</p>
<h3 id="heading-public-cloud">Public cloud</h3>
<p>Here, everything is handled by the cloud service provider. It's the most popular model. When using a public cloud, you're not concerned about the server maintenance, and you're sure of high reliability and the possibility of unlimited scalability. This usually means you share servers with other people. </p>
<p>It is the cheapest model, and companies usually use a pay-as-you-go model (so you never have to commit too much upfront financially). </p>
<p>A potential issue with this is, having everything handled by the cloud service provider means you have little or no control over the services.</p>
<h3 id="heading-private-cloud">Private cloud</h3>
<p>This is similar to the traditional ways of hosting applications. Here, you do have your own data centers. This means that only you get to use the servers and have unlimited control over them. </p>
<p>Now, the difference is, you provide a self service interface to users of your servers, usually developers in your company. You still have to manage the physical servers, and you're responsible for their maintenance and scaling.</p>
<p>This method can be more secure than the public cloud, as you have control and can setup as much security as possible. It also comes in very handy if you have data that must not get out due to compliance requirements.</p>
<p>But this method is way more cost intensive, although with a more predictable or fixed pricing model. These servers and hardware are expensive. Having them means having someone to manage them, which means more expense. Scaling also means buying new devices every time. </p>
<h3 id="heading-hybrid-cloud">Hybrid cloud</h3>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/05/What-is-Hybrid-Cloud.jpeg" alt="Image" width="600" height="400" loading="lazy">
<em>Hybrid Cloud | <a target="_blank" href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fw3codemasters.in%2Fwhat-is-hybrid-cloud-benefits-of-a-unified-hybrid-cloud-platform%2F&amp;psig=AOvVaw3ekfLv5gwNG2kjXGoFfWA4&amp;ust=1652833178148000&amp;source=images&amp;cd=vfe&amp;ved=0CA0QjhxqFwoTCPj5qKKp5fcCFQAAAAAdAAAAABAI">W3Codemasters</a></em></p>
<p>This approach merges both the public and cloud methods. It basically allows you more flexibility. You get to use public services, and also setup your own when you need to. Here you're able to comply with regulations, through your servers, and also offer high accessibility, through a cloud service provider. This method is perfect for organizations trying to migrate from one model to another, keeping the business operation during the transition.</p>
<p>An example application of this would be hosting an application on a public cloud and connecting it to a database on a secured private cloud.</p>
<p>This method is also more expensive than the public cloud as you do have to cater for some of the servers. It could also get complicated as data gets distributed between multiple servers and applications.</p>
<h3 id="heading-how-to-choosed-a-deployment-model">How to Choosed a Deployment Model</h3>
<p>The choice between public, private, or hybrid cloud deployment models depends on an organization's unique requirements. </p>
<ul>
<li>Public clouds offer cost efficiency and global reach</li>
<li>Private clouds provide enhanced security and control</li>
<li>Hybrid clouds offer flexibility and a strategic balance between the two.</li>
</ul>
<p>The decision ultimately hinges on factors such as security needs, compliance requirements, scalability, and the level of control desired over the IT infrastructure.</p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>Now you should have have enough information to kickstart your career in cloud computing.</p>
<p>If you have any questions or relevant advice, please get in touch with me to share them.</p>
<p>To read more of my articles or follow my work, you can connect with me on <a target="_blank" href="https://www.linkedin.com/in/idris-aweda-zubair-5433121a3/">LinkedIn</a>, <a target="_blank" href="https://twitter.com/AwedaIdris">Twitter</a>, and <a target="_blank" href="https://github.com/Zubs">Github</a>. It’s quick, it’s easy, and it’s free!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Queues in Web Applications – Node.js and Redis Tutorial ]]>
                </title>
                <description>
                    <![CDATA[ When you're building large scale web applications, speed is a major priority. Users don't want to wait long for responses anymore, and they shouldn't have to. But some processes take time, and they cannot be made any faster or eliminated. Message que... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-queues-in-web-applications/</link>
                <guid isPermaLink="false">66c4c699744830ebca763790</guid>
                
                    <category>
                        <![CDATA[ Node.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ queue ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Redis ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Zubair Idris Aweda ]]>
                </dc:creator>
                <pubDate>Thu, 06 Jul 2023 16:23:18 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/07/businessmen02.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>When you're building large scale web applications, speed is a major priority. Users don't want to wait long for responses anymore, and they shouldn't have to. But some processes take time, and they cannot be made any faster or eliminated.</p>
<p>Message queues help solve this problem by providing an additional branch to the usual request-response journey. This additional branch helps make sure users can get immediate responses, and the time-consuming processes can be done on the side. Everybody goes home happy.</p>
<p>This article will focus on explaining what message queues are and how to get started with them by building a very simple application. You should be familiar with the basics of Node.js, and you should have Redis installed either locally or on a cloud instance. Learn how to install Redis <a target="_blank" href="https://redis.io/docs/getting-started/installation/">here</a>.</p>
<h2 id="heading-what-is-a-queue">What is a Queue?</h2>
<p>A queue is a data structure that allows you store entities in an order. Queues use a first-in-first-out (FIFO) principle. </p>
<p>The concept of queues in computer science is the same as the concept of queues in everyday life where people line up to get things. You join a queue from the back, wait till it is your turn, then leave the queue from the front after you have been attended to.</p>
<p>In computer science, when a process like an API request is running, and you need to remove a certain task (like sending an email) from the current flow, you push it to a queue and continue the process.</p>
<p>The diagram below illustrates the lifecycle of a queue:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/job-lifecycle.png" alt="Image" width="600" height="400" loading="lazy">
<em>Queue Lifecycle | https://optimalbits.github.io/bull/</em></p>
<h2 id="heading-what-is-a-job">What is a Job?</h2>
<p>A job is any piece of data that is used on a queue, usually a JSON-like object.</p>
<p>As demonstrated in the cover image of this article, you can think of a job as each person on a queue at an airport. Each person holds a briefcase containing specific data, and other instructions (passports and maybe medical papers where required) that will help when it is their turn to be attended to.</p>
<p>New people joining this queue will enter from the back (as the last person), and people will be attended to from the front. That is how jobs are also processed, each job contains data that will be used for its processing. New jobs are added from the back while jobs are taken out from the front.</p>
<h3 id="heading-what-is-a-job-producer">What is a Job Producer?</h3>
<p>A job producer is any piece of code that adds a job to a queue. In real life, this would be the security guard at the airport that gives direction to people, telling them which queue to join for different purposes. </p>
<p>A job producer can exist independently of a job consumer. This means that in a microservice setup, a particular service might just be concerned with adding jobs to a queue, but not how they're processed after.</p>
<h3 id="heading-what-is-a-worker-job-consumer">What is a Worker (Job Consumer)?</h3>
<p>A worker, or job consumer, is a process, or function, that can execute a job. Think of a worker as a bank cashier attending to people on a queue at the bank. When the first person comes in, they join the queue as the only one on the queue. The cashier then calls for them and the queue is emptied. </p>
<p>The cashier requests for specific details to be used to process the transaction from the person. While the cashier attends to that customer, four more customers could have lined up. They will remain on the queue till the cashier is done with the first customer before calling for the next one. This is the same process with queue workers — they pick the first job in the queue, and process it.</p>
<h3 id="heading-what-are-failed-jobs">What are Failed Jobs?</h3>
<p>Often times, some jobs might fail during processing.</p>
<p>Here are some reasons why a job could fail:</p>
<ul>
<li>Invalid or missing input data: When data required for a job to be processed is missing, the job will fail. For example, a job to send an email will fail without the recipient's email address.</li>
<li>Timeout: A job could be failed by the queue mechanism if it is taking longer than usual. This could be due to an issue on a dependency of the job or something else, but usually you don't want a single job running forever.</li>
<li>Network or infrastructure problems: These problems are almost out of your control, but they do happen. A database connection error for example would fail a job.</li>
<li>Dependency issues: Sometimes a job relies on some external resources to function well. Whenever these other resources are unavailable or unsuccessful, the job will fail.</li>
</ul>
<p>When jobs fail, you can configure your queue mechanism to retry them. You can either retry the job immediately, or after a calculated amount of time. You can set a maximum number of attempts, which is recommended. If not, you end up running a job that will always fail infinitely.</p>
<h2 id="heading-why-use-queues">Why Use Queues?</h2>
<p>Queues are useful for creating robust communication channels between microservices. Multiple services can use the same queue. Different services could be tasked with different problems. When a service completes its task, it can push a job to another service that has workers waiting for that job. That service will pick it up and do whatever is needed with the data.</p>
<p>Queues are also useful for offloading heavy tasks from a process. As you'll see in this article, a time consuming task like sending of an email can be put on a queue to avoid slowing down response time.</p>
<p>Queues help avoid single points of failure. A process that has the ability to fail and can be retried is best processed using a queue where it can be retried after a while.</p>
<h2 id="heading-how-to-build-a-simple-application-that-uses-queues">How to Build a Simple Application that Uses Queues</h2>
<p>In this article, we'll build a simple project using Node.js and <a target="_blank" href="https://redis.io/">Redis</a>. We'll use the <a target="_blank" href="https://optimalbits.github.io/bull/">Bull</a> library as it simplifies a lot of the complexities involved in building a queue system. The project will have a single endpoint to send emails.</p>
<h3 id="heading-create-a-new-nodejs-project">Create a New Node.js Project</h3>
<pre><code class="lang-shell">mkdir nodejs-queue-project
cd nodejs-queue-project
npm init -y
</code></pre>
<p>The commands above will create a new folder named <code>nodejs-queue-project</code> and a <code>package.json</code> file in it. The <code>package.json</code> file should look like this:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"name"</span>: <span class="hljs-string">"nodejs-queue-project"</span>,
  <span class="hljs-attr">"version"</span>: <span class="hljs-string">"1.0.0"</span>,
  <span class="hljs-attr">"description"</span>: <span class="hljs-string">""</span>,
  <span class="hljs-attr">"main"</span>: <span class="hljs-string">"index.js"</span>,
  <span class="hljs-attr">"scripts"</span>: {
    <span class="hljs-attr">"test"</span>: <span class="hljs-string">"echo \"Error: no test specified\" &amp;&amp; exit 1"</span>
  },
  <span class="hljs-attr">"keywords"</span>: [],
  <span class="hljs-attr">"author"</span>: <span class="hljs-string">""</span>,
  <span class="hljs-attr">"license"</span>: <span class="hljs-string">"ISC"</span>
}
</code></pre>
<h3 id="heading-install-the-required-dependencies">Install the Required Dependencies</h3>
<pre><code class="lang-shell">npm i express @types/express @types/node body-parser ts-node ts-lint typescript nodemon nodemailer @types/nodemailer
</code></pre>
<p>The commands above will install the different packages and dependencies required for the project. </p>
<p>After installation, you can update the <code>scripts</code> section of your <code>package.json</code> to have a <code>dev</code> command. Your whole <code>package.json</code> file should look like this now:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"name"</span>: <span class="hljs-string">"nodejs-queue-project"</span>,
  <span class="hljs-attr">"version"</span>: <span class="hljs-string">"1.0.0"</span>,
  <span class="hljs-attr">"description"</span>: <span class="hljs-string">""</span>,
  <span class="hljs-attr">"main"</span>: <span class="hljs-string">"index.js"</span>,
  <span class="hljs-attr">"scripts"</span>: {
    <span class="hljs-attr">"dev"</span>: <span class="hljs-string">"nodemon src/app.ts"</span>
  },
  <span class="hljs-attr">"keywords"</span>: [],
  <span class="hljs-attr">"author"</span>: <span class="hljs-string">""</span>,
  <span class="hljs-attr">"license"</span>: <span class="hljs-string">"ISC"</span>,
  <span class="hljs-attr">"dependencies"</span>: {
    <span class="hljs-attr">"@types/express"</span>: <span class="hljs-string">"^4.17.17"</span>,
    <span class="hljs-attr">"@types/node"</span>: <span class="hljs-string">"^20.3.3"</span>,
    <span class="hljs-attr">"@types/nodemailer"</span>: <span class="hljs-string">"^6.4.8"</span>,
    <span class="hljs-attr">"body-parser"</span>: <span class="hljs-string">"^1.20.2"</span>,
    <span class="hljs-attr">"express"</span>: <span class="hljs-string">"^4.18.2"</span>,
    <span class="hljs-attr">"nodemailer"</span>: <span class="hljs-string">"^6.9.3"</span>,
    <span class="hljs-attr">"nodemon"</span>: <span class="hljs-string">"^2.0.22"</span>,
    <span class="hljs-attr">"ts-lint"</span>: <span class="hljs-string">"^4.5.1"</span>,
    <span class="hljs-attr">"ts-node"</span>: <span class="hljs-string">"^10.9.1"</span>,
    <span class="hljs-attr">"typescript"</span>: <span class="hljs-string">"^5.1.6"</span>
  }
}
</code></pre>
<p>The file above shows all your installed dependencies. The <code>npm run dev</code> command will run when you use the <code>dev</code> script.</p>
<h2 id="heading-how-to-build-the-endpoint">How to Build the Endpoint</h2>
<p>The first thing to do is to create a new folder named <code>src</code>. This folder will contain all your code files. The first file it will contain is the root file of the application — the <code>app.ts</code> file as defined in the <code>package.json</code> file.</p>
<p>We'll use the <code>app.ts</code> file to import required packages and create a simple server with a single endpoint to send a email as seen below:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> express <span class="hljs-keyword">from</span> <span class="hljs-string">"express"</span>;
<span class="hljs-keyword">import</span> bodyParser <span class="hljs-keyword">from</span> <span class="hljs-string">"body-parser"</span>;
<span class="hljs-keyword">import</span> nodemailer <span class="hljs-keyword">from</span> <span class="hljs-string">"nodemailer"</span>;

<span class="hljs-keyword">const</span> app = express();

app.use(bodyParser.json());

app.post(<span class="hljs-string">"/send-email"</span>, <span class="hljs-keyword">async</span> (req, res) =&gt; {
  <span class="hljs-keyword">const</span> { <span class="hljs-keyword">from</span>, to, subject, text } = req.body;

  <span class="hljs-comment">// Use a test account as this is a tutorial</span>
  <span class="hljs-keyword">const</span> testAccount = <span class="hljs-keyword">await</span> nodemailer.createTestAccount();

  <span class="hljs-keyword">const</span> transporter = nodemailer.createTransport({
    host: <span class="hljs-string">"smtp.ethereal.email"</span>,
    port: <span class="hljs-number">587</span>,
    secure: <span class="hljs-literal">false</span>,
    auth: {
      user: testAccount.user,
      pass: testAccount.pass,
    },
    tls: {
      rejectUnauthorized: <span class="hljs-literal">false</span>,
    },
  });

  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Sending mail to %s"</span>, to);

  <span class="hljs-keyword">let</span> info = <span class="hljs-keyword">await</span> transporter.sendMail({
    <span class="hljs-keyword">from</span>,
    to,
    subject,
    text,
    html: <span class="hljs-string">`&lt;strong&gt;<span class="hljs-subst">${text}</span>&lt;/strong&gt;`</span>,
  });

  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Message sent: %s"</span>, info.messageId);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Preview URL: %s"</span>, nodemailer.getTestMessageUrl(info));

  res.json({
    message: <span class="hljs-string">"Email Sent"</span>,
  });
});

app.listen(<span class="hljs-number">4300</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Server started at http://localhost:4300"</span>);
});
</code></pre>
<p>Now, you can start your server by running <code>npm run dev</code> in your terminal. You should see a message saying <code>Server started at [http://localhost:4300](http://localhost:4300)</code> in your terminal.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/Screenshot-2023-07-01-at-17.41.33.png" alt="Image" width="600" height="400" loading="lazy">
<em>npm run dev message</em></p>
<p>You can now test the endpoint using a tool like Postman:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/Screenshot-2023-07-01-at-17.30.33.png" alt="Image" width="600" height="400" loading="lazy">
<em>Endpoint testing on Postman</em></p>
<p>The request took almost 4 seconds as shown in the screenshot. This is very slow for an endpoint. If you take a look at your terminal, you should also see a URL where you can preview the email that was sent.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/Screenshot-2023-07-01-at-17.43.01.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Opening the link lets you see how the email looks.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/Screenshot-2023-07-01-at-17.43.47.png" alt="Image" width="600" height="400" loading="lazy">
<em>Email content</em></p>
<h2 id="heading-how-to-create-the-queue">How to Create the Queue</h2>
<p>To make the process even faster, the email can be queued to be sent later and a response sent to the user immediately.</p>
<p>To do this, install the <code>bull</code> library and its <code>@types</code> library as we'll use it to create a queue. That is:</p>
<pre><code class="lang-shell">npm i bull @types/bull
</code></pre>
<p>Creating a new queue using <code>bull</code> is as easy as instantiating a new <code>Bull</code> object with a name for the queue:</p>
<pre><code class="lang-ts"><span class="hljs-comment">// This goes at the top of your file</span>
<span class="hljs-keyword">import</span> Bull <span class="hljs-keyword">from</span> <span class="hljs-string">'bull'</span>;

<span class="hljs-keyword">const</span> emailQueue = <span class="hljs-keyword">new</span> Bull(<span class="hljs-string">"email"</span>);
</code></pre>
<p>When the queue is created with just the queue name, it tries to use the default Redis connection URL: <code>localhost:6379</code>. If you prefer using a different URL, simply pass in a second object to the <code>Bull</code> class as an options object:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">const</span> emailQueue = <span class="hljs-keyword">new</span> Bull(<span class="hljs-string">"email"</span>, {
  redis: <span class="hljs-string">"localhost:6379"</span>,
});
</code></pre>
<p>At this point, you can create a simple function to serve as a job producer and add a job to the queue every time a request comes in.</p>
<pre><code class="lang-ts"><span class="hljs-keyword">type</span> EmailType = {
  <span class="hljs-keyword">from</span>: <span class="hljs-built_in">string</span>;
  to: <span class="hljs-built_in">string</span>;
  subject: <span class="hljs-built_in">string</span>;
  text: <span class="hljs-built_in">string</span>;
};

<span class="hljs-keyword">const</span> sendNewEmail = <span class="hljs-keyword">async</span> (email: EmailType) =&gt; {
  emailQueue.add({ ...email });
};
</code></pre>
<p>This newly created function, <code>sendNewEmail</code>, accepts an object containing details of the new email to be sent of type <code>EmailType</code>. There's sender email address (<code>from</code>), recipient email address (<code>to</code>), <code>subject</code> of the email, and the content of the email (<code>text</code>). Then it pushes a new job to the queue. </p>
<p>You can use this function instead of sending the email during the request now. Modify the endpoint to do this:</p>
<pre><code class="lang-ts">app.post(<span class="hljs-string">"/send-email"</span>, <span class="hljs-keyword">async</span> (req, res) =&gt; {
  <span class="hljs-keyword">const</span> { <span class="hljs-keyword">from</span>, to, subject, text } = req.body;

  <span class="hljs-keyword">await</span> sendNewEmail({ <span class="hljs-keyword">from</span>, to, subject, text });

  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Added to queue"</span>);

  res.json({
    message: <span class="hljs-string">"Email Sent"</span>,
  });
});
</code></pre>
<p>At this point, the code is simpler and the process is faster. The request only takes about 40m — about 100x faster than before.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/Screenshot-2023-07-01-at-18.25.40.png" alt="Image" width="600" height="400" loading="lazy">
<em>Endpoint testing with Postman</em></p>
<p>At this point, the email is added to a queue. It will remain on the queue until processed. The job can be processed by the same application or another service (if in a <a target="_blank" href="https://www.freecodecamp.org/news/microservices-architecture-for-humans/">microservice setup</a>).</p>
<h2 id="heading-how-to-process-the-jobs">How to Process the Jobs</h2>
<p>The cycle is incomplete and useless if the mails never leave the queue. We'll create a job consumer to process the jobs and clear the queue.</p>
<p>We can do this by creating the logic for a function that accepts a <code>Job</code> object and sends the email:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">const</span> processEmailQueue = <span class="hljs-keyword">async</span> (job: Job) =&gt; {
  <span class="hljs-comment">// Use a test account as this is a tutorial</span>
  <span class="hljs-keyword">const</span> testAccount = <span class="hljs-keyword">await</span> nodemailer.createTestAccount();

  <span class="hljs-keyword">const</span> transporter = nodemailer.createTransport({
    host: <span class="hljs-string">"smtp.ethereal.email"</span>,
    port: <span class="hljs-number">587</span>,
    secure: <span class="hljs-literal">false</span>,
    auth: {
      user: testAccount.user,
      pass: testAccount.pass,
    },
    tls: {
      rejectUnauthorized: <span class="hljs-literal">false</span>,
    },
  });

  <span class="hljs-keyword">const</span> { <span class="hljs-keyword">from</span>, to, subject, text } = job.data;

  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Sending mail to %s"</span>, to);

  <span class="hljs-keyword">let</span> info = <span class="hljs-keyword">await</span> transporter.sendMail({
    <span class="hljs-keyword">from</span>,
    to,
    subject,
    text,
    html: <span class="hljs-string">`&lt;strong&gt;<span class="hljs-subst">${text}</span>&lt;/strong&gt;`</span>,
  });

  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Message sent: %s"</span>, info.messageId);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Preview URL: %s"</span>, nodemailer.getTestMessageUrl(info));

  <span class="hljs-keyword">return</span> nodemailer.getTestMessageUrl(info);
};
</code></pre>
<p>The function above accepts a <code>Job</code> object. The object has useful properties that shows the status of and data in a job. Here, we use the <code>data</code> property. </p>
<p>At this point, all we have is a function. It doesn't pick up jobs automatically because it doesn't know which queue to work with.</p>
<p>Before connecting it to the queue, you can go on to add a few jobs to the queue by sending some requests. You can check the email jobs currently queued by running this command in your <code>redis-cli</code>:</p>
<pre><code class="lang-shell">LRANGE bull:email:wait 0 -1
</code></pre>
<p>This checks the email waitlist, and returns the <code>ids</code> of the waiting jobs.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/Screenshot-2023-07-01-at-18.47.35.png" alt="Image" width="600" height="400" loading="lazy">
<em>Redis CLI</em></p>
<p>I have created a few jobs just to show how workers actually work.</p>
<p>Now, connect the worker to the queue by adding this line of code:</p>
<pre><code class="lang-ts">emailQueue.process(processEmailQueue);
</code></pre>
<p>This is what your <code>app.ts</code> file should now look after that:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> express <span class="hljs-keyword">from</span> <span class="hljs-string">"express"</span>;
<span class="hljs-keyword">import</span> bodyParser <span class="hljs-keyword">from</span> <span class="hljs-string">"body-parser"</span>;
<span class="hljs-keyword">import</span> nodemailer <span class="hljs-keyword">from</span> <span class="hljs-string">"nodemailer"</span>;
<span class="hljs-keyword">import</span> Bull, { Job } <span class="hljs-keyword">from</span> <span class="hljs-string">"bull"</span>;

<span class="hljs-keyword">const</span> app = express();

app.use(bodyParser.json());

<span class="hljs-keyword">const</span> emailQueue = <span class="hljs-keyword">new</span> Bull(<span class="hljs-string">"email"</span>, {
  redis: <span class="hljs-string">"localhost:6379"</span>,
});

<span class="hljs-keyword">type</span> EmailType = {
  <span class="hljs-keyword">from</span>: <span class="hljs-built_in">string</span>;
  to: <span class="hljs-built_in">string</span>;
  subject: <span class="hljs-built_in">string</span>;
  text: <span class="hljs-built_in">string</span>;
};

<span class="hljs-keyword">const</span> sendNewEmail = <span class="hljs-keyword">async</span> (email: EmailType) =&gt; {
  emailQueue.add({ ...email });
};

<span class="hljs-keyword">const</span> processEmailQueue = <span class="hljs-keyword">async</span> (job: Job) =&gt; {
  <span class="hljs-comment">// Use a test account as this is a tutorial</span>
  <span class="hljs-keyword">const</span> testAccount = <span class="hljs-keyword">await</span> nodemailer.createTestAccount();

  <span class="hljs-keyword">const</span> transporter = nodemailer.createTransport({
    host: <span class="hljs-string">"smtp.ethereal.email"</span>,
    port: <span class="hljs-number">587</span>,
    secure: <span class="hljs-literal">false</span>,
    auth: {
      user: testAccount.user,
      pass: testAccount.pass,
    },
    tls: {
      rejectUnauthorized: <span class="hljs-literal">false</span>,
    },
  });

  <span class="hljs-keyword">const</span> { <span class="hljs-keyword">from</span>, to, subject, text } = job.data;

  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Sending mail to %s"</span>, to);

  <span class="hljs-keyword">let</span> info = <span class="hljs-keyword">await</span> transporter.sendMail({
    <span class="hljs-keyword">from</span>,
    to,
    subject,
    text,
    html: <span class="hljs-string">`&lt;strong&gt;<span class="hljs-subst">${text}</span>&lt;/strong&gt;`</span>,
  });

  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Message sent: %s"</span>, info.messageId);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Preview URL: %s"</span>, nodemailer.getTestMessageUrl(info));
};

emailQueue.process(processEmailQueue);

app.post(<span class="hljs-string">"/send-email"</span>, <span class="hljs-keyword">async</span> (req, res) =&gt; {
  <span class="hljs-keyword">const</span> { <span class="hljs-keyword">from</span>, to, subject, text } = req.body;

  <span class="hljs-keyword">await</span> sendNewEmail({ <span class="hljs-keyword">from</span>, to, subject, text });

  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Added to queue"</span>);

  res.json({
    message: <span class="hljs-string">"Email Sent"</span>,
  });
});

app.listen(<span class="hljs-number">4300</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Server started at http://localhost:4300"</span>);
});
</code></pre>
<p>Once you save, you'll notice that the server restarts and immediately starts sending out mails. This is because the worker sees the queue and begins processing immediately.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/Screenshot-2023-07-01-at-18.51.14.png" alt="Image" width="600" height="400" loading="lazy">
<em>Server sending out queued emails</em></p>
<p>Now, both the producer and the worker are active. Every new API request will be pushed to the queue, and the worker will immediately process it unless there's some pending jobs already.</p>
<h2 id="heading-summary"><strong>Summary</strong></h2>
<p>I hope this article helped you understand what a message queue is, how to add jobs and create processes to run them, and how you can use them to build better web applications. You can find the code files used in this article on <a target="_blank" href="https://github.com/Zubs/php-redis">GitHub</a>.</p>
<p>If you have any questions or relevant advice, please get in touch with me to share them.</p>
<p>To read more of my articles or follow my work, you can connect with me on <a target="_blank" href="https://www.linkedin.com/in/idris-aweda-zubair-5433121a3/">LinkedIn</a>, <a target="_blank" href="https://twitter.com/AwedaIdris">Twitter</a>, and <a target="_blank" href="https://github.com/Zubs">Github</a>. It’s quick, it’s easy, and it’s free!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How Method Overloading Works in PHP ]]>
                </title>
                <description>
                    <![CDATA[ As software engineers, we sometimes have to perform certain tasks that can be achieved with a variable number of inputs.  To solve this problem, you can create multiple functions to solve for the different possible number of inputs. Or we can write a... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/method-overloading-in-php/</link>
                <guid isPermaLink="false">66c4c6a226a77d9936ef0a7c</guid>
                
                    <category>
                        <![CDATA[ PHP ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Zubair Idris Aweda ]]>
                </dc:creator>
                <pubDate>Mon, 15 May 2023 17:11:35 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/05/kisscc0-line-art-drawing-drum-cartoon-overload-5b74068a69e855.7493203415343305064338.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>As software engineers, we sometimes have to perform certain tasks that can be achieved with a variable number of inputs. </p>
<p>To solve this problem, you can create multiple functions to solve for the different possible number of inputs. Or we can write a large function to solve this problem. </p>
<p>A better way to do this is to create different variations of a simple function to solve for the different scenarios you have.</p>
<p>In this tutorial you will learn how PHP lets you easily solve this problem using method overloading and how you can use these variations.</p>
<h2 id="heading-what-is-polymorphism">What is Polymorphism?</h2>
<p>Polymorphism is a Greek word that literally means many forms. In programming terms, it is defined as the ability of objects of different classes to respond differently based on the same message. </p>
<p>Polymorphism is the concept that lets classes share the same interface and have different definitions for the same method. Polymorphism is one of the key concepts in Object Oriented Programming (OOP).</p>
<h2 id="heading-what-is-method-overloading">What is Method Overloading?</h2>
<p>Method overloading is a concept that allows you to have a method that can perform differently based on its number of parameters. It allows you have multiple definitions for a same method in the same class.  </p>
<p>This method will have the same name for all its uses, but might produce different output in different situations. Method overloading is a key concept under the umbrella of polymorphism.</p>
<h3 id="heading-traditional-overloading">Traditional Overloading</h3>
<p>For example, say you have an <code>add</code> method that you want to use to sum a couple of numbers in these ways:</p>
<pre><code class="lang-php"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> $a, <span class="hljs-keyword">int</span> $b</span>): <span class="hljs-title">int</span>
</span>{
    <span class="hljs-keyword">return</span> $a + $b;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> $a, <span class="hljs-keyword">int</span> $b, <span class="hljs-keyword">int</span> $c</span>): <span class="hljs-title">int</span>
</span>{
    $sum = $a + $b + $c;
    <span class="hljs-keyword">return</span> $sum &gt; <span class="hljs-number">10</span> ? <span class="hljs-number">10</span> : $sum;
}
</code></pre>
<p>In the first definition, the method takes in two parameters and simply returns their sum. In the second definition, it takes three parameters and it returns the sum of these only when it's equal to 10 or less.</p>
<p>Now, unlike other programming languages, PHP doesn't really let you redefine a method multiple times like this:</p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SampleClass</span>
</span>{
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> $a, <span class="hljs-keyword">int</span> $b</span>): <span class="hljs-title">int</span>
    </span>{
        <span class="hljs-keyword">return</span> $a + $b;
    }

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> $a, <span class="hljs-keyword">int</span> $b, <span class="hljs-keyword">int</span> $c</span>): <span class="hljs-title">int</span>
    </span>{
        <span class="hljs-keyword">return</span> $a + $b + $c &gt; <span class="hljs-number">10</span> ?? <span class="hljs-number">10</span>;
    }
}
</code></pre>
<p>You would get an error like this: <code>PHP Fatal error:  Cannot redeclare SampleClass::add()</code>. But PHP supports method overloading using a magic keyword, <code>__call</code>. </p>
<h3 id="heading-the-call-keyword">The <code>__call</code> keyword</h3>
<p>This is a magic method that PHP calls when it tries to execute a method of a class and it doesn't find it. This magic keyword takes in two arguments: a function name and other arguments to be passed into the function. Its definition looks like this:</p>
<pre><code class="lang-php"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__call</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> $function_name, <span class="hljs-keyword">array</span> $arguments</span>) </span>{}
</code></pre>
<p>Using this magic method, you can create as many methods and as many variations of each of these methods as you like. </p>
<p>For example, to achieve our intended goal with the <code>add</code> function, update the <code>__call</code> definition and your <code>SampleClass</code> to be like this:</p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SampleClass</span>
</span>{
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__call</span>(<span class="hljs-params">$function_name, $arguments</span>)
    </span>{
        $count = count($arguments);

        <span class="hljs-comment">// Check function name</span>
        <span class="hljs-keyword">if</span> ($function_name == <span class="hljs-string">'add'</span>) {
            <span class="hljs-keyword">if</span> ($count == <span class="hljs-number">2</span>) {
                <span class="hljs-keyword">return</span> array_sum($arguments);
            } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> ($count == <span class="hljs-number">3</span>) {
                <span class="hljs-keyword">return</span> array_sum($arguments) &gt; <span class="hljs-number">10</span> ? <span class="hljs-number">10</span> : array_sum($arguments);
            }
        }
    }
}
</code></pre>
<p>The code is pretty self explanatory. Here's a step by step breakdown:</p>
<ul>
<li>Use the <code>count</code> method to know how many arguments are passed to your method. </li>
<li>Check the function name being passed in. This <code>__call</code> will house all the different methods you intend to create variations of, so the name should be unique and be used to group variations of the methods.</li>
<li>Handle the logic as you like based on the different number of arguments. Here, we return the sum as is when we have two arguments. We return the sum if it's less than 10 when we have three arguments.</li>
<li>When you call the <code>add</code> method, PHP checks for a method with the same name in the class, if it doesn't find it, it calls the <code>__call</code> method instead, and that is how the code is run.</li>
</ul>
<p>To call the <code>add</code> method now, create a new instance of the <code>SampleClass</code> class and try it out.</p>
<pre><code class="lang-php">$sampleObject = <span class="hljs-keyword">new</span> SampleClass;
<span class="hljs-keyword">echo</span> $sampleObject-&gt;add(<span class="hljs-number">12</span>, <span class="hljs-number">12</span>) . PHP_EOL; <span class="hljs-comment">// Outputs 24 </span>
<span class="hljs-keyword">echo</span> $sampleObject-&gt;add(<span class="hljs-number">12</span>, <span class="hljs-number">2</span>, <span class="hljs-number">6</span>) . PHP_EOL; <span class="hljs-comment">// Outputs 10</span>
</code></pre>
<p>The two variations work perfectly 🥳.</p>
<h2 id="heading-applications-of-method-overloading">Applications Of Method Overloading</h2>
<ul>
<li>In sort functions: The method can be programmed to behave differently with no arguments, or with one argument, or with two depending on what you're trying to solve.</li>
<li>Payment processing: The same method can be used to handle different payment processors. And these processors often need a different number of inputs to work well. So the method can figure which to use based on the number of arguments passed in and react accordingly.</li>
<li>Database wrappers: A database class could have a "query" method that can handle different types of queries with the same method name. For example, the "query" method could take in a SELECT query, an INSERT query, or an UPDATE query as parameters and execute the appropriate query based on the parameter passed in.</li>
</ul>
<h2 id="heading-summary"><strong>Summary</strong></h2>
<p>I hope you now understand what method overloading is in PHP, and how you can use it to write better PHP applications.</p>
<p>If you have any questions or relevant advice, please get in touch with me to share them.</p>
<p>To read more of my articles or follow my work, you can connect with me on <a target="_blank" href="https://www.linkedin.com/in/idris-aweda-zubair-5433121a3/">LinkedIn</a>, <a target="_blank" href="https://twitter.com/AwedaIdris">Twitter</a>, and <a target="_blank" href="https://github.com/Zubs">Github</a>. It’s quick, it’s easy, and it’s free!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Redis in Your PHP Apps ]]>
                </title>
                <description>
                    <![CDATA[ Redis is a data store that stores data primarily in memory. It's faster than traditional databases, and has grown quite popular. In this tutorial, you'll learn the basics of how Redis works, when to use it, how to install it on your device, and how t... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-redis-with-php/</link>
                <guid isPermaLink="false">66c4c69de7521bfd6862b3ad</guid>
                
                    <category>
                        <![CDATA[ database ]]>
                    </category>
                
                    <category>
                        <![CDATA[ PHP ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Redis ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Zubair Idris Aweda ]]>
                </dc:creator>
                <pubDate>Wed, 03 May 2023 19:51:55 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/05/pexels-tom-fisk-3063470.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Redis is a data store that stores data primarily in memory. It's faster than traditional databases, and has grown quite popular.</p>
<p>In this tutorial, you'll learn the basics of how Redis works, when to use it, how to install it on your device, and how to use it as a caching system in a PHP web application.</p>
<h2 id="heading-what-is-redis">What Is Redis?</h2>
<p>Redis is a data store – like a database, but one that stores data primarily in-memory. This makes it much faster than traditional databases where data is stored in disks. Because of this speed, Redis is often used as a caching tool.</p>
<p>Redis can store data in any data type, as it uses a key-value pair system to store data. This is also unlike traditional databases that use documents or rows. </p>
<p>You can think of a Redis database as a big JSON object, where everything in the database is a key-value pair. This means it might not be the best place to store structured data.</p>
<p>You can also use Redis as a database, as it has the ability to write data to disk for persistence. You can configure Redis to persist data either periodically or after every command you issue. When Redis isn't configured to persist data, it is very volatile, and a system crash would result in a loss of data.</p>
<p>Redis is popular in production level applications and it's used by large companies like Twitter, Github, SnapChat and StackOverFlow.</p>
<h2 id="heading-when-to-use-redis">When to Use Redis</h2>
<ul>
<li>For One Time Passwords (OTPs): These are usually generated to be used once, and have short lifespans. With Redis' ability to set an expiry date for data, you can safely store the OTP without worrying about deleting them after a certain period.</li>
<li>For frequently accessed resources: For data that doesn't change too frequently but is accessed a lot, you can use Redis to save time that would have been spent querying the database or making a call to some external service.</li>
<li>For heavy duty queries: For database queries that take time, and also won't change too often, use Redis to reduce this time by storing the results for as long as you like.</li>
</ul>
<h2 id="heading-how-to-install-redis">How to Install Redis</h2>
<p>You can install Redis on any operating system. Here are the instructions for macOS, Windows Subsystem for Linux, and Linux.</p>
<h3 id="heading-macos">macOS</h3>
<p>To install Redis on macOS, run:</p>
<pre><code class="lang-shell">brew install redis
</code></pre>
<p>Then, run this command to start Redis:</p>
<pre><code class="lang-shell">redis-server
</code></pre>
<h3 id="heading-windows-subsystem-for-linux-and-linux">Windows Subsystem for Linux and Linux</h3>
<p>Redis doesn't exactly support the Windows operating system yet, so you can install WSL (Windows Subsystem for Linux) on windows to have a Linux environment.</p>
<p>To install Redis on Linux, run:</p>
<pre><code class="lang-shell">curl -fsSL https://packages.redis.io/gpg | sudo gpg --dearmor -o /usr/share/keyrings/redis-archive-keyring.gpg

echo "deb [signed-by=/usr/share/keyrings/redis-archive-keyring.gpg] https://packages.redis.io/deb $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/redis.list

sudo apt-get update
sudo apt-get install redis
</code></pre>
<p>Then, run this command to start Redis:</p>
<pre><code class="lang-shell">sudo service redis-server start
</code></pre>
<p>Now that Redis is installed, you can test it by running <code>redis-cli ping</code>. This will output <em>"PONG"</em>. Like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/Screenshot-2023-04-30-at-13.36.14.png" alt="Image" width="600" height="400" loading="lazy">
<em>Testing Redis Installation</em></p>
<h2 id="heading-redis-basics">Redis Basics</h2>
<p>To use Redis as a REPL or as a standalone application, run <code>redis-cli</code>. It will open the REPL environment.</p>
<h3 id="heading-how-to-set-data">How to Set Data</h3>
<p>Use the <code>SET</code> keyword to set a key value pair in Redis. To set a <code>username</code> key to the value <code>Zubs</code> , run this: </p>
<pre><code class="lang-redis">SET username Zubs
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/Screenshot-2023-04-30-at-13.41.36.png" alt="Image" width="600" height="400" loading="lazy">
<em>Setting a key-value pair</em></p>
<h3 id="heading-how-to-get-data">How to Get Data</h3>
<p>To get the recently saved <code>username</code> key, use the <code>GET</code> keyword like this: </p>
<pre><code class="lang-redis">GET username
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/Screenshot-2023-04-30-at-13.43.52.png" alt="Image" width="600" height="400" loading="lazy">
<em>Getting a value by key</em></p>
<h3 id="heading-how-to-delete-data">How to Delete Data</h3>
<p>You can also delete a previously stored key using the <code>DEL</code> keyword like this:</p>
<pre><code class="lang-redis">DEL username
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/Screenshot-2023-04-30-at-17.57.26.png" alt="Image" width="600" height="400" loading="lazy">
<em>Deleting a value by key</em></p>
<h3 id="heading-how-to-check-if-a-value-exists">How to Check if a Value Exists</h3>
<p>You can check for the existence of a key by using the <code>EXISTS</code> keyword. It returns <code>0</code> when the key doesn't exist, and <code>1</code> if it does. You can test by checking if the recently deleted <code>username</code> key exists. Like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/Screenshot-2023-04-30-at-18.04.17.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-how-to-set-a-time-to-live-for-keys">How to Set a Time to Live for Keys</h3>
<p> Redis lets you specify how long some key should exist for when creating it. This is one really great feature of Redis. To do this, use the <code>SETEX</code> keyword like this:</p>
<pre><code class="lang-redis">SETEX key seconds value
</code></pre>
<p>You can check the time to live for a specific key using the <code>TTL</code> keyword. This returns <code>-1</code> if the key has no set expiration, meaning it will be stored indefinitely. It returns <code>-2</code> if the key doesn't exist. And it returns the time in seconds if the key exists.</p>
<p>You can set an expiration time in seconds for a key previously created without an expiration time using the <code>EXPIRE</code> keyword. For example, create a key to store a variable <code>age</code> with a value of <code>26</code>. </p>
<pre><code class="lang-redis">SET age 26
</code></pre>
<p>Then, set an expiration time of 10 seconds for it.</p>
<pre><code class="lang-redis">EXPIRE age 20
</code></pre>
<p>Check the time left to live repeatedly a couple of times to see how it actually reduces and eventually doesn't exist again.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/Screenshot-2023-04-30-at-18.22.58.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-build-a-simple-application-with-redis">How to Build a Simple Application with Redis</h2>
<p>To help you understand how Redis works, we'll now build a basic web application that uses Redis to cache data to load responses faster. You'll be building a simple application that fetches images data from <a target="_blank" href="https://www.freecodecamp.org/news/p/043f81af-1384-435c-b08a-4f80327a6002/'https://jsonplaceholder.typicode.com/photos'">JSONPlaceholder</a> and returns them.</p>
<h3 id="heading-create-a-new-php-project-using-composer">Create a New PHP Project Using Composer</h3>
<p>Create a new folder for the project, change directory into the newly created folder, and run the following compound to create a new composer project:</p>
<pre><code class="lang-shell">composer init -q
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/Screenshot-2023-04-30-at-19.06.40.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This will create a new <code>composer.json</code> file that should look like this:</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"require"</span>: {}
}
</code></pre>
<p>Next, create a public folder to house your public facing code files. Then create a new <code>index.php</code> file in the folder.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/Screenshot-2023-04-30-at-19.26.54.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Put in some boilerplate content in the PHP file for now and start a server.</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">echo</span> <span class="hljs-string">"Hello World!"</span>;
</code></pre>
<pre><code class="lang-shell">php -S localhost:8080
</code></pre>
<h3 id="heading-install-a-simple-router-and-handle-requests">Install a Simple Router and Handle Requests</h3>
<p>To complete the project, install a simple PHP router, <code>Altorouter</code>, and a web client, <code>Guzzlehttp</code>.</p>
<pre><code class="lang-shell">composer require altorouter/altorouter guzzlehttp/guzzle
</code></pre>
<p>Update the <code>index.php</code> to contain this code:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-comment">// Import composer autoload file</span>
<span class="hljs-keyword">require_once</span> <span class="hljs-keyword">__DIR__</span> . <span class="hljs-string">'/../vendor/autoload.php'</span>;

<span class="hljs-comment">// Import GuzzleHttp Client</span>
<span class="hljs-keyword">use</span> <span class="hljs-title">GuzzleHttp</span>\<span class="hljs-title">Client</span>;

<span class="hljs-comment">// Instantiate router and web client</span>
$router = <span class="hljs-keyword">new</span> AltoRouter();
$client = <span class="hljs-keyword">new</span> Client();

<span class="hljs-comment">// Register Sample route</span>
$router-&gt;map(<span class="hljs-string">'GET'</span>, <span class="hljs-string">'/'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">// Set response Content-Type</span>
    header(<span class="hljs-string">'Content-Type: application/json; charset=utf-8'</span>);

    <span class="hljs-comment">// Return basic response</span>
    <span class="hljs-keyword">echo</span> json_encode([<span class="hljs-string">'data'</span> =&gt; <span class="hljs-string">'Hello World'</span>]);
});

<span class="hljs-comment">/**
 * Route to get all photos
 */</span>
$router-&gt;map(<span class="hljs-string">'GET'</span>, <span class="hljs-string">'/photos'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) <span class="hljs-title">use</span> (<span class="hljs-params">$client</span>) </span>{
    <span class="hljs-comment">// Make request to JSONPlaceholder</span>
    $response = $client-&gt;request(<span class="hljs-string">'GET'</span>, <span class="hljs-string">'https://jsonplaceholder.typicode.com/photos'</span>);

    header(<span class="hljs-string">'Content-Type: application/json; charset=utf-8'</span>);
    <span class="hljs-keyword">echo</span> json_encode([
        <span class="hljs-string">'data'</span> =&gt; json_decode($response-&gt;getBody()-&gt;getContents())
    ]);
});

<span class="hljs-comment">/**
 * Route to get single photo by id
 */</span>
$router-&gt;map(<span class="hljs-string">'GET'</span>, <span class="hljs-string">'/photos/[i:id]'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"><span class="hljs-keyword">int</span> $id</span>) <span class="hljs-title">use</span> (<span class="hljs-params">$client</span>) </span>{
    $response = $client-&gt;request(<span class="hljs-string">'GET'</span>, <span class="hljs-string">'https://jsonplaceholder.typicode.com/photos/'</span> . $id);

    header(<span class="hljs-string">'Content-Type: application/json; charset=utf-8'</span>);
    <span class="hljs-keyword">echo</span> json_encode([
        <span class="hljs-string">'data'</span> =&gt; json_decode($response-&gt;getBody()-&gt;getContents())
    ]);
});

$match = $router-&gt;match();

<span class="hljs-keyword">if</span>( is_array($match) &amp;&amp; is_callable( $match[<span class="hljs-string">'target'</span>] ) ) {
    call_user_func_array( $match[<span class="hljs-string">'target'</span>], $match[<span class="hljs-string">'params'</span>] );
} <span class="hljs-keyword">else</span> {
    <span class="hljs-comment">// no route was matched</span>
    header( $_SERVER[<span class="hljs-string">"SERVER_PROTOCOL"</span>] . <span class="hljs-string">' 404 Not Found'</span>);
}
</code></pre>
<p>The code is pretty self explanatory. But, here's a breakdown for clarity. From lines 1-11, the required classes GuzzleHttp and AltoRouter are imported and instantiated.</p>
<p>From lines 14-20, the first route is registered, with a simple closure that returns "Hello World!". Lines 25-45 register two more routes, one to fetch all photos, <code>/photos</code> and another to fetch a single photo, <code>/photos/id</code>. </p>
<p>The final lines are required based on documentation of the router package to actually execute the closures set in the routes declaration.</p>
<p>You can test these routes using Postman.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/Screenshot-2023-04-30-at-20.19.36.png" alt="Image" width="600" height="400" loading="lazy">
<em>Hello World route</em></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/Screenshot-2023-04-30-at-20.21.01.png" alt="Image" width="600" height="400" loading="lazy">
<em>Get All Photos route</em></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/Screenshot-2023-04-30-at-20.26.19.png" alt="Image" width="600" height="400" loading="lazy">
<em>Get a Single Photo route</em></p>
<p>The <code>/photos</code> route takes an average of 1400ms per request. The <code>/photos/id</code> takes an average of 900ms per request. </p>
<h3 id="heading-install-and-instantiate-redis">Install and Instantiate Redis</h3>
<p>These times can be reduced by caching the results of the original request to JSONPlaceholder, then returning a response from the cache instead of making a request every time.</p>
<p>To use Redis with PHP, install the <a target="_blank" href="https://github.com/phpredis/phpredis">PhpRedis</a> extension. This extension provides an API for communicating with Redis. You can easily install it using the command:</p>
<pre><code class="lang-shell">pecl install redis
</code></pre>
<p>After installation, you can then use this class in your PHP project. Import the class and instantiate it at the top of your <code>index.php</code> file:</p>
<pre><code class="lang-php">$redis = <span class="hljs-keyword">new</span> Redis();
$redis-&gt;connect(<span class="hljs-string">'127.0.0.1'</span>);
</code></pre>
<p>Having done this, you can now use Redis in your project.</p>
<h3 id="heading-how-to-cache-data-with-redis">How to Cache Data with Redis</h3>
<p>Store the raw JSON response returned from JSONPlaceholder to Redis with an expiry time of 1 hour (3600 seconds).</p>
<pre><code class="lang-php">$response = $client-&gt;request(<span class="hljs-string">'GET'</span>, <span class="hljs-string">'https://jsonplaceholder.typicode.com/photos'</span>);

$redis-&gt;setex(
    <span class="hljs-string">'photos'</span>,
    <span class="hljs-number">3600</span>,
    $response-&gt;getBody()-&gt;getContents()
);
</code></pre>
<p>Here, you create a new key called <code>photos</code>, give it an expiration time of 1 hour, then assign it the raw response gotten from JSONPlaceholder.</p>
<p>But at this point the API still takes a long time to respond. This is because you're only storing this response, you're not using Redis to return the response. </p>
<p>To fix this, when a new request comes in, check if you have some data previosuly stored in-memory. If yes, you return the data in-memory, else, you make a call to JSONPlaceholder.</p>
<p>Update the <code>/photos</code> block to this:</p>
<pre><code class="lang-php"><span class="hljs-comment">/**
 * Route to get all photos
 */</span>
$router-&gt;map(<span class="hljs-string">'GET'</span>, <span class="hljs-string">'/photos'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) <span class="hljs-title">use</span> (<span class="hljs-params">$client, $redis</span>) </span>{
    <span class="hljs-comment">// Check if Redis has the key</span>
    <span class="hljs-keyword">if</span> (!$redis-&gt;exists(<span class="hljs-string">'photos'</span>)) {
        $response = $client-&gt;request(<span class="hljs-string">'GET'</span>, <span class="hljs-string">'https://jsonplaceholder.typicode.com/photos'</span>);

        <span class="hljs-comment">// Store the data for next use</span>
        $redis-&gt;setex(
            <span class="hljs-string">'photos'</span>,
            REDIS_STANDARD_EXPIRY,
            $response-&gt;getBody()-&gt;getContents()
        );
    }

    header(<span class="hljs-string">'Content-Type: application/json; charset=utf-8'</span>);
    <span class="hljs-keyword">echo</span> json_encode([
        <span class="hljs-string">'data'</span> =&gt; json_decode($redis-&gt;get(<span class="hljs-string">'photos'</span>))
    ]);
});
</code></pre>
<p>Testing in Postman to see improvements, you see the average response time after the first call (the original call before it is cached) has dropped to an average of 20ms for the <code>/photos</code> route. This is an improvement of over 50x. Redis saves a lot of processing time and power.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/Screenshot-2023-04-30-at-21.11.34.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Update the <code>/photos/id</code> route to use Redis too:</p>
<pre><code class="lang-php">$router-&gt;map(<span class="hljs-string">'GET'</span>, <span class="hljs-string">'/photos/[i:id]'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"><span class="hljs-keyword">int</span> $id</span>) <span class="hljs-title">use</span> (<span class="hljs-params">$client, $redis</span>) </span>{
    <span class="hljs-keyword">if</span> (!$redis-&gt;exists(<span class="hljs-string">'photos:'</span> . $id)) {
        $response = $client-&gt;request(<span class="hljs-string">'GET'</span>, <span class="hljs-string">'https://jsonplaceholder.typicode.com/photos/'</span> . $id);

        $redis-&gt;setex(
            <span class="hljs-string">'photos:'</span> . $id,
            REDIS_STANDARD_EXPIRY,
            $response-&gt;getBody()-&gt;getContents()
        );
    }

    header(<span class="hljs-string">'Content-Type: application/json; charset=utf-8'</span>);
    <span class="hljs-keyword">echo</span> json_encode([
        <span class="hljs-string">'data'</span> =&gt; json_decode($redis-&gt;get(<span class="hljs-string">'photos:'</span> . $id))
    ]);
});
</code></pre>
<p>The <code>/photos/id</code> route is now also much faster as it takes less than 5ms to get a response, an improvement of over 45x.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/Screenshot-2023-04-30-at-21.12.31.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-summary">Summary</h2>
<p>I hope you now understand the what Redis is, its basics, and how you can use it to enhance the speed of your PHP web applications. You can find the code files used in this article on <a target="_blank" href="https://github.com/Zubs/php-redis">GitHub</a>.</p>
<p>If you have any questions or relevant advice, please get in touch with me to share them.</p>
<p>To read more of my articles or follow my work, you can connect with me on <a target="_blank" href="https://www.linkedin.com/in/idris-aweda-zubair-5433121a3/">LinkedIn</a>, <a target="_blank" href="https://twitter.com/AwedaIdris">Twitter</a>, and <a target="_blank" href="https://github.com/Zubs">Github</a>. It’s quick, it’s easy, and it’s free!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use SQL Triggers ]]>
                </title>
                <description>
                    <![CDATA[ MySQL Triggers are like JavaScript event listeners. They are not executed until an action that they have been told to listen for happens.  Here's a helpful description of them from the MySQL docs: A trigger is a named database object that is associa... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/sql-triggers/</link>
                <guid isPermaLink="false">66c4c6ab99f22436b71945df</guid>
                
                    <category>
                        <![CDATA[ database ]]>
                    </category>
                
                    <category>
                        <![CDATA[ MySQL ]]>
                    </category>
                
                    <category>
                        <![CDATA[ SQL ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Zubair Idris Aweda ]]>
                </dc:creator>
                <pubDate>Tue, 21 Feb 2023 20:13:01 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/02/pexels-tima-miroshnichenko-5640619.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>MySQL Triggers are like JavaScript event listeners. They are not executed until an action that they have been told to listen for happens. </p>
<p>Here's a helpful description of them from the MySQL docs:</p>
<blockquote>
<p>A trigger is a named database object that is associated with a table, and that activates when a particular event occurs for the table.   </p>
<p>Some uses for triggers are to perform checks of values to be inserted into a table or to perform calculations on values involved in an update. - <a target="_blank" href="https://dev.mysql.com/doc/refman/8.0/en/triggers.html">MySQL.com</a></p>
</blockquote>
<p>Triggers are useful for automating repetitive tasks. You can just set up a trigger to do some calculation after every specific database action. You can also set up a trigger to perform data validation tasks on a table.</p>
<p>A trigger gets fired when an <code>INSERT</code>, <code>UPDATE</code> or <code>DELETE</code> operation happens on a database table. A trigger is fired per row, so if multiple rows of data are being inserted or deleted, each one still fires the action setup by the trigger. A trigger can be set to fire before or after an action.</p>
<p>In this tutorial, you'll learn how to create triggers, how to drop them, and when they're useful.</p>
<h2 id="heading-how-to-create-a-trigger">How to Create A Trigger</h2>
<p>To create a new trigger, use the <code>CREATE TRIGGER</code> command. This command has the following structure:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TRIGGER</span> trigger_name
trigger_time 
trigger_event
<span class="hljs-keyword">ON</span> table_name 
<span class="hljs-keyword">FOR</span> <span class="hljs-keyword">EACH</span> <span class="hljs-keyword">ROW</span>
trigger_body
</code></pre>
<p>So here's a breakdown of every line:</p>
<ul>
<li>The keyword <code>CREATE TRIGGER</code> is mandatory and is followed by the name of the trigger. You'll use this name to refer to the trigger in future, and to delete the trigger if the need ever arises. This name should be unique per database.</li>
<li>The <code>trigger_time</code> is a variable value that can only be either <code>BEFORE</code> or <code>AFTER</code>. This determines whether the trigger will fire before or after the event has happened.</li>
<li>The <code>trigger_event</code> is another variable that has a limited number of possible options. This variable cannot be any value other than <code>INSERT</code>, <code>UPDATE</code>, or <code>DELETE</code>. It specifies what event to listen for.</li>
<li><code>table_name</code> is the name of the table the trigger should watch. This has to be the name of an existing table in your database, but it can be an empty table.</li>
<li>The <code>FOR EACH ROW</code> is the other mandatory part of the trigger definition.</li>
<li><code>trigger_body</code> is the SQL query that you want to be run when this trigger is fired.</li>
</ul>
<p>To create an example trigger, I will create a simple <code>users</code> table for practice.</p>
<pre><code class="lang-sql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span>
    <span class="hljs-keyword">users</span> (
        fullname <span class="hljs-built_in">VARCHAR</span>(<span class="hljs-number">120</span>),
        email <span class="hljs-built_in">VARCHAR</span>(<span class="hljs-number">120</span>),
        username <span class="hljs-built_in">VARCHAR</span>(<span class="hljs-number">30</span>),
        <span class="hljs-keyword">password</span> <span class="hljs-built_in">VARCHAR</span>(<span class="hljs-number">60</span>)
    );
</code></pre>
<p>Now, we can create a simple trigger and attach it to this empty table. A trigger that encrypts string passwords before they are inserted using the <code>MD5</code> function would make sense.</p>
<pre><code class="lang-sql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TRIGGER</span> password_hasher <span class="hljs-keyword">BEFORE</span> <span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">ON</span> <span class="hljs-keyword">users</span> <span class="hljs-keyword">FOR</span> <span class="hljs-keyword">EACH</span> <span class="hljs-keyword">ROW</span>
<span class="hljs-keyword">SET</span>
    NEW.password = <span class="hljs-keyword">MD5</span> (NEW.password);
</code></pre>
<p>This example is pretty straightforward and self-explanatory. But there's a <code>NEW</code> keyword there. This keyword gives you access to the new data being created and lets you use or modify the values as you like. </p>
<p>You can only modify these values if your set <code>event_time</code> is <code>BEFORE</code>. If the <code>event_time</code> is set to <code>AFTER</code>, the data has already been stored before getting to the trigger so it cannot be modified again.  </p>
<p>You can use the <code>NEW</code> keyword in <code>INSERT</code> and <code>UPDATE</code> events but not the <code>DELETE</code> event.</p>
<p>There's also the <code>OLD</code> keyword that you can use in <code>DELETE</code> and <code>UPDATE</code> event triggers that gives you access to the former values of the affected record. You can't use this keyword on an <code>INSERT</code> event because there is no previous record before new data is created.</p>
<p>To test this trigger, insert a row into the <code>users</code> table:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span>
    <span class="hljs-keyword">users</span>
<span class="hljs-keyword">VALUES</span>
    (
        <span class="hljs-string">'idris babu'</span>,
        <span class="hljs-string">'zubs@test.com'</span>,
        <span class="hljs-string">'zubby1'</span>,
        <span class="hljs-string">'password'</span>
    );
</code></pre>
<p>Check your table for the values. You should have something like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/Screenshot-2023-02-18-at-02.14.44.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The password value has been correctly encrypted. 🥳</p>
<h2 id="heading-how-to-drop-a-trigger">How to Drop a Trigger</h2>
<p>After creating a trigger, you might want to stop its execution for some reason. In this case, you can drop the trigger. </p>
<p>To drop the trigger, use the <code>DROP TRIGGER</code> command. The command only requires the name of the trigger. You can use the command like this:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">DROP</span> <span class="hljs-keyword">TRIGGER</span> password_hasher;
</code></pre>
<p>Running this query will remove the trigger that we created above and every record inserted from now on will not have the password encrypted. </p>
<p>To test this, insert the same record as before, and check the result.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/Screenshot-2023-02-18-at-02.24.21.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The newly created record doesn't have an encrypted password.</p>
<p>Something to keep in mind: if you drop the table completely, all associated triggers are also dropped automatically.</p>
<h2 id="heading-when-to-use-triggers">When to Use Triggers</h2>
<ol>
<li>Logging: You can have a trigger to automatically write to another table on insertion, update, or deletion of record from a table.</li>
<li>Data validation: You can write a trigger to ensure data is a certain type and correct values can be set when needed.</li>
<li>Data syncronisation: You can use a trigger to keep related tables updated. For example, in an ecommerce table, every time a sales record gets created, a trigger can update the vendor's balance. Or if the vendor's record is deleted, a trigger can remove all their products.</li>
</ol>
<h2 id="heading-summary"><strong>Summary</strong></h2>
<p>I hope you now understand SQL triggers and when to use them so you can write better queries.</p>
<p>If you have any questions or relevant advice, please get in touch with me to share them.</p>
<p>To read more of my articles or follow my work, you can connect with me on <a target="_blank" href="https://www.linkedin.com/in/idris-aweda-zubair-5433121a3/">LinkedIn</a>, <a target="_blank" href="https://twitter.com/AwedaIdris">Twitter</a>, and <a target="_blank" href="https://github.com/Zubs">Github</a>. It’s quick, it’s easy, and it’s free!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use MySQL Common Table Expressions – with Example Queries ]]>
                </title>
                <description>
                    <![CDATA[ In your day to day job as a Software Engineer or Database Administrator, you'll likely have to write long complex queries, often with some subqueries.  These queries over time become less performant, difficult to read and understand, and even more di... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/mysql-common-table-expressions/</link>
                <guid isPermaLink="false">66c4c6a51b22d2d8d9040ecc</guid>
                
                    <category>
                        <![CDATA[ database ]]>
                    </category>
                
                    <category>
                        <![CDATA[ MySQL ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Zubair Idris Aweda ]]>
                </dc:creator>
                <pubDate>Mon, 20 Feb 2023 17:52:56 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/02/Common-dining-table-eettafel-Esstisch-04-1280x854.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In your day to day job as a Software Engineer or Database Administrator, you'll likely have to write long complex queries, often with some subqueries. </p>
<p>These queries over time become less performant, difficult to read and understand, and even more difficult to manage. And no one wants to do the hard job of refactoring them, so they just live on. </p>
<p>Or you have probably had to fetch similar data based on a set of data or parameters. To achieve this, you write many similar, sometimes exactly identical subqueries and bring them together using the UNION keyword. </p>
<p>Well, you can make your life easier and solve these problems efficiently using a Common Table Expression.</p>
<blockquote>
<p>A common table expression (CTE) is a named temporary result set that exists within the scope of a single statement and that can be referred to later within that statement, possibly multiple times. – <a target="_blank" href="https://dev.mysql.com/doc/refman/8.0/en/with.html">MySQL.com</a></p>
</blockquote>
<p>Using a Common Table Expression, you can write more readable and more performant queries very easily. It's actually easier than it is to write multiple subqueries that could make your queries unreadable and less performant.</p>
<p>You'll primarily use a common table expression for two reasons:</p>
<ul>
<li>To write queries without using subqueries (or using fewer subqueries)</li>
<li>To write recursive functions</li>
</ul>
<p>In this tutorial, I'll show you how to write your own common table expressions.</p>
<h2 id="heading-how-to-create-a-common-table-expression">How to Create a Common Table Expression</h2>
<p>You can create a Common Table Expression (CTE) using the <code>WITH</code> keyword. You can specify multiple common table expressions at the same time by comma-separating the queries making up each common table expression.</p>
<p>The general shape of a Common Table Expression is like so:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">WITH</span> cte_name <span class="hljs-keyword">AS</span> (<span class="hljs-keyword">query</span>)

<span class="hljs-comment">-- Multiple CTEs</span>
<span class="hljs-keyword">WITH</span>
    cte_name1 <span class="hljs-keyword">AS</span> (
        <span class="hljs-comment">-- Query here</span>
    ),
    cte_name2 <span class="hljs-keyword">AS</span> (
        <span class="hljs-comment">-- Query here</span>
    )
</code></pre>
<p>The <code>WITH</code> keyword is followed by the CTE name. After the name, you introduce the query to be run in the CTE using the <code>AS</code> keyword. You need to enclose the query must in parentheses. The CTE cannot be followed by a semicolon like other SQL queries. Instead it is followed by another query that uses it.</p>
<p>After creating a CTE, you can easily use the result of the queries run in the CTE by referencing the CTE in other queries, other CTEs, or even in itself.</p>
<h3 id="heading-cte-example">CTE Example</h3>
<p>If you have a table of world_cup players, for example, you can create a CTE like this:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">WITH</span>
    barca_players <span class="hljs-keyword">AS</span> (
        <span class="hljs-keyword">SELECT</span>
            <span class="hljs-keyword">id</span>,
            player_name,
            nationality,
            <span class="hljs-keyword">position</span>,
            <span class="hljs-keyword">TIMESTAMPDIFF</span> (<span class="hljs-keyword">YEAR</span>, player_dob, <span class="hljs-keyword">CURRENT_DATE</span>) age
        <span class="hljs-keyword">FROM</span>
            wc_players
        <span class="hljs-keyword">WHERE</span>
            club = <span class="hljs-string">'Barcelona'</span>
    )
<span class="hljs-keyword">SELECT</span>
    *
<span class="hljs-keyword">FROM</span>
    barca_players;
</code></pre>
<p>Here, we've created a CTE named <code>barca_players</code>. This CTE will return the name, position, age, and nationality of every Barcelona player that was at the world cup. It contains the subquery:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span>
    <span class="hljs-keyword">id</span>,
    player_name,
    nationality,
    <span class="hljs-keyword">position</span>,
    <span class="hljs-keyword">TIMESTAMPDIFF</span> (<span class="hljs-keyword">YEAR</span>, player_dob, <span class="hljs-keyword">CURRENT_DATE</span>) age
<span class="hljs-keyword">FROM</span>
    wc_players
<span class="hljs-keyword">WHERE</span>
    club = <span class="hljs-string">'Barcelona'</span>;
</code></pre>
<p>This subquery is what produces the CTE result. Next, it is followed by a query that uses this result. You can see the result of selecting every record in the CTE below.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/Screenshot-2023-02-17-at-22.59.25.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>You can also select only specific fields from the CTE, for example:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">WITH</span>
    barca_players <span class="hljs-keyword">AS</span> (
        <span class="hljs-keyword">SELECT</span>
            <span class="hljs-keyword">id</span>,
            player_name,
            nationality,
            <span class="hljs-keyword">position</span>,
            <span class="hljs-keyword">TIMESTAMPDIFF</span> (<span class="hljs-keyword">YEAR</span>, player_dob, <span class="hljs-keyword">CURRENT_DATE</span>) age
        <span class="hljs-keyword">FROM</span>
            wc_players
        <span class="hljs-keyword">WHERE</span>
            club = <span class="hljs-string">'Barcelona'</span>
    )
<span class="hljs-keyword">SELECT</span>
    player_name,
    <span class="hljs-keyword">position</span>
<span class="hljs-keyword">FROM</span>
    barca_players;
</code></pre>
<p>This query is almost the same as the first one, except that it selects only the player names and positions from the list.</p>
<h2 id="heading-how-to-use-common-table-expressions-with-parameters">How to Use Common Table Expressions With Parameters</h2>
<p>You can also pass arguments to the CTE. These are aliases you can use for referencing columns of the query results. The number of parameters passed into the CTE must be the same as the number of columns being selected in its subquery. This is because the columns get matched to the aliases one by one, one after the other.</p>
<p>For example, in the <code>barca_players</code> CTE created above, you can decide to refer to the <code>nationality</code> column as <code>country</code>, and <code>position</code> as <code>role</code>:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">WITH</span>
    barca_players (<span class="hljs-keyword">id</span>, player_name, country, <span class="hljs-keyword">role</span>, age) <span class="hljs-keyword">AS</span> (
        <span class="hljs-keyword">SELECT</span>
            <span class="hljs-keyword">id</span>,
            player_name,
            nationality,
            <span class="hljs-keyword">position</span>,
            <span class="hljs-keyword">TIMESTAMPDIFF</span> (<span class="hljs-keyword">YEAR</span>, player_dob, <span class="hljs-keyword">CURRENT_DATE</span>) age
        <span class="hljs-keyword">FROM</span>
            wc_players
        <span class="hljs-keyword">WHERE</span>
            club = <span class="hljs-string">'Barcelona'</span>
    )
<span class="hljs-keyword">SELECT</span>
    player_name,
    <span class="hljs-keyword">role</span>
<span class="hljs-keyword">FROM</span>
    barca_players;
</code></pre>
<p>Notice that in the CTE subquery, you still use the correct column names. But in the outer <code>SELECT</code> query, you use the new aliases specified as parameters to the CTE.</p>
<h2 id="heading-recursive-common-table-expressions">Recursive Common Table Expressions</h2>
<p>When you reference a Common Table Expression within itself, it becomes a recursive Common Table Expression. </p>
<p>A Recursive Common Table Expression, as the name implies, is a common table expression that can run a subquery multiple times, as long as a condition is met. It iterates continuously until it reaches a break point, when the condition stops being true.</p>
<p>To define a recursive CTE, the <code>RECURSIVE</code> keyword must be in its name. Without this keyword, MySQL throws an error.</p>
<p>For example, you can write a common table expression that prints numbers 1 to 10 and their squares like this:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">WITH</span> <span class="hljs-keyword">RECURSIVE</span>
    numbers_list (n, <span class="hljs-keyword">square</span>) <span class="hljs-keyword">AS</span> (
        <span class="hljs-keyword">SELECT</span>
            <span class="hljs-number">1</span>,
            <span class="hljs-number">1</span>
        <span class="hljs-keyword">UNION</span> <span class="hljs-keyword">ALL</span>
        <span class="hljs-keyword">SELECT</span>
            n + <span class="hljs-number">1</span>,
            (n + <span class="hljs-number">1</span>) * (n + <span class="hljs-number">1</span>)
        <span class="hljs-keyword">FROM</span>
            numbers_list
        <span class="hljs-keyword">WHERE</span>
            n &lt; <span class="hljs-number">10</span>
    )
<span class="hljs-keyword">SELECT</span>
    *
<span class="hljs-keyword">FROM</span>
    numbers_list;
</code></pre>
<p>Let's examine what is happening here:</p>
<p>In the first two lines, the recursive common table expression is defined with two parameters, one representing the column for the number, and the other representing the column for the square:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">WITH</span> <span class="hljs-keyword">RECURSIVE</span>
    numbers_list (n, <span class="hljs-keyword">square</span>) <span class="hljs-keyword">AS</span> (
</code></pre>
<p>Next, the subquery. The subquery is in two parts, joined by the <code>UNION ALL</code> keyword to form one. You can also join these subqueries by the <code>UNION</code> keyword if you don't need duplicate records. </p>
<p>The first part of the subquery is a key part of recursive common table expressions. It is the base query, the first result set, the initial iteration. This query is the starting point of all iterations. </p>
<p>In this example, it is static, as no records are being fetched.</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span>
    <span class="hljs-number">1</span>,
    <span class="hljs-number">1</span>
</code></pre>
<p>After this first query, the result table has one row, and looks like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/Screenshot-2023-02-17-at-23.55.27.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The second part of the subquery is where the iteration really happens. </p>
<p>In this query, the CTE is referenced within itself, and its columns can be used. When a column name is mentioned, the most recent value of that column is taken. </p>
<p>So at the start of the iteration, <code>n</code> is 1 and <code>square</code> is also 1. That means, <code>n + 1</code> is 2, and <code>(n + 1) * (n + 1)</code> is 2 *2 which is 4. 2 and 4 get added to the result table and then become the most recent values in the table. <code>n</code> becomes 2, and <code>square</code> becomes <code>4</code>. </p>
<p>This continues until the condition in the <code>WHERE</code> keyword is stops being true.</p>
<p>The <code>WHERE</code> keyword in the query specifies the breakpoint of the CTE. Until the condition specified is met, the query keeps getting run. In this case, after every iteration, the query checks if <code>n</code> is less than 10.</p>
<p>If a condition that will always evaluate to true is set, then this creates an endless loop and you get an error like <code>Recursive query aborted after 1001 iterations. Try increasing @@cte_max_recursion_depth to a larger value.</code></p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span>
    n + <span class="hljs-number">1</span>,
    (n + <span class="hljs-number">1</span>) * (n + <span class="hljs-number">1</span>)
<span class="hljs-keyword">FROM</span>
    numbers_list
<span class="hljs-keyword">WHERE</span>
    n &lt; <span class="hljs-number">10</span>
</code></pre>
<p>Now you might think, "If the condition checks for <code>n &lt; 10</code> , how come 10 is still in the final table?". </p>
<p>Well, the reason is because in SQL, the <code>WHERE</code> keyword part of a query is evaluated first before other parts. So, when <code>n = 9</code> is the last row, the query runs once more, and before insertion or anything, it checks if 9 is less than 10. Since 9 is less than 10, it adds <code>n + 1</code> which is 10 to the list. Then on the next iteration, 10 is the most recent record and it is not less than itself, so the loop ends. </p>
<p>Keep in mind that a Recursive Common Table Expression consists of a recursive <code>SELECT</code> query, and a non-recursive <code>SELECT</code> query.</p>
<h3 id="heading-simple-recursive-common-table-expression-rules">Simple Recursive Common Table Expression Rules</h3>
<ul>
<li>You can't use the <code>GROUP BY</code> keyword. This is because you can only group a collection, but in a recursive common table expression, records are handled and evaluated individually. Other keywords like <code>ORDER BY</code>, <code>DISTINCT</code>, and aggregate functions like <code>SUM</code> cannot be used either.</li>
<li>You can't use window functions.</li>
</ul>
<p>These rules apply to the recursive part of a recursive common table expression.</p>
<h3 id="heading-use-cases-for-recursive-ctes">Use Cases for Recursive CTEs</h3>
<h4 id="heading-fibonacci-sequence">Fibonacci Sequence</h4>
<blockquote>
<p>The Fibonacci sequence is a sequence in which each number is the sum of the two preceding ones. The sequence commonly starts from 0 and 1, although some authors start the sequence from 1 and 1 or sometimes from 1 and 2. (<a target="_blank" href="https://en.wikipedia.org/wiki/Fibonacci_number">source</a>)</p>
</blockquote>
<p>You can easily generate a Fibonacci sequence of any length using a recursive common table expression. For example, here's a query that will get the first 20 numbers of a Fibonacci sequence starting from 0 and 1.</p>
<pre><code class="lang-sql"><span class="hljs-keyword">WITH</span> <span class="hljs-keyword">RECURSIVE</span>
    fibonacci (n, fib_n, next_fib_n) <span class="hljs-keyword">AS</span> (
        <span class="hljs-comment">/*
        * n - Number of iterations
        * fib_n - Currennt Fibonnaci number. Starts at 0
        * next_fib_n - Next Fibonnaci number. Starts at 1
        */</span>
        <span class="hljs-keyword">SELECT</span>
            <span class="hljs-number">1</span>,
            <span class="hljs-number">0</span>,
            <span class="hljs-number">1</span>
        <span class="hljs-keyword">UNION</span> <span class="hljs-keyword">ALL</span>
        <span class="hljs-keyword">SELECT</span>
            n + <span class="hljs-number">1</span>,
            next_fib_n,
            fib_n + next_fib_n
        <span class="hljs-keyword">FROM</span>
            fibonacci
        <span class="hljs-keyword">WHERE</span>
            n &lt; <span class="hljs-number">20</span>
    )
<span class="hljs-keyword">SELECT</span>
    *
<span class="hljs-keyword">FROM</span>
    fibonacci;
</code></pre>
<h4 id="heading-hierarchical-data-traversal">Hierarchical Data Traversal</h4>
<p>In many application databases, you will find that hierarchical data is stored in the same table.</p>
<p>For example, a <code>categories</code> table will usually contain main categories and sub-categories referencing their parent category. An <code>employees</code> table will contain regular employees with their <code>manager_id</code>, as well as their managers or supervisors, because they are also employees.</p>
<p>If you had a <code>categories</code> table like this, with 4 records, 1 main category, and a chain of  sub-categories:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span>
    categories (
        <span class="hljs-keyword">id</span> <span class="hljs-built_in">int</span>,
        cat_name <span class="hljs-built_in">varchar</span>(<span class="hljs-number">100</span>),
        parent_category_id <span class="hljs-built_in">int</span> <span class="hljs-keyword">DEFAULT</span> <span class="hljs-literal">NULL</span>
    );

<span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span>
    categories
<span class="hljs-keyword">VALUES</span>
    (<span class="hljs-number">1</span>, <span class="hljs-string">'Mens'</span>, <span class="hljs-literal">NULL</span>),
    (<span class="hljs-number">2</span>, <span class="hljs-string">'Tops'</span>, <span class="hljs-number">1</span>),
    (<span class="hljs-number">3</span>, <span class="hljs-string">'Jerseys'</span>, <span class="hljs-number">2</span>),
    (<span class="hljs-number">4</span>, <span class="hljs-string">'England'</span>, <span class="hljs-number">3</span>);
</code></pre>
<p>You can fetch each category, with its parent category attached easily like this:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">WITH</span> <span class="hljs-keyword">RECURSIVE</span>
    category_tree <span class="hljs-keyword">AS</span> (
        <span class="hljs-keyword">SELECT</span>
            <span class="hljs-keyword">id</span>,
            cat_name,
            parent_category_id,
            cat_name <span class="hljs-keyword">AS</span> full_name
        <span class="hljs-keyword">FROM</span>
            categories
        <span class="hljs-keyword">WHERE</span>
            parent_category_id <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span>
        <span class="hljs-keyword">UNION</span> <span class="hljs-keyword">ALL</span>
        <span class="hljs-keyword">SELECT</span>
            c.id,
            c.cat_name,
            c.parent_category_id,
            <span class="hljs-keyword">CONCAT</span> (ct.full_name, <span class="hljs-string">' &gt; '</span>, c.cat_name)
        <span class="hljs-keyword">FROM</span>
            categories c
            <span class="hljs-keyword">JOIN</span> category_tree ct <span class="hljs-keyword">ON</span> c.parent_category_id = ct.id
    )
<span class="hljs-keyword">SELECT</span>
    full_name
<span class="hljs-keyword">FROM</span>
    category_tree;
</code></pre>
<p>In this example, the base query selects the root category, where <code>parent_category_id IS NULL</code>. Then it goes on to look for a category where the <code>parent_category_id</code> is the <code>id</code> of the current category by using a <code>JOIN</code>. It repeats this until it gets to the final category. The result of this query is the following:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/Screenshot-2023-02-18-at-01.19.10.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-summary"><strong>Summary</strong></h2>
<p>I hope you now understand how to use MySQL Common Table Expressions, their variations (regular and recursive), and when to use them so you can write better queries. You can find more about common table expressions in the docs <a target="_blank" href="https://dev.mysql.com/doc/refman/8.0/en/with.html">here</a>.</p>
<p>If you have any questions or relevant advice, please get in touch with me to share them.</p>
<p>To read more of my articles or follow my work, you can connect with me on <a target="_blank" href="https://www.linkedin.com/in/idris-aweda-zubair-5433121a3/">LinkedIn</a>, <a target="_blank" href="https://twitter.com/AwedaIdris">Twitter</a>, and <a target="_blank" href="https://github.com/Zubs">Github</a>. It’s quick, it’s easy, and it’s free!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ MySQL Date Functions – Explained with Example Queries ]]>
                </title>
                <description>
                    <![CDATA[ SQL is a programming language we use to interact with relational databases. SQL databases contain tables, which contain rows of data. These tables can contain a wide range of data types. In this article, you'll learn how MySQL functions help make dat... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/mysql-date-functions/</link>
                <guid isPermaLink="false">66c4c6a8bd556981b1bdc460</guid>
                
                    <category>
                        <![CDATA[ database ]]>
                    </category>
                
                    <category>
                        <![CDATA[ MySQL ]]>
                    </category>
                
                    <category>
                        <![CDATA[ SQL ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Zubair Idris Aweda ]]>
                </dc:creator>
                <pubDate>Wed, 25 Jan 2023 17:15:13 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/01/image-162-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>SQL is a programming language we use to interact with relational databases. SQL databases contain tables, which contain rows of data. These tables can contain a wide range of data types.</p>
<p>In this article, you'll learn how MySQL functions help make date management very easy. </p>
<p>These functions help perform various tasks. Some perform simple tasks like adding days to dates, finding how many days are between two dates, or even more complicated tasks like how to tell how far into a year a date is by number of days.</p>
<p>Before proceeding, keep in mind that this article was written on <code>2023-01-24</code>. So your results on running the queries here might be slightly different based on when you read it.</p>
<h2 id="heading-how-to-use-the-currentdate-function-in-sql">How to Use the <code>CURRENT_DATE</code> Function in SQL</h2>
<p>This function returns today's date in the format '<strong>YYYY-MM-DD</strong>'. It is one of the simplest MySQL functions to use. It takes no arguments at all.</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">CURRENT_DATE</span>;
<span class="hljs-comment">-- Returns 2023-01-24</span>
</code></pre>
<p>This function has synonymous functions that work just the way it does: <code>CUR_DATE</code> and <code>CURRENT_DATE()</code> will return the exact same result as <code>CURRENT_DATE</code>.</p>
<h2 id="heading-how-to-use-the-adddate-function-in-sql">How to Use the <code>ADDDATE</code> Function in SQL</h2>
<p>This functions performs additions, or subtractions, on date values. It takes an interval that can be in days, or months, or even years. This interval can be positive or negative. The function takes this format:</p>
<pre><code class="lang-sql">ADDDATE(date/expr, INTERVAL expr unit);
</code></pre>
<p>Here, the <code>date/expr</code> refers to the base date value to be added to or subtracted from. And the <code>INTERVAL</code> is a constant keyword that has to come before the <code>expr</code> that is used to set the value of the increment in numbers. Finally, you have the unit, which can be <code>day</code>, <code>week</code>,  <code>month</code>, <code>quarter</code> or even <code>year</code>.  The <code>unit</code> can also be a smaller value like <code>second</code> or even <code>microsecond</code>. Check the <a target="_blank" href="https://dev.mysql.com/doc/refman/8.0/en/expressions.html#temporal-intervals">MySQL docs</a> for more possible values.</p>
<p>This functions works exactly the same as the <code>DATE_ADD</code> and you can use them interchangeably.</p>
<p>Using ADDDATE, you can find the date of 45 days from today like this:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> ADDDATE(<span class="hljs-keyword">CURRENT_DATE</span>, <span class="hljs-built_in">INTERVAL</span> <span class="hljs-number">45</span> <span class="hljs-keyword">DAY</span>);
<span class="hljs-comment">-- Returns 2023-03-10</span>
</code></pre>
<p>To get the date of the day 7 months and 3 weeks ago, use the ADDDATE like this:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> ADDDATE(
    ADDDATE(<span class="hljs-keyword">CURRENT_DATE</span>, <span class="hljs-built_in">INTERVAL</span> <span class="hljs-number">-7</span> <span class="hljs-keyword">MONTH</span>), 
    <span class="hljs-built_in">INTERVAL</span> <span class="hljs-number">-3</span> <span class="hljs-keyword">WEEK</span>
);
<span class="hljs-comment">-- Returns 2022-06-03</span>
</code></pre>
<p>Here, we called the ADDDATE function twice. First, to get the date of 7 months ago. Then, we called it again to get the date of 3 weeks before that time.</p>
<p>A common use case of ADDDATE in real life applications is to get data values to be used in a WHERE clause as a range. </p>
<p>For example, if you had an <code>employees</code> table with a <code>hiredate</code> field that stores their resumption date. To see all employees that resumed in the past year (where <code>hiredate</code> &gt; the date of a year ago), use ADDDATE like this:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> * 
<span class="hljs-keyword">FROM</span> employees 
<span class="hljs-keyword">WHERE</span> hiredate &gt; ADDDATE(<span class="hljs-keyword">CURRENT_DATE</span>, <span class="hljs-built_in">INTERVAL</span> <span class="hljs-number">-1</span> <span class="hljs-keyword">YEAR</span>);
</code></pre>
<p>Another common case would be when you have to filter by a time range. In a <code>songs</code> table with a <code>released</code> field, to fetch all songs released in the last three weeks except for the ones released this week, use ADDDATE like this:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> * 
<span class="hljs-keyword">FROM</span> songs 
<span class="hljs-keyword">WHERE</span> released 
<span class="hljs-keyword">BETWEEN</span> ADDDATE(<span class="hljs-keyword">CURRENT_DATE</span>, <span class="hljs-built_in">INTERVAL</span> <span class="hljs-number">-3</span> <span class="hljs-keyword">WEEK</span>) 
<span class="hljs-keyword">AND</span> ADDDATE(<span class="hljs-keyword">CURRENT_DATE</span>, <span class="hljs-built_in">INTERVAL</span> <span class="hljs-number">-1</span> <span class="hljs-keyword">WEEK</span>);
</code></pre>
<h2 id="heading-how-to-use-the-datediff-function-in-sql">How to Use the <code>DATEDIFF</code> Function in SQL</h2>
<p>This function returns the number of days between two dates. It takes in the two dates to be subtracted. Let's use <code>DATEDIFF</code> to find the number of days between today and <code>2023-03-10</code>.</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">DATEDIFF</span>(<span class="hljs-string">'2023-03-10'</span>, <span class="hljs-keyword">CURRENT_DATE</span>);
<span class="hljs-comment">-- Returns 45</span>
</code></pre>
<p>Rearranging the dates and calling the function again results in a difference in the response:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">DATEDIFF</span>(<span class="hljs-keyword">CURRENT_DATE</span>, <span class="hljs-string">'2023-03-10'</span>);
<span class="hljs-comment">-- Returns -45</span>
</code></pre>
<p>You can use this function with the <code>ABS</code> function to get the absolute value and not have issues with the negative sign or value.</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">ABS</span>(<span class="hljs-keyword">DATEDIFF</span>(<span class="hljs-keyword">CURRENT_DATE</span>, <span class="hljs-string">'2023-03-10'</span>));
<span class="hljs-comment">-- Returns 45</span>
</code></pre>
<p>This is very useful when you have to return data with respect to time. <code>For example, in many blogs, you see a part that says something like 'Posted 7 days ago'. You can use the</code>DATEDIFF` to get this value easily.</p>
<h2 id="heading-how-to-use-the-dateformat-function-in-sql">How to Use the <code>DATE_FORMAT</code> Function in SQL</h2>
<p>This function lets you present your data anyhow you want it. This is a very useful function. It takes in the date to be formatted, and also a string representing the desired format. The function takes this format:</p>
<pre><code class="lang-sql">DATE_FORMAT(date, format)
</code></pre>
<p>The format string can be of any length and each character in it defines a specific format and must be prefixed by the percentage symbol, <code>%</code>. For example, given the date <code>2023-03-10</code>, you can present this as <code>Fri 10th March, 2023</code> like so:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">DATE_FORMAT</span>(<span class="hljs-string">'2023-03-10'</span>, <span class="hljs-string">'%a %D %M, %Y'</span>);
</code></pre>
<p>Here, we passed in the format string <code>'%a %D %M, %Y'</code>. But, what does this truly mean? Here's a few things to note:</p>
<ul>
<li>The provided format string, <code>'%a %D %M, %Y'</code>, is exactly the same shape as the result, <code>Fri 10th March, 2023</code>. This means you can shape the result anyhow you like – even the space characters matter. Every character in the format string is returned as part of the result, except it is prefixed using the percentage sign, then it is read as a format character. For example, rewriting the format string to <code>'45 days from today is %a, %D day of %M, %Y'</code> will result in <code>45 days from today is Fri, 10th day of March, 2023</code>.</li>
<li>The <code>a</code> used results in the abbreviated weekday name, Fri.</li>
<li>The <code>D</code> returned the day of the month with English suffix, 10th.</li>
<li>The <code>M</code> returned the name of the month, March.</li>
<li>The <code>Y</code> returned the year, 2023.</li>
</ul>
<p>There are many more characters that you can use in the format string, and you can find them <a target="_blank" href="https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_date-format">here</a>.</p>
<h2 id="heading-how-to-use-the-max-and-min-functions-in-sql">How to Use the <code>MAX</code> and <code>MIN</code> Functions in SQL</h2>
<p>While these functions aren't limited or specific to date data type, they are very useful when working with dates. You can use the MAX to find the latest record in a table. You can use the MIN to find the oldest record in a table.</p>
<p>In a table of <code>employees</code>, with a <code>birthday</code> field storing their date of birth, you can find the oldest employee using the MAX function like this:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> *
<span class="hljs-keyword">FROM</span> employees
<span class="hljs-keyword">WHERE</span> birthday = (<span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">MAX</span>(birthday) <span class="hljs-keyword">from</span> employees);
</code></pre>
<p>Or alternatively, like this:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> *
<span class="hljs-keyword">FROM</span> employees
<span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> birthday <span class="hljs-keyword">DESC</span>
<span class="hljs-keyword">LIMIT</span> <span class="hljs-number">1</span>;
</code></pre>
<p>You could get the youngest employee using the MIN function:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> *
<span class="hljs-keyword">FROM</span> employees
<span class="hljs-keyword">WHERE</span> birthday = (<span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">MIN</span>(birthday) <span class="hljs-keyword">from</span> employees);
</code></pre>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> *
<span class="hljs-keyword">FROM</span> employees
<span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> birthday
<span class="hljs-keyword">LIMIT</span> <span class="hljs-number">1</span>;
</code></pre>
<h2 id="heading-summary"><strong>Summary</strong></h2>
<p>I hope you now understand the MySQL date functions we discussed here, their variations and arguments, and when to use them so you can write better queries. You can find more of these functions <a target="_blank" href="https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html">here</a>.</p>
<p>If you have any questions or relevant advice, please get in touch with me to share them.</p>
<p>To read more of my articles or follow my work, you can connect with me on <a target="_blank" href="https://www.linkedin.com/in/idris-aweda-zubair-5433121a3/">LinkedIn</a>, <a target="_blank" href="https://twitter.com/AwedaIdris">Twitter</a>, and <a target="_blank" href="https://github.com/Zubs">Github</a>. It’s quick, it’s easy, and it’s free!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use JavaScript for Data Analysis – A Beginner's Guide ]]>
                </title>
                <description>
                    <![CDATA[ Data analysis involves taking data you have and extracting useful information from them. During the process, you need to clean the data, present them in a useful way, and draw conclusions that can help companies make important decisions. Data analysi... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/basics-of-data-analysis-with-javascript/</link>
                <guid isPermaLink="false">66c4c69326a77d9936ef0a79</guid>
                
                    <category>
                        <![CDATA[ data analysis ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Zubair Idris Aweda ]]>
                </dc:creator>
                <pubDate>Tue, 17 Jan 2023 21:59:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/01/pexels-burak-the-weekender-186461.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Data analysis involves taking data you have and extracting useful information from them. During the process, you need to clean the data, present them in a useful way, and draw conclusions that can help companies make important decisions.</p>
<p>Data analysis is commonly done with languages like Python and R. Very few people know that you can also perform Data Analysis with JavaScript, and it is pretty easy, too.</p>
<p>This article focuses on the most basic data analysis functions that you can do in JavaScript. Let's dive in.</p>
<h2 id="heading-how-to-find-the-average-with-javascript">How to Find the Average with JavaScript</h2>
<p>When you want to find the average of a group of numbers, you add them all together and divide by the number of items you have.</p>
<p>For example, if you have a group of numbers 2, 5, 7, 9, and 12, you add them all together and divide that result by 5 (there are five numbers in your group). So the average is 2+5+7+9+12 = 35, and 35/5 = 7. </p>
<p>The average, in other words, is the result obtained by dividing the sum of all the values in the set by the length or count of the set.</p>
<p>Take this sample set of random numbers between 1 and 1000 as an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> data = [
    <span class="hljs-number">943</span>, <span class="hljs-number">504</span>, <span class="hljs-number">733</span>, <span class="hljs-number">122</span>, <span class="hljs-number">868</span>, <span class="hljs-number">994</span>, <span class="hljs-number">553</span>, <span class="hljs-number">376</span>, <span class="hljs-number">450</span>, <span class="hljs-number">212</span>,
    <span class="hljs-number">295</span>, <span class="hljs-number">859</span>, <span class="hljs-number">29</span>, <span class="hljs-number">820</span>, <span class="hljs-number">148</span>, <span class="hljs-number">589</span>, <span class="hljs-number">621</span>, <span class="hljs-number">870</span>, <span class="hljs-number">941</span>, <span class="hljs-number">909</span>,
    <span class="hljs-number">725</span>, <span class="hljs-number">160</span>, <span class="hljs-number">198</span>, <span class="hljs-number">568</span>, <span class="hljs-number">409</span>, <span class="hljs-number">625</span>, <span class="hljs-number">207</span>, <span class="hljs-number">338</span>, <span class="hljs-number">162</span>, <span class="hljs-number">439</span>,
    <span class="hljs-number">894</span>, <span class="hljs-number">937</span>, <span class="hljs-number">929</span>, <span class="hljs-number">648</span>, <span class="hljs-number">91</span>, <span class="hljs-number">235</span>, <span class="hljs-number">550</span>, <span class="hljs-number">851</span>, <span class="hljs-number">626</span>, <span class="hljs-number">926</span>,
    <span class="hljs-number">190</span>, <span class="hljs-number">770</span>, <span class="hljs-number">33</span>, <span class="hljs-number">274</span>, <span class="hljs-number">79</span>, <span class="hljs-number">355</span>, <span class="hljs-number">768</span>, <span class="hljs-number">504</span>, <span class="hljs-number">415</span>, <span class="hljs-number">232</span>,
    <span class="hljs-number">33</span>, <span class="hljs-number">327</span>, <span class="hljs-number">100</span>, <span class="hljs-number">1000</span>, <span class="hljs-number">775</span>, <span class="hljs-number">803</span>, <span class="hljs-number">587</span>, <span class="hljs-number">676</span>, <span class="hljs-number">17</span>, <span class="hljs-number">952</span>,
    <span class="hljs-number">931</span>, <span class="hljs-number">838</span>, <span class="hljs-number">447</span>, <span class="hljs-number">358</span>, <span class="hljs-number">282</span>, <span class="hljs-number">606</span>, <span class="hljs-number">877</span>, <span class="hljs-number">185</span>, <span class="hljs-number">514</span>, <span class="hljs-number">263</span>,
    <span class="hljs-number">887</span>, <span class="hljs-number">725</span>, <span class="hljs-number">270</span>, <span class="hljs-number">716</span>, <span class="hljs-number">762</span>, <span class="hljs-number">633</span>, <span class="hljs-number">900</span>, <span class="hljs-number">948</span>, <span class="hljs-number">786</span>, <span class="hljs-number">28</span>,
    <span class="hljs-number">950</span>, <span class="hljs-number">858</span>, <span class="hljs-number">587</span>, <span class="hljs-number">804</span>, <span class="hljs-number">127</span>, <span class="hljs-number">803</span>, <span class="hljs-number">111</span>, <span class="hljs-number">609</span>, <span class="hljs-number">606</span>, <span class="hljs-number">461</span>,
    <span class="hljs-number">947</span>, <span class="hljs-number">868</span>, <span class="hljs-number">43</span>, <span class="hljs-number">432</span>, <span class="hljs-number">113</span>, <span class="hljs-number">607</span>, <span class="hljs-number">852</span>, <span class="hljs-number">698</span>, <span class="hljs-number">984</span>, <span class="hljs-number">575</span>
];
</code></pre>
<p>To calculate the average of this set in JavaScript, you can use the <code>array.reduce</code> method (to get the sum of the array) along with the <code>array.length</code> method (to get the count of values in the set) to find the average like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> average = data.reduce(<span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> a + b) / data.length; <span class="hljs-comment">// Returns 552.35</span>
</code></pre>
<p>You could also find the average using a third party library like <a target="_blank" href="https://www.npmjs.com/package/mathjs">math.js</a>, like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { mean } <span class="hljs-keyword">from</span> <span class="hljs-string">'mathjs'</span>;

<span class="hljs-keyword">const</span> average = mean(...data); <span class="hljs-comment">// Returns 552.35</span>
</code></pre>
<p>You can also find the average using either a <code>for</code> or a <code>forEach</code> loop.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> sum = <span class="hljs-number">0</span>;

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> datum <span class="hljs-keyword">of</span> data) sum += datum;

<span class="hljs-keyword">const</span> average = sum / data.length; <span class="hljs-comment">// Returns 552.35</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> sum = <span class="hljs-number">0</span>;

data.forEach(<span class="hljs-function">(<span class="hljs-params">datum</span>) =&gt;</span> sum += datum);

<span class="hljs-keyword">const</span> average = sum / data.length; <span class="hljs-comment">// Returns 552.35</span>
</code></pre>
<h2 id="heading-how-to-find-the-maximum-and-minimum-with-javascript">How to Find the Maximum and Minimum with JavaScript</h2>
<p>When you're working with functions, the maximum and minimum are the largest and smallest values of that function. You can calculate these for a specific range, or for the entire set of values.</p>
<p>Using the same array from above, we can get the maximum value using the <code>max</code> method of the built-in <code>Math</code> module.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> max = <span class="hljs-built_in">Math</span>.max(...data); <span class="hljs-comment">// Returns 1000</span>
</code></pre>
<p>You can also get the minimum value using the <code>min</code> method.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> min = <span class="hljs-built_in">Math</span>.min(...data); <span class="hljs-comment">// Returns 17</span>
</code></pre>
<p>Alternatively, you can also use a third partly library like math.js to find the maximum and minimum values, like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { min, max } <span class="hljs-keyword">from</span> <span class="hljs-string">'mathjs'</span>;

<span class="hljs-keyword">const</span> maxValue = max(...data); <span class="hljs-comment">// Returns 1000</span>
<span class="hljs-keyword">const</span> minValue = min(...data); <span class="hljs-comment">// Returns 17</span>
</code></pre>
<p>You can also decide to find the maximum and minimum values by yourself. You can do this using the <code>array.sort</code> method and picking the first and last items in the list as your minimum and maximum values, respectively. Or you can also do this by using a loop and keeping track of the maximum and minimum values.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> sortedData = data.sort(<span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> a - b);

<span class="hljs-keyword">const</span> min = sortedData[<span class="hljs-number">0</span>]; <span class="hljs-comment">// Returns 17</span>
<span class="hljs-keyword">const</span> max = sortedData[sortedData.length - <span class="hljs-number">1</span>]; <span class="hljs-comment">// Returns 1000</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> min, max;

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> datum <span class="hljs-keyword">of</span> data) {
    <span class="hljs-keyword">if</span> (!min || !max) {
        min = datum;
        max = datum;
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (datum &lt; min) min = datum;
    <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (datum &gt; max) max = datum;
}
</code></pre>
<h2 id="heading-how-to-find-the-sum-with-javascript">How to Find the Sum with JavaScript</h2>
<p>The sum, or total, is the result of the addition of a sequence of numbers. In the section explaining average above, we saw a way to get the sum of a sequence using <code>array.reduce</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> sum = data.reduce(<span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> a + b); <span class="hljs-comment">// Returns 55235</span>
</code></pre>
<p>Another very easy way would be to use the <code>sum</code> method of math.js.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { sum } <span class="hljs-keyword">from</span> <span class="hljs-string">'mathjs'</span>;

<span class="hljs-keyword">const</span> sumValue = sum(...data); <span class="hljs-comment">// Returns 55235</span>
</code></pre>
<p>You can also find the sum using a loop if you like.</p>
<h2 id="heading-how-to-find-the-mode-with-javascript">How to Find the Mode with JavaScript</h2>
<p>The mode of a dataset represents the value that appears the greatest number of times in the set. If you're analyzing that dataset, it's the value that you're most likely to find.</p>
<p>You can find the most occurring element of an array by iterating over the array, using an object to map each value to its count, and looping over this object at the end to find the highest value.</p>
<p>To make this easier to illustrate, modify the <code>data</code> array that we've used so far, like this:</p>
<pre><code class="lang-javascript">data[<span class="hljs-number">99</span>] = <span class="hljs-number">33</span>;
</code></pre>
<p>Now, you can find the mode like so:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> frequency = {};

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> datum <span class="hljs-keyword">of</span> data) {
    <span class="hljs-keyword">if</span> (frequency[datum]) frequency[datum] += <span class="hljs-number">1</span>;
    <span class="hljs-keyword">else</span> frequency[datum] = <span class="hljs-number">1</span>;
}

<span class="hljs-keyword">let</span> highestFrequency = <span class="hljs-number">0</span>;
<span class="hljs-keyword">let</span> modeValue = <span class="hljs-number">0</span>; 

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> datum <span class="hljs-keyword">in</span> frequency) {
    <span class="hljs-keyword">if</span> (frequency[datum] &gt; highestFrequency) {
        highestFrequency = frequency[datum];
        modeValue = datum;
    }
}
</code></pre>
<p>You can make this a function if you ever need to do it more than once.</p>
<p>You can find the mode more easily by using the <code>mode</code> method of the math.js library:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> modeValue = mode(...data); <span class="hljs-comment">// Returns 33</span>
</code></pre>
<h2 id="heading-how-to-find-the-median-with-javascript">How to Find the Median with JavaScript</h2>
<p>If you want to find the median of a dataset, you just need to find the value in the exact middle of the set. This means that the data has to be ordered, or sorted in ascending or descending order – otherwise the middle value has no significance.</p>
<p>You can find the median by sorting the array first, then selecting the item in the middle position if the array has an odd number of elements. If the array has an even number of elements, you select the two items in the middle and find their average.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> sortedArray = data.sort(<span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> a - b);

<span class="hljs-keyword">const</span> middlePosition = <span class="hljs-built_in">Math</span>.floor(data.length / <span class="hljs-number">2</span>);

<span class="hljs-keyword">const</span> median = data.length % <span class="hljs-number">2</span> == <span class="hljs-number">0</span> ? (sortedArray[middlePosition] + sortedArray[middlePosition - <span class="hljs-number">1</span>]) / <span class="hljs-number">2</span> : sortedArray[middlePosition]; <span class="hljs-comment">// Returns 597.5</span>
</code></pre>
<p>Alternatively, you can find the median by using the <code>median</code> method on math.js.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { median } <span class="hljs-keyword">from</span> <span class="hljs-string">'mathjs'</span>;

<span class="hljs-keyword">const</span> medianValue = median(...data); <span class="hljs-comment">// Returns 597.6</span>
</code></pre>
<h2 id="heading-summary"><strong>Summary</strong></h2>
<p>I hope you now understand how to perform these basic Data Analysis functions using JavaScript. The math.js library is one of the many JavaScript libraries that contain multiple helpful functions to make Data Analysis very easy with JavaScript.</p>
<p>If you have any questions or relevant advice, please get in touch with me to share them.</p>
<p>To read more of my articles or follow my work, you can connect with me on <a target="_blank" href="https://www.linkedin.com/in/idris-aweda-zubair-5433121a3/">LinkedIn</a>, <a target="_blank" href="https://twitter.com/AwedaIdris">Twitter</a>, and <a target="_blank" href="https://github.com/Zubs">Github</a>. It’s quick, it’s easy, and it’s free!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ SQL Joins – LEFT Join, RIGHT Join, and INNER Join Explained ]]>
                </title>
                <description>
                    <![CDATA[ SQL is a programming language we use to interact with relational databases. SQL databases contain tables, which contain rows of data. These tables usually contain similar or related data. In an office management web application database, you would ha... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/understanding-sql-joins/</link>
                <guid isPermaLink="false">66c4c6b199f22436b71945e1</guid>
                
                    <category>
                        <![CDATA[ database ]]>
                    </category>
                
                    <category>
                        <![CDATA[ SQL ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Zubair Idris Aweda ]]>
                </dc:creator>
                <pubDate>Tue, 10 Jan 2023 18:23:24 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/01/JOIN-s.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>SQL is a programming language we use to interact with relational databases. SQL databases contain tables, which contain rows of data. These tables usually contain similar or related data.</p>
<p>In an office management web application database, you would have tables for <code>employees</code>, their <code>departments</code>, their <code>managers</code>, the <code>projects</code> they work on, and so on depending on the structure of your application. </p>
<p>In the <code>employees</code> table, you would find data like the employee ID, name, salary, department ID (used to link the employee to the department), and other fields that match your needs. The other tables would also contain data for their specific entities.</p>
<h2 id="heading-what-are-joins"><strong>What Are Joins?</strong></h2>
<p>If you ever need to bring multiple tables in your database together to access the data, you use a JOIN.</p>
<p>Joins let you fetch data that is scattered across tables. For example, using the database tables that we'll create in a moment, we'll be able to get all the details of an employee, along with their manager name, and department they're working in by using a join. </p>
<p>A join lets you use a single query to achieve this. You use a join because you can only get this data by bringing data from the <code>employees</code> table, <code>departments</code> table, and <code>projects</code> table together. In simple terms, you would be JOIN-ing these tables together.</p>
<p> To perform a join, you use the <strong>JOIN</strong> keyword. And we'll see how it works in this tutorial.</p>
<h3 id="heading-prerequisites">Prerequisites:</h3>
<p>To continue with this tutorial, you should know the basics of insertion and retrieval operations with SQL.</p>
<p>Also, you can setup a demo database that we'll use for this article. The database should have tables like this: </p>
<pre><code class="lang-sql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> employees (
    <span class="hljs-keyword">id</span> <span class="hljs-built_in">int</span>,
    emp_name <span class="hljs-built_in">varchar</span>(<span class="hljs-number">100</span>),
    salary <span class="hljs-built_in">int</span>,
    dept_id <span class="hljs-built_in">int</span>,
    manager_id <span class="hljs-built_in">int</span>
);

<span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span> employees 
<span class="hljs-keyword">VALUES</span> (<span class="hljs-number">1</span>, <span class="hljs-string">'Idris'</span>, <span class="hljs-number">1000</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>), (<span class="hljs-number">2</span>, <span class="hljs-string">'Aweda'</span>, <span class="hljs-number">2000</span>, <span class="hljs-number">2</span>, <span class="hljs-number">2</span>), (<span class="hljs-number">3</span>, <span class="hljs-string">'Zubair'</span>, <span class="hljs-number">3000</span>, <span class="hljs-number">3</span>, <span class="hljs-number">2</span>), (<span class="hljs-number">4</span>, <span class="hljs-string">'Young'</span>, <span class="hljs-number">4000</span>, <span class="hljs-number">3</span>, <span class="hljs-number">3</span>), (<span class="hljs-number">5</span>, <span class="hljs-string">'Babu'</span>, <span class="hljs-number">5000</span>, <span class="hljs-number">1</span>, <span class="hljs-number">3</span>), (<span class="hljs-number">6</span>, <span class="hljs-string">'John'</span>, <span class="hljs-number">1000</span>, <span class="hljs-number">8</span>, <span class="hljs-number">1</span>);

<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> departments (
    <span class="hljs-keyword">id</span> <span class="hljs-built_in">int</span>,
    dept_name <span class="hljs-built_in">varchar</span>(<span class="hljs-number">100</span>)
);

<span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span> departments
<span class="hljs-keyword">VALUES</span> (<span class="hljs-number">1</span>, <span class="hljs-string">'Engineering'</span>), (<span class="hljs-number">2</span>, <span class="hljs-string">'Product'</span>), (<span class="hljs-number">3</span>, <span class="hljs-string">'Marketing'</span>), (<span class="hljs-number">4</span>, <span class="hljs-string">'Support'</span>);

<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> managers (
    <span class="hljs-keyword">id</span> <span class="hljs-built_in">int</span>,
    manager_name <span class="hljs-built_in">varchar</span>(<span class="hljs-number">100</span>),
    dept_id <span class="hljs-built_in">int</span>
);

<span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span> managers
<span class="hljs-keyword">VALUES</span> (<span class="hljs-number">1</span>, <span class="hljs-string">'Doe'</span>, <span class="hljs-number">1</span>), (<span class="hljs-number">2</span>, <span class="hljs-string">'Jane'</span>, <span class="hljs-number">2</span>), (<span class="hljs-number">3</span>, <span class="hljs-string">'May'</span>, <span class="hljs-number">4</span>);

<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> projects (
    <span class="hljs-keyword">id</span> <span class="hljs-built_in">int</span>,
    project_name <span class="hljs-built_in">varchar</span>(<span class="hljs-number">100</span>),
    emp_id <span class="hljs-built_in">int</span>
);

<span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span> projects
<span class="hljs-keyword">VALUES</span> (<span class="hljs-number">1</span>, <span class="hljs-string">'Fintech App'</span>, <span class="hljs-number">1</span>), (<span class="hljs-number">1</span>, <span class="hljs-string">'Fintech App'</span>, <span class="hljs-number">5</span>), (<span class="hljs-number">1</span>, <span class="hljs-string">'Fintech App'</span>, <span class="hljs-number">6</span>), (<span class="hljs-number">2</span>, <span class="hljs-string">'Cooking Website'</span>, <span class="hljs-number">1</span>), (<span class="hljs-number">2</span>, <span class="hljs-string">'Cooking Website'</span>, <span class="hljs-number">2</span>);
</code></pre>
<h2 id="heading-how-to-use-an-inner-join-in-sql"><strong>How to Use an Inner Join in SQL</strong></h2>
<p>There are many types of joins in SQL, and each one has a different purpose.</p>
<p>The inner join is the most basic type of join. It is so basic that sometimes, you can omit the JOIN keyword and still perform an inner join. </p>
<p>For example, say you want to fetch the name of all employees in the organanization, along with the name of their departments. In a situation like this, you need data from both the <code>employees</code> table and the <code>departments</code> table. A simple join like this would do:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> e.emp_name, d.dept_name 
<span class="hljs-keyword">FROM</span> employees e, departments d 
<span class="hljs-keyword">WHERE</span> e.dept_id = d.id;
</code></pre>
<p>So how does this actually work? To start with, take a look at the <code>FROM</code> part of the query:</p>
<pre><code class="lang-sql">FROM employees e, departments d
</code></pre>
<p>Here, data is being fetched from more than one table, and each table is aliased. The alias is very useful for scenarios where both tables have similarly named fields,  like the <code>id</code> field both tables have in this case. You would be able to access the different fields easily using the short alias created.</p>
<p>Next, in the <code>SELECT</code> part of the query, we also specify the columns we want (and we use the alias to tell which table each value comes from):  </p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> e.emp_name, d.dept_name
</code></pre>
<p>And finally, to ensure only correct values are matched to each other, the <code>WHERE</code> part of the query specifies the conditions that have to be met for the data to be joined.</p>
<pre><code class="lang-sql">WHERE e.dept_id = d.id;
</code></pre>
<p>So for the first employee, the <code>dept_id</code> is <code>1</code>, so we fetch the department with <code>id = 1</code>, and it's name is returned. This happens for as many rows as there are in the employees table.</p>
<p>The result of the query looks like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/Screenshot-2023-01-07-at-15.45.09.png" alt="Image" width="600" height="400" loading="lazy">
<em>Result of JOIN query</em></p>
<p>Here, notice that the number of employees returned is smaller than the number of employees that actually exist. This is because when you use an INNER JOIN, <em>you only get records that exist in both tables</em>. </p>
<p>That is, the employee with <code>id = 6</code> that was not returned has a <code>dept_it = 8</code>. Now, this department isn't in the <code>departments</code> table, so it wasn't returned.</p>
<p>Another way to achieve this same result would be to actually spell out the JOIN like this:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> e.emp_name, d.dept_name
<span class="hljs-keyword">FROM</span> employees e
<span class="hljs-keyword">JOIN</span> departments d
<span class="hljs-keyword">ON</span> (e.dept_id = d.id);
</code></pre>
<p>Or use the INNER JOIN like this:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> e.emp_name, d.dept_name
<span class="hljs-keyword">FROM</span> employees e
<span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> departments d
<span class="hljs-keyword">ON</span> (e.dept_id = d.id);
</code></pre>
<p>These queries return exactly the same result as the first one. But they are more readable as they're explicit. </p>
<p>In these queries, you're selecting from the <code>employees</code> table, then joining the <code>departments</code> table to the result. The ON in the query is used to specify the conditions on which to JOIN. It's the same as the WHERE condition in the first query.</p>
<h3 id="heading-inner-join-use-case">INNER JOIN Use Case</h3>
<p>In real applications, you use an INNER JOIN when only records that exist in both tables matter. </p>
<p>For example, in an inventory management application, you could have a table for <code>sales</code>, and another for <code>products</code>. Now, the <code>sales</code> table will contain <code>product_id</code> (a reference to the sold product), along with other details like <code>sold_at</code> (when the product was sold) and maybe customer details. </p>
<p>The <code>products</code> table, on the other hand, will have the <code>name</code>, <code>price</code>, and maybe the <code>quantity</code> of every product. </p>
<p>Now say it's end of the week and you need to do a sales report. You would need to fetch all <code>sales</code> records, along with the product name and price to display on a dashboard or export as a CSV of some sort. </p>
<p>To do this, you would use an INNER JOIN of the <code>products</code> table on the <code>sales</code> table, because you do not care about products that were not sold – you only want to see every sale that was made, and the name and price of the product that was sold. Every other product will be exempted from this report.</p>
<h2 id="heading-how-to-use-a-left-join-in-sql"><strong>How to Use a Left Join in SQL</strong></h2>
<p>In another scenario, you might want to fetch all the employee names and their department names, but this time without leaving any employee or department name out. Here, you'd you use a LEFT JOIN. </p>
<p>In a LEFT JOIN, <em>every record from the table on the left, the base table, will be returned</em>. Then values from the right table, the table being joined, will be added where they exist.</p>
<p>The LEFT JOIN is also known as LEFT OUTER JOIN and you can use them interchangeably.</p>
<p>So to fetch all employee and department names, you can modify the previous query to use LEFT JOIN, like this:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> e.emp_name, d.dept_name
<span class="hljs-keyword">FROM</span> employees e
<span class="hljs-keyword">LEFT</span> <span class="hljs-keyword">JOIN</span> departments d
<span class="hljs-keyword">ON</span> (e.dept_id = d.id);
</code></pre>
<p>The result of this query looks like this now:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/Screenshot-2023-01-07-at-15.55.10.png" alt="Image" width="600" height="400" loading="lazy">
<em>Result of LEFT JOIN</em></p>
<p>Now, employee with <code>id = 6</code> and <code>dept_id = 8</code> is returned, with the department name being set as NULL because there is no department with <code>id = 8</code>.</p>
<h3 id="heading-left-join-use-case">LEFT JOIN Use Case</h3>
<p>In real applications, you use a LEFT JOIN when there's a primary, always existing entity that can be related to another entity that doesn't always exist. </p>
<p>An easy use case would be in a multi-vendor ecommerce application where after a user signs up, they can set up a store and add products to the store. </p>
<p>A user, on signing up, doesn't automatically have a store until they create it. So if you try to view all users, with their store details, you would use a LEFT JOIN of the <code>stores</code> table on the <code>users</code> table. This is because every record in the <code>users</code> table is important, store or no store. </p>
<p>When the user has a store set up, the store details are returned, and if otherwise, NULL is returned. But, you wouldn't be losing any existing data.</p>
<h2 id="heading-how-to-use-a-right-join-in-sql"><strong>How to Use a Right Join in SQL</strong></h2>
<p>The RIGHT JOIN works like the opposite of the LEFT JOIN. In a RIGHT JOIN, every record from the table on the right, the table being joined, will be returned. Then values from the left table, the base table, will be added where they exist.</p>
<p>The RIGHT JOIN is also known as the RIGHT OUTER JOIN and you can use them interchangeably.</p>
<p>An example would be to modify the previous query to use a RIGHT JOIN instead of a LEFT JOIN, like this:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> e.emp_name, d.dept_name
<span class="hljs-keyword">FROM</span> employees e
<span class="hljs-keyword">RIGHT</span> <span class="hljs-keyword">JOIN</span> departments d
<span class="hljs-keyword">ON</span> (e.dept_id = d.id);
</code></pre>
<p>Now, your result looks like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/Screenshot-2023-01-07-at-16.02.08.png" alt="Image" width="600" height="400" loading="lazy">
<em>Result of RIGHT JOIN</em></p>
<p>Now, every department in the <code>departments</code> table was returned. And employees in those departments were returned too. For the last row, there is no employee with <code>dept_id = 4</code>, which is why the NULL value gets returned.</p>
<h3 id="heading-right-join-use-case">RIGHT JOIN Use Case</h3>
<p>The RIGHT JOIN works exactly as the LEFT JOIN works in real applications. The difference between them comes from the level of importance of the tables to be joined. </p>
<p>The LEFT JOIN is more commonly used because you very likely will write your query from left to right, listing tables in that order of importance too. Otherwise, the RIGHT JOIN works exactly as the LEFT JOIN.</p>
<h3 id="heading-how-to-combine-joins-in-sql">How to Combine JOINS in SQL</h3>
<p>So far, we've only joined one table to another. But, you can actually join as many tables as you like by using any or all of these joins together as you like. </p>
<p>For example, say you want to fetch the names of all employees, with their department names, manager names, and projects names. You would have to join the <code>employees</code> table to the <code>departments</code> table, the <code>managers</code> table, and the <code>projects</code> table. You can achieve this using this query:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> e.emp_name, d.dept_name, m.manager_name, p.project_name
<span class="hljs-keyword">FROM</span> employees e
<span class="hljs-keyword">LEFT</span> <span class="hljs-keyword">JOIN</span> departments d
<span class="hljs-keyword">ON</span> (e.dept_id = d.id)
<span class="hljs-keyword">LEFT</span> <span class="hljs-keyword">JOIN</span> managers m
<span class="hljs-keyword">ON</span> (e.manager_id = m.id)
<span class="hljs-keyword">LEFT</span> <span class="hljs-keyword">JOIN</span> projects p
<span class="hljs-keyword">ON</span> (e.id = p.emp_id);
</code></pre>
<p>In this query, start from the <code>employees</code> table as a base table. Then you LEFT JOIN the <code>departments</code> table. You also LEFT JOIN the <code>managers</code> table, and finally, the <code>projects</code> table.</p>
<p>The result of this query will look like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/Screenshot-2023-01-07-at-19.30.29.png" alt="Image" width="600" height="400" loading="lazy">
<em>Result of general JOIN query</em></p>
<p>The reason for using a LEFT JOIN here is because you have to fetch ALL employees. You could use an INNER JOIN in place of the LEFT JOIN in the <code>managers</code> table because all employees have a <code>manager_id</code> that actually exists in the <code>managers</code> table. But to be safe, you can just use the LEFT JOIN.</p>
<h2 id="heading-how-to-use-a-cross-join-in-sql"><strong>How to Use a Cross Join in SQL</strong></h2>
<p>This is also known as a CARTESIAN JOIN. It returns every record from both tables in a multiplication-like manner. It returns every possible combination of rows from both tables. It doesn't need a JOIN condition like the other JOINs. </p>
<p>For example, if you do a CROSS JOIN between tables <code>employees</code> and <code>departments</code>, your result will look like this:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> e.emp_name, d.dept_name
<span class="hljs-keyword">FROM</span> employees e
<span class="hljs-keyword">CROSS</span> <span class="hljs-keyword">JOIN</span> departments d;
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/Screenshot-2023-01-07-at-20.19.24.png" alt="Image" width="600" height="400" loading="lazy">
<em>CROSS JOIN of <code>employees</code> and <code>departments</code> tables.</em></p>
<p>Here you have 24 rows, which is a product of the number of rows in the <code>employees</code> table, 6, and the number of rows in the <code>departments</code> table, 4. The records were returned so that for every record in the <code>employees</code> table, it is mapped to a record in the <code>departments</code> table.</p>
<h3 id="heading-cross-join-use-case">CROSS JOIN Use Case</h3>
<p>A common use case of CROSS JOIN would be in an ecommerce application where it is possible to have size or color variations of all products. If you ever need to fetch a list of all products in different sizes, like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/Screenshot-2023-01-10-at-13.13.55.png" alt="Image" width="600" height="400" loading="lazy">
<em>Result of a basic CROSS JOIN</em></p>
<p>This result was gotten from CROSS JOINing a <code>sizes</code> table that contains an <code>id</code> for each size, a string <code>size</code> that can be either 'Small', 'Medium', or 'Large' and another field called <code>ratio</code> to affect how this size affects the product price. So, for every product, it is mapped to a size, and the price is calculated.</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> 
  p.product_name, 
  <span class="hljs-keyword">ROUND</span>(p.price * s.ratio, <span class="hljs-number">2</span>) <span class="hljs-keyword">as</span> price, 
  s.size 
<span class="hljs-keyword">FROM</span> products p 
<span class="hljs-keyword">CROSS</span> <span class="hljs-keyword">JOIN</span> <span class="hljs-keyword">sizes</span> s;
</code></pre>
<h2 id="heading-how-to-use-a-self-join-in-sql"><strong>How to Use a Self Join in SQL</strong></h2>
<p>As the name implies, is when you try <em>to join a table to itself.</em> There is no self JOIN keyword.</p>
<p>Take this new <code>categories</code> table, for example. This table contains both main categories and sub-categories. If you ever have to fetch the categories and their sub-categories, you can use a SELF JOIN.</p>
<pre><code class="lang-sql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> categories (
    <span class="hljs-keyword">id</span> <span class="hljs-built_in">int</span>,
    cat_name <span class="hljs-built_in">varchar</span>(<span class="hljs-number">100</span>),
    parent_category_id <span class="hljs-built_in">int</span> <span class="hljs-keyword">DEFAULT</span> <span class="hljs-literal">NULL</span>
);

<span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span> categories 
<span class="hljs-keyword">VALUES</span> (<span class="hljs-number">1</span>, <span class="hljs-string">'Ladies'</span>, <span class="hljs-literal">NULL</span>), (<span class="hljs-number">2</span>, <span class="hljs-string">'Mens'</span>, <span class="hljs-literal">NULL</span>), (<span class="hljs-number">3</span>, <span class="hljs-string">'Lingeries'</span>, <span class="hljs-number">1</span>), (<span class="hljs-number">4</span>, <span class="hljs-string">'Shoes'</span>, <span class="hljs-number">2</span>);
</code></pre>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> cat.cat_name, parent_cat.cat_name <span class="hljs-keyword">AS</span> <span class="hljs-keyword">parent</span> 
<span class="hljs-keyword">FROM</span> categories cat
<span class="hljs-keyword">JOIN</span> categories parent_cat 
<span class="hljs-keyword">ON</span> cat.parent_category_id = parent_cat.id;
</code></pre>
<p>Here, see how the table was referenced twice. Be careful with the alias as it's important in differentiating both instances. The result of this query looks like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/Screenshot-2023-01-07-at-21.40.25.png" alt="Image" width="600" height="400" loading="lazy">
<em>Result of simple Self JOIN on <code>categories</code> table</em></p>
<h3 id="heading-self-join-use-case">SELF JOIN Use Case</h3>
<p>In many applications, you find hierarchical data stored in a single table. Like the category and sub-category as shown in the previous example. Or as in employee and manager, because they're both employees of the company. </p>
<p>In case of the latter, the table will have fields such as <code>id</code>, <code>name</code>, <code>manager_id</code> (this is basically the <code>id</code> of another employee). Let's say you want to write a query where you have to fetch a list of managers and the number of their employees. Given that these managers are also employees, you only have one table to fetch from, the <code>employees</code> table. To do this fetch, do a SELF JOIN of the <code>employees</code> table on the <code>employees</code> table like this:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> e2.name <span class="hljs-keyword">AS</span> supervisor, <span class="hljs-keyword">COUNT</span>(e1.name) <span class="hljs-keyword">AS</span> number_of_employees
<span class="hljs-keyword">FROM</span> employee e1
<span class="hljs-keyword">JOIN</span> employee e2
<span class="hljs-keyword">ON</span> e1.manager_id = e2.id
<span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span> e2.name;
</code></pre>
<p>This would correctly return the managers and the number of employees working under them.</p>
<h2 id="heading-summary"><strong>Summary</strong></h2>
<p>I hope you now understand SQL JOINs, the different types, and when to use them so you can write better queries. </p>
<p>All the JOINs here work with MySQL. There are other JOINs like FULL OUTER JOIN and NATURAL JOIN that we didn't discuss, but you can look into them yourself if you like.</p>
<p>If you have any questions or relevant advice, please get in touch with me to share them.</p>
<p>To read more of my articles or follow my work, you can connect with me on <a target="_blank" href="https://www.linkedin.com/in/idris-aweda-zubair-5433121a3/">LinkedIn</a>, <a target="_blank" href="https://twitter.com/AwedaIdris">Twitter</a>, and <a target="_blank" href="https://github.com/Zubs">Github</a>. It’s quick, it’s easy, and it’s free!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Migrate a Database in PHP Using Phinx ]]>
                </title>
                <description>
                    <![CDATA[ Building modern web applications usually involves a lot of data. Managing these data (databases) during development and production can be a lot.  This is especially true if there's more than one developer, and multiple environments where changes have... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/easy-database-migrations-in-php-using-phinx/</link>
                <guid isPermaLink="false">66c4c6964173ed342943d0ac</guid>
                
                    <category>
                        <![CDATA[ data migration ]]>
                    </category>
                
                    <category>
                        <![CDATA[ database ]]>
                    </category>
                
                    <category>
                        <![CDATA[ PHP ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Zubair Idris Aweda ]]>
                </dc:creator>
                <pubDate>Wed, 30 Mar 2022 23:59:31 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/03/0-ddWHLcHqIojSq_GO.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Building modern web applications usually involves a lot of data. Managing these data (databases) during development and production can be a lot. </p>
<p>This is especially true if there's more than one developer, and multiple environments where changes have to be manually implemented.</p>
<p>Database migrations help developers manage these changes easily, across multiple environments and developers. </p>
<p>This article explains:</p>
<ul>
<li>What database migrations are.</li>
<li>How to get started with database migrations in PHP using Phinx.</li>
<li>How to manage tables in your database.</li>
</ul>
<p>This article is meant for readers with basic PHP knowledge. It will help you learn to easily (and better) manage your databases.</p>
<h2 id="heading-what-are-database-migrations">What Are Database Migrations?</h2>
<p>In basic terms, migrations contain changes that you wish to make to your database. These changes could be creating or dropping a table, adding or removing some field(s) from a table, changing column types, and many more. </p>
<p>These files make it easy to make these same changes across multiple systems as anyone with the files can just run them, and have their database updated.</p>
<p>So in a real life scenario, some developer on the team could make a change to the <em>users</em> table to allow the <em>gender</em> field to accept more than the default <em>male</em> and <em>female</em> options, maybe a third <em>other</em> option. </p>
<p>After making this change, the developer creates a migration. This migration includes changes that they have made to the database – in this case a change to a column on a table – and other developers can easily get this change to their own local databases by running the migrations.</p>
<blockquote>
<p>Migrations are like version control for your database, allowing your team to define and share the application's database schema definition. If you have ever had to tell a teammate to manually add a column to their local database schema after pulling in your changes from source control, you've faced the problem that database migrations solve. - <a target="_blank" href="https://laravel.com/docs/9.x/">Laravel</a></p>
</blockquote>
<p>Many popular web frameworks already have support for migrations built in. But in this article, we explore using migrations in vanilla PHP.</p>
<p>Learn more about database migrations <a target="_blank" href="https://www.cloudbees.com/blog/database-migration">here</a>.</p>
<h2 id="heading-what-is-phinx">What Is Phinx?</h2>
<blockquote>
<p>Phinx is a PHP library that makes it ridiculously easy to manage the database migrations for your PHP app. - Phinx</p>
</blockquote>
<p>Phinx makes it possible to manage migrations easily regardless of whether you're using a PHP framework or not. It is also very easy to install (as we will see later on). </p>
<p>It ships with a couple of commands to make operations easier. It is fully customisable (you can do whatever you want with it 🙃). It also works in multiple environments, meaning you can have some production migrations, testing migrations, and dev migrations.</p>
<h2 id="heading-phinx-installation">Phinx Installation</h2>
<p>You can add Phinx to any PHP project using composer.</p>
<pre><code class="lang-bash">$ mkdir php-migrations
$ <span class="hljs-built_in">cd</span> php-migrations
$ composer init
</code></pre>
<p>The first command creates a folder in your current directory, <code>php-migrations</code>, and the second command moves into it. The last command starts an interactive shell.</p>
<p>Follow the prompt, filling in the details as required (the default values are fine). You can set the project description, author name (or contributors' names), minimum stability for dependencies, project type, license, and define your dependencies.</p>
<p>When you get to the dependencies part, install the <code>robmorgan/phinx</code> <em>phinx</em> package as a dependency.</p>
<p>Accept the other defaults and proceed to generating the <code>composer.json</code> file. The generated file should look like this currently:</p>
<pre><code class="lang-php">{
    <span class="hljs-string">"name"</span>: <span class="hljs-string">"zubair/php-migrations"</span>,
    <span class="hljs-string">"description"</span>: <span class="hljs-string">"A simple tutorial on how to use and manage migrations in PHP applications."</span>,
    <span class="hljs-string">"type"</span>: <span class="hljs-string">"project"</span>,
    <span class="hljs-string">"require"</span>: {
        <span class="hljs-string">"robmorgan/phinx"</span>: <span class="hljs-string">"^0.12.10"</span>
    },
    <span class="hljs-string">"license"</span>: <span class="hljs-string">"ISC"</span>,
    <span class="hljs-string">"autoload"</span>: {
        <span class="hljs-string">"psr-4"</span>: {
            <span class="hljs-string">"Zubs\\"</span>: <span class="hljs-string">"src/"</span>
        }
    },
    <span class="hljs-string">"authors"</span>: [
        {
            <span class="hljs-string">"name"</span>: <span class="hljs-string">"Zubs"</span>,
            <span class="hljs-string">"email"</span>: <span class="hljs-string">"zubairidrisaweda@gmail.com"</span>
        }
    ]
}
</code></pre>
<h2 id="heading-init-phinx">Init Phinx</h2>
<p>After installing Phinx, you need to initialise it. You can do this very easily using its binary installed in the <code>vendor</code> folder.</p>
<pre><code class="lang-bash">$ ./vendor/bin/phinx init
</code></pre>
<p>This creates phinx's configuration file as a PHP file. It could be created as a JSON file too. I prefer JSON for configurations, so I will use the JSON format.</p>
<pre><code class="lang-bash">$ ./vendor/bin/phinx init --format=json
</code></pre>
<p>Here's what the default configuration file looks like:</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"paths"</span>: {
        <span class="hljs-attr">"migrations"</span>: <span class="hljs-string">"%%PHINX_CONFIG_DIR%%/db/migrations"</span>,
        <span class="hljs-attr">"seeds"</span>: <span class="hljs-string">"%%PHINX_CONFIG_DIR%%/db/seeds"</span>
    },
    <span class="hljs-attr">"environments"</span>: {
        <span class="hljs-attr">"default_migration_table"</span>: <span class="hljs-string">"phinxlog"</span>,
        <span class="hljs-attr">"default_environment"</span>: <span class="hljs-string">"development"</span>,
        <span class="hljs-attr">"production"</span>: {
            <span class="hljs-attr">"adapter"</span>: <span class="hljs-string">"mysql"</span>,
            <span class="hljs-attr">"host"</span>: <span class="hljs-string">"localhost"</span>,
            <span class="hljs-attr">"name"</span>: <span class="hljs-string">"production_db"</span>,
            <span class="hljs-attr">"user"</span>: <span class="hljs-string">"root"</span>,
            <span class="hljs-attr">"pass"</span>: <span class="hljs-string">""</span>,
            <span class="hljs-attr">"port"</span>: <span class="hljs-number">3306</span>,
            <span class="hljs-attr">"charset"</span>: <span class="hljs-string">"utf8"</span>
        },
        <span class="hljs-attr">"development"</span>: {
            <span class="hljs-attr">"adapter"</span>: <span class="hljs-string">"mysql"</span>,
            <span class="hljs-attr">"host"</span>: <span class="hljs-string">"localhost"</span>,
            <span class="hljs-attr">"name"</span>: <span class="hljs-string">"development_db"</span>,
            <span class="hljs-attr">"user"</span>: <span class="hljs-string">"root"</span>,
            <span class="hljs-attr">"pass"</span>: <span class="hljs-string">""</span>,
            <span class="hljs-attr">"port"</span>: <span class="hljs-number">3306</span>,
            <span class="hljs-attr">"charset"</span>: <span class="hljs-string">"utf8"</span>
        },
        <span class="hljs-attr">"testing"</span>: {
            <span class="hljs-attr">"adapter"</span>: <span class="hljs-string">"mysql"</span>,
            <span class="hljs-attr">"host"</span>: <span class="hljs-string">"localhost"</span>,
            <span class="hljs-attr">"name"</span>: <span class="hljs-string">"testing_db"</span>,
            <span class="hljs-attr">"user"</span>: <span class="hljs-string">"root"</span>,
            <span class="hljs-attr">"pass"</span>: <span class="hljs-string">""</span>,
            <span class="hljs-attr">"port"</span>: <span class="hljs-number">3306</span>,
            <span class="hljs-attr">"charset"</span>: <span class="hljs-string">"utf8"</span>
        }
    },
    <span class="hljs-attr">"version_order"</span>: <span class="hljs-string">"creation"</span>
}
</code></pre>
<p>In this configuration file, notice how Phinx expects that you have a <code>db/migrations</code> path (for your migrations) by default. You can change this if you want, but I think it's fine and I'll be keeping it.</p>
<pre><code class="lang-bash">$ mkdir db &amp;&amp; db/migrations
</code></pre>
<p>You can read more about these configurations in the <a target="_blank" href="https://book.cakephp.org/phinx/0/en/configuration.html">official documentation</a>.</p>
<p>Phinx also ships with commands for different actions to make it easier to use in our projects.</p>
<h2 id="heading-how-to-create-a-migration">How to Create A Migration</h2>
<p>Phinx uses classes for its migrations. To create a new migration (say, one to create a <em>posts</em> table), use the <code>create</code> command with the name of the migration.</p>
<pre><code class="lang-bash">$ ./vendor/bin/phinx create PostsTableMigration
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/03/Screenshot-2022-03-28-at-13.22.17.png" alt="Image" width="600" height="400" loading="lazy">
<em>Creating A Migration</em></p>
<p>This creates a <code>20220328122134_posts_table_migration.php</code> file in the <code>db/migrations</code> directory created earlier. This file is named using the <code>YYYYMMDDHHMMSS_my_new_migration.php</code> format. In this format, the first 14 characters, <em>YYYYMMDDHHMMSS</em>, are representations of the current timestamp.</p>
<p>The <code>20220328122134_posts_table_migration.php</code> looks like this currently:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>
<span class="hljs-keyword">declare</span>(strict_types=<span class="hljs-number">1</span>);

<span class="hljs-keyword">use</span> <span class="hljs-title">Phinx</span>\<span class="hljs-title">Migration</span>\<span class="hljs-title">AbstractMigration</span>;

<span class="hljs-keyword">final</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PostsTableMigration</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">AbstractMigration</span>
</span>{
    <span class="hljs-comment">/**
     * Change Method.
     *
     * Write your reversible migrations using this method.
     *
     * More information on writing migrations is available here:
     * https://book.cakephp.org/phinx/0/en/migrations.html#the-change-method
     *
     * Remember to call "create()" or "update()" and NOT "save()" when working
     * with the Table class.
     */</span>
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">change</span>(<span class="hljs-params"></span>): <span class="hljs-title">void</span>
    </span>{

    }
}
</code></pre>
<p>This file (and all other migrations created using Phinx) extends the <code>Phinx\Migration\AbstractMigration</code> class. This class has all the methods you need to interact with your database.</p>
<p>This migration file also includes a <code>change</code> method. This method was introduced recently to Phinx in version 0.2.0 to implements Phinx's idea of reversible migrations. </p>
<p>These are migration files with just one method, <em>change,</em> that contains logic for performing some action, leaving Phinx to figure out how to reverse it. Rather than the traditional use of two methods, <em>up</em> and <em>down</em>, to create and reverse actions.</p>
<blockquote>
<p>Phinx still allows you use <em>up</em> and down methods. But it gives the change method preference over them when they are used together. It ignores them.</p>
</blockquote>
<h2 id="heading-how-to-manage-tables">How to Manage Tables</h2>
<p>Tables are the basis on which structured databases are built and are the most important part of what Phinx offers. </p>
<p>You can easily manage database tables using PHP code with Phinx. Phinx offers a powerful <code>table()</code> method. This method retrieves an instance of the <em>Table</em> object.</p>
<h3 id="heading-how-to-create-a-table">How to Create a Table</h3>
<p>Creating a table is really easy using Phinx. You create a new instance of the <em>Table</em> object using the <code>table()</code> method with the table name.</p>
<pre><code class="lang-php">$table = <span class="hljs-keyword">$this</span>-&gt;table(<span class="hljs-string">'posts'</span>);
</code></pre>
<p>Next, you can add columns with their settings.</p>
<pre><code class="lang-php">$table-&gt;addColumn(<span class="hljs-string">'title'</span>, <span class="hljs-string">'string'</span>, [<span class="hljs-string">'limit'</span> =&gt; <span class="hljs-number">20</span>])
    -&gt;addColumn(<span class="hljs-string">'body'</span>, <span class="hljs-string">'text'</span>)
    -&gt;addColumn(<span class="hljs-string">'cover_image'</span>, <span class="hljs-string">'string'</span>)
    -&gt;addTimestamps()
    -&gt;addIndex([<span class="hljs-string">'title'</span>], [<span class="hljs-string">'unique'</span> =&gt; <span class="hljs-literal">true</span>]);
</code></pre>
<p>Here, I've created columns <code>title</code>, <code>body</code>, <code>cover_image</code>, <code>created_at</code>, and <code>updated_at</code>. I also set the type of the <code>title</code> to be a <em>string</em> with 20 or fewer characters. </p>
<p>I set the <code>body</code> to be a text field, so it can hold long posts. The <code>cover_image</code> is also a <em>string</em> field that uses the default size of a string (255). </p>
<p>The <code>created_at</code> and <code>updated_at</code> fields are timestamps automatically generated in the <code>addTimestamps()</code> method. </p>
<p>Finally, I set the <code>title</code> field to be unique (as it would be in a real blog).</p>
<p>You can get all the available column types by checking the <a target="_blank" href="https://book.cakephp.org/phinx/0/en/migrations.html#valid-column-types">Valid Column Types</a>. You can also get all the available column options by checking the <a target="_blank" href="https://book.cakephp.org/phinx/0/en/migrations.html#valid-column-options">Valid Column Options</a>.</p>
<p>Finally, you can say that the database should be created by using the <code>create</code> method.</p>
<pre><code class="lang-php">$table-&gt;create();
</code></pre>
<p>In the end, your migration file's <em>change</em> method should look like this:</p>
<pre><code class="lang-php"><span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">change</span>(<span class="hljs-params"></span>): <span class="hljs-title">void</span>
</span>{
    $table = <span class="hljs-keyword">$this</span>-&gt;table(<span class="hljs-string">'posts'</span>);

    $table-&gt;addColumn(<span class="hljs-string">'title'</span>, <span class="hljs-string">'string'</span>, [<span class="hljs-string">'limit'</span> =&gt; <span class="hljs-number">20</span>])
        -&gt;addColumn(<span class="hljs-string">'body'</span>, <span class="hljs-string">'text'</span>)
        -&gt;addColumn(<span class="hljs-string">'cover_image'</span>, <span class="hljs-string">'string'</span>)
        -&gt;addTimestamps()
        -&gt;addIndex([<span class="hljs-string">'title'</span>], [<span class="hljs-string">'unique'</span> =&gt; <span class="hljs-literal">true</span>]);

     $table-&gt;create();
}
</code></pre>
<p>We can now run this migration to create our table.</p>
<h2 id="heading-how-to-run-migrations">How to Run Migrations</h2>
<p>After creating migrations, the next step is to enforce these desired changes in the database. Running migrations actually enforces these changes.</p>
<pre><code class="lang-php">$ ./vendor/bin/phinx migrate
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/03/Screenshot-2022-03-29-at-18.54.56.png" alt="Image" width="600" height="400" loading="lazy">
<em>Running a migration</em></p>
<p>This image shows the result of the migration. You can see the time taken to run the migration.</p>
<p>Now, if you check your database GUI tool, you'll notice that the <em>posts</em> table was created with an additional field, the <em>id</em> field. This field is also the primary field by default. And it also auto-increments.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/03/Screenshot-2022-03-29-at-19.00.27.png" alt="Image" width="600" height="400" loading="lazy">
<em>posts table.</em></p>
<p>You may change the primary key to some other key by either specifying some other field as the primary field, or by mapping the <em>id</em> field to the desired primary field. The latter includes the auto incrementing ability of the normal <em>id</em> field.</p>
<pre><code class="lang-php">$table = <span class="hljs-keyword">$this</span>-&gt;table(<span class="hljs-string">'posts'</span>, [
    <span class="hljs-string">'id'</span> =&gt; <span class="hljs-literal">false</span>,
    <span class="hljs-string">'primary_key'</span> =&gt; [<span class="hljs-string">'posts_key'</span>]
]);

$table = <span class="hljs-keyword">$this</span>-&gt;table(<span class="hljs-string">'posts'</span>, [
    <span class="hljs-string">'id'</span> =&gt; <span class="hljs-string">'posts_key'</span>,
]);
</code></pre>
<p>In the first method, the primary key to be used has to be a column on the table (it is not auto-created).</p>
<p>You may also set which environment you want to run the migrations. </p>
<pre><code class="lang-bash">$ ./vendor/bin/phinx migrate -e testing
</code></pre>
<h3 id="heading-how-to-reversemigrations">How to ReverseMigrations</h3>
<p>Migrations can be reversed by being <em>run down</em>. This is the reverse of migrating <em>up</em>. The table previously created will be dropped, columns added will be removed, and the database will be returned to its initial pre-migration state.</p>
<pre><code class="lang-bash">$ ./vendor/bin/phinx rollback
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/03/Screenshot-2022-03-29-at-18.56.46.png" alt="Image" width="600" height="400" loading="lazy">
<em>Reversing a migration</em></p>
<h3 id="heading-how-to-check-migration-status">How to Check Migration Status</h3>
<p>As your application size increases, it is expected that your database migrations will increase. Due to this, at some point, you may wish to check the status of your migrations, to know which have been run, and which have not.</p>
<pre><code class="lang-bash">$ ./vendor/bin/phinx status
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/03/Screenshot-2022-03-29-at-18.58.07.png" alt="Image" width="600" height="400" loading="lazy">
<em>Checking migration status</em></p>
<h3 id="heading-how-to-drop-a-table">How to Drop a Table</h3>
<p>You can easily use the <code>drop</code> method, followed by the <code>save</code> method to persist the change, on the <em>Table</em> object.</p>
<pre><code class="lang-php"><span class="hljs-keyword">$this</span>-&gt;table(<span class="hljs-string">'posts'</span>)-&gt;drop()-&gt;save();
</code></pre>
<h3 id="heading-how-to-rename-a-table">How to Rename a Table</h3>
<pre><code class="lang-php">$table = <span class="hljs-keyword">$this</span>-&gt;table(<span class="hljs-string">'posts'</span>);

$table-&gt;rename(<span class="hljs-string">'articles'</span>)
    -&gt;update();
</code></pre>
<p>To drop a table, get the table. Then use the <code>rename</code> method with the new name, followed by the <code>update</code> method to persist this change.</p>
<h3 id="heading-how-to-change-a-tables-primary-key">How to Change a Table's Primary Key</h3>
<p>You can also change a table's primary key very easily.</p>
<pre><code class="lang-php">$table = <span class="hljs-keyword">$this</span>-&gt;table(<span class="hljs-string">'posts'</span>);

$table-&gt;changePrimaryKey(<span class="hljs-string">'new_primary_key'</span>);

$table-&gt;update();
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Now you know how to set up migrations in your PHP applications.</p>
<p>If you have any questions or relevant advice, please get in touch with me to share them.</p>
<p>To read more of my articles or follow my work, you can connect with me on <a target="_blank" href="https://www.linkedin.com/in/idris-aweda-zubair-5433121a3/">LinkedIn</a>, <a target="_blank" href="https://twitter.com/AwedaIdris">Twitter</a>, and <a target="_blank" href="https://github.com/Zubs">Github</a>. It’s quick, it’s easy, and it’s free!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Test PHP Code With PHPUnit ]]>
                </title>
                <description>
                    <![CDATA[ There are many different ways to test your software application, and unit testing is an important one. So what is unit testing and how can you do it? You'll learn that and more in this article. What is Unit Testing? Unit testing is a software develo... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/test-php-code-with-phpunit/</link>
                <guid isPermaLink="false">66c4c6adbd556981b1bdc462</guid>
                
                    <category>
                        <![CDATA[ PHP ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Software Testing ]]>
                    </category>
                
                    <category>
                        <![CDATA[ unit testing ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Zubair Idris Aweda ]]>
                </dc:creator>
                <pubDate>Wed, 09 Mar 2022 01:15:45 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/03/120480919-metal-bolts-nuts-group-drawing-technical-drafting-steel-screws-threaded-parts-with-hexagonal-head-bl--1-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>There are many different ways to test your software application, and unit testing is an important one.</p>
<p>So what is unit testing and how can you do it? You'll learn that and more in this article.</p>
<h2 id="heading-what-is-unit-testing">What is Unit Testing?</h2>
<blockquote>
<p>Unit testing is a software development process in which the smallest testable parts of an application, called units, are individually and independently scrutinised for process operation. - <a target="_blank" href="https://searchsoftwarequality.techtarget.com/definition/unit-testing#:~:text=Unit%20testing%20is%20a%20software,developers%20and%20sometimes%20QA%20staff.">SearchSoftwareQuality</a></p>
</blockquote>
<p>In basic terms, unit testing means that you break your application down to its simplest pieces and test these small pieces to ensure that each part is error free (and secure). </p>
<p>This testing is automated and written by software engineers as part of their development process. This is a very important step during development as it helps developers build better applications with fewer bugs.</p>
<h2 id="heading-what-is-phpunit">What is PHPUnit?</h2>
<p>You can perform unit testing in PHP with <a target="_blank" href="https://phpunit.de">PHPUnit</a>, a programmer-oriented testing framework for PHP. PHPUnit is an instance of the xUnit architecture for unit testing frameworks. It is very easy to install and get started with.</p>
<h2 id="heading-phpunit-installation">PHPUnit Installation</h2>
<p>You can install PHPUnit globally on your server. You can also install it locally, on a per-project, development-time basis as a dependency to your project using composer. This article will explain how to use it on a per project basis.</p>
<p>To get started, create and initiate a new project with composer using these commands:</p>
<pre><code class="lang-bash">$ mkdir test-project
$ <span class="hljs-built_in">cd</span> test-project
$ composer init
</code></pre>
<p>The first command creates a folder in your current directory, <code>test-project</code> and the second command moves into it. The last command starts an interactive shell.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/03/Screenshot-2022-03-08-at-11.08.39.png" alt="Image" width="600" height="400" loading="lazy">
<em>Composer init prompt</em></p>
<p>Follow the prompt, filling in the details as required (the default values are fine). You can set the project description, author name (or contributors' names), minimum stability for dependencies, project type, license, and define your dependencies.</p>
<p>You can skip the dependencies part, as we are not installing any dependencies. PHPUnit is supposed to be a <code>dev-dependency</code> because testing as a whole should only happen during development.</p>
<p>Now, when the prompt asks <code>Would you like to define your dev dependencies (require-dev) interactively [yes]?</code>, press enter to accept. Then type in <code>phpunit/phpunit</code> to install PHPUnit as a <code>dev-dependency</code>.</p>
<p>Accept the other defaults and proceed to generating the <code>composer.json</code> file. The generated file should look like this currently:</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"name"</span>: <span class="hljs-string">"zubair/test-project"</span>,
    <span class="hljs-attr">"require-dev"</span>: {
        <span class="hljs-attr">"phpunit/phpunit"</span>: <span class="hljs-string">"^9.5"</span>
    },
    <span class="hljs-attr">"autoload"</span>: {
        <span class="hljs-attr">"psr-4"</span>: {
            <span class="hljs-attr">"Zubair\\TestProject\\"</span>: <span class="hljs-string">"src/"</span>
        }
    },
    <span class="hljs-attr">"authors"</span>: [
        {
            <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Idris Aweda Zubair"</span>,
            <span class="hljs-attr">"email"</span>: <span class="hljs-string">"zubairidrisaweda@gmail.com"</span>
        }
    ],
    <span class="hljs-attr">"require"</span>: {}
}
</code></pre>
<p>To learn how to install PHPUnit globally on your server, read <a target="_blank" href="https://phpunit.readthedocs.io/en/9.5/installation.html#">here</a>.</p>
<h2 id="heading-how-to-write-tests-in-phpunit">How to Write Tests in PHPUnit</h2>
<p>Writing tests in PHPUnit is quite simple. Here are a few conventions to get you started:</p>
<ul>
<li>To test a class in PHP, you'll create a test class named after that class. For example, if I had some sort of <code>User</code> class, the test class would be named <code>UserTest</code>.</li>
<li>The test class, <code>UserTest</code>, will usually inherit the <code>PHPUnit\Framework\TestCase</code> class.</li>
<li>Individual tests on the class are public methods named with <code>test</code> as a prefix. For example, to test a <code>sayHello</code> method on the <code>User</code> class, the method will be named <code>testSayHello</code>.</li>
<li>Inside the test method, say <code>testSayHello</code>, you use PHPUnit's method like <code>assertSame</code> to see that some method returns some expected value.</li>
</ul>
<p>A popular convention is to have all tests in a <code>tests</code> directory, and all source code in the <code>src</code> directory. </p>
<h2 id="heading-phpunit-testing-example">PHPUnit Testing Example</h2>
<p>To help understand this article, here's a sample <code>User</code> class with simple methods that will be tested:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">Zubair</span>\<span class="hljs-title">TestProject</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">InvalidArgumentException</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> $age;
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">array</span> $favorite_movies = [];
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> $name;

    <span class="hljs-comment">/**
     * <span class="hljs-doctag">@param</span> int $age
     * <span class="hljs-doctag">@param</span> string $name
     */</span>
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__construct</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> $age, <span class="hljs-keyword">string</span> $name</span>)
    </span>{
        <span class="hljs-keyword">$this</span>-&gt;age = $age;
        <span class="hljs-keyword">$this</span>-&gt;name = $name;
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">tellName</span>(<span class="hljs-params"></span>): <span class="hljs-title">string</span>
    </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">"My name is "</span> . <span class="hljs-keyword">$this</span>-&gt;name . <span class="hljs-string">"."</span>;
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">tellAge</span>(<span class="hljs-params"></span>): <span class="hljs-title">string</span>
    </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">"I am "</span> . <span class="hljs-keyword">$this</span>-&gt;age . <span class="hljs-string">" years old."</span>;
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addFavoriteMovie</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> $movie</span>): <span class="hljs-title">bool</span>
    </span>{
        <span class="hljs-keyword">$this</span>-&gt;favorite_movies[] = $movie;

        <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">removeFavoriteMovie</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> $movie</span>): <span class="hljs-title">bool</span>
    </span>{
        <span class="hljs-keyword">if</span> (!in_array($movie, <span class="hljs-keyword">$this</span>-&gt;favorite_movies)) <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">InvalidArgumentException</span>(<span class="hljs-string">"Unknown movie: "</span> . $movie);

        <span class="hljs-keyword">unset</span>(<span class="hljs-keyword">$this</span>-&gt;favorite_movies[array_search($movie, <span class="hljs-keyword">$this</span>-&gt;favorite_movies)]);

        <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
    }
}
</code></pre>
<p>This user class could be the <code>User</code> class in your movie streaming application. The user has a name, age, and a list of favourite movies that can be updated. For the rest of the article we will test that all these features work as they're expected to.</p>
<p>Create a <code>UserTest</code> class in the <code>tests</code> folder. Paste this in to start:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">namespace</span> <span class="hljs-title">Zubair</span>\<span class="hljs-title">TestProject</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">PHPUnit</span>\<span class="hljs-title">Framework</span>\<span class="hljs-title">TestCase</span>;

<span class="hljs-keyword">final</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserTest</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">TestCase</span>
</span>{
    <span class="hljs-comment">// Tests will go here</span>
}
</code></pre>
<h3 id="heading-test-constructor">Test Constructor</h3>
<p>Normally, you wouldn't be testing the <code>__construct</code> method. However, since we're setting values in it, it only makes sense to be sure that the values are being set correctly. </p>
<p>This seems like a very small thing to test, but that's the whole point of unit tests – to ensure that the smallest parts of your application function as expected.</p>
<p>Create a <code>testClassConstructor</code> method to test the constructor:</p>
<pre><code class="lang-php"><span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">testClassConstructor</span>(<span class="hljs-params"></span>)
</span>{
    $user = <span class="hljs-keyword">new</span> User(<span class="hljs-number">18</span>, <span class="hljs-string">'John'</span>);

    <span class="hljs-keyword">$this</span>-&gt;assertSame(<span class="hljs-string">'John'</span>, $user-&gt;name);
    <span class="hljs-keyword">$this</span>-&gt;assertSame(<span class="hljs-number">18</span>, $user-&gt;age);
    <span class="hljs-keyword">$this</span>-&gt;assertEmpty($user-&gt;favorite_movies);
}
</code></pre>
<p>Let's take a quick break now, to see how to run the tests.</p>
<h2 id="heading-how-to-run-tests-in-phpunit">How to Run Tests in PHPUnit</h2>
<p>You can run all the tests in a directory using the PHPUnit binary installed in your vendor folder.</p>
<pre><code class="lang-bash">$ ./vendor/bin/phpunit --verbose tests
</code></pre>
<p>You can also run a single test by providing the path to the test file.</p>
<pre><code class="lang-bash">$ ./vendor/bin/phpunit --verbose tests/UserTest.php
</code></pre>
<p>You use the <code>--verbose</code> flag to get more information on the test status.</p>
<p>Now, we can run the test and see the output:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/03/Screenshot-2022-03-08-at-13.17.54.png" alt="Image" width="600" height="400" loading="lazy">
<em>Test Output</em></p>
<p>The output shows that we ran 1 test, and made 3 assertions in it. We also see how long it took to run the test, as well as how much memory was used in running the test.</p>
<p>These assertions are what PHPUnit uses to compare values returned from the methods to their expected value. </p>
<p>This example uses <code>assertSame</code> to check if the <code>name</code> and <code>age</code> properties on the user object match the entered values. It also uses <code>assertEmpty</code> to check that the <code>favorite_movies</code> array is empty. </p>
<p>To see a list of all these assertions, you can check out PHPUnit's docs <a target="_blank" href="https://phpunit.readthedocs.io/en/9.5/assertions.html#appendixes-assertions">here</a>.</p>
<p>Edit the code to check if the user age is the same as <em>21</em>.</p>
<pre><code class="lang-php"><span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">testClassConstructor</span>(<span class="hljs-params"></span>)
</span>{
    $user = <span class="hljs-keyword">new</span> User(<span class="hljs-number">18</span>, <span class="hljs-string">'John'</span>);

    <span class="hljs-keyword">$this</span>-&gt;assertSame(<span class="hljs-string">'John'</span>, $user-&gt;name);
    <span class="hljs-keyword">$this</span>-&gt;assertSame(<span class="hljs-number">21</span>, $user-&gt;age);
    <span class="hljs-keyword">$this</span>-&gt;assertEmpty($user-&gt;favorite_movies);
}
</code></pre>
<p>Running the test again this time gives this output:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/03/Screenshot-2022-03-08-at-13.24.20.png" alt="Image" width="600" height="400" loading="lazy">
<em>Failed Assertion Output</em></p>
<p>The output now shows that we ran 1 test, with 2 successful assertions, and also a failed one. We can see some explanation of the failure, showing the expected value, the gotten value, and the line where the error is from.</p>
<h3 id="heading-test-testname-and-tellage">Test testName and tellAge</h3>
<p>Next, we can test the <code>testName</code> method. This method tells the name of a user as a sentence. So, we can write the test to check:</p>
<ul>
<li>If the returned value is a string.</li>
<li>If the returned string has the user's name in it (with or without case sensitivity).</li>
</ul>
<pre><code class="lang-php"><span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">testTellName</span>(<span class="hljs-params"></span>)
</span>{
    $user = <span class="hljs-keyword">new</span> User(<span class="hljs-number">18</span>, <span class="hljs-string">'John'</span>);

    <span class="hljs-keyword">$this</span>-&gt;assertIsString($user-&gt;tellName());
    <span class="hljs-keyword">$this</span>-&gt;assertStringContainsStringIgnoringCase(<span class="hljs-string">'John'</span>, $user-&gt;tellName());
}
</code></pre>
<p>The test uses the assertions <code>assertIsString</code>  and <code>assertStringContainsStringIgnoringCase</code> to check that the return value is a string and that it contains the string <em>John</em>, respectively.</p>
<p>The <code>testAge</code> method is very similar to <code>testName</code> and uses the same logic. Its test will be similar to the previous one:</p>
<pre><code class="lang-php"><span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">testTellAge</span>(<span class="hljs-params"></span>)
</span>{
    $user = <span class="hljs-keyword">new</span> User(<span class="hljs-number">18</span>, <span class="hljs-string">'John'</span>);

    <span class="hljs-keyword">$this</span>-&gt;assertIsString($user-&gt;tellAge());
    <span class="hljs-keyword">$this</span>-&gt;assertStringContainsStringIgnoringCase(<span class="hljs-string">'18'</span>, $user-&gt;tellAge());
}
</code></pre>
<h3 id="heading-test-addfavoritemovie">Test addFavoriteMovie</h3>
<p>We can test this method, too. This method adds a movie to the list of movies. To test it, we can check if the newly added movie is in the list, and that the number of items in the list actually increased. </p>
<p>The latter is for confirming that items are not being displaced. Also, since the function returns some value at the end, we can check that this value is correct too.</p>
<pre><code class="lang-php"><span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">testAddFavoriteMovie</span>(<span class="hljs-params"></span>)
</span>{
    $user = <span class="hljs-keyword">new</span> User(<span class="hljs-number">18</span>, <span class="hljs-string">'John'</span>);

    <span class="hljs-keyword">$this</span>-&gt;assertTrue($user-&gt;addFavoriteMovie(<span class="hljs-string">'Avengers'</span>));
    <span class="hljs-keyword">$this</span>-&gt;assertContains(<span class="hljs-string">'Avengers'</span>, $user-&gt;favorite_movies);
    <span class="hljs-keyword">$this</span>-&gt;assertCount(<span class="hljs-number">1</span>, $user-&gt;favorite_movies);
}
</code></pre>
<p>Here, we use a few new assertions – <code>assertTrue</code>, <code>assertContains</code>, and <code>assertCount</code> – to check that the returned value is true, that it contains the newly added string, and that the array now has one item in it.</p>
<h3 id="heading-test-removefavoritemovie">Test removeFavoriteMovie</h3>
<p>Finally, we can test that the method to remove a movie works. </p>
<pre><code class="lang-php"><span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">testRemoveFavoriteMovie</span>(<span class="hljs-params"></span>)
</span>{
    $user = <span class="hljs-keyword">new</span> User(<span class="hljs-number">18</span>, <span class="hljs-string">'John'</span>);

    <span class="hljs-keyword">$this</span>-&gt;assertTrue($user-&gt;addFavoriteMovie(<span class="hljs-string">'Avengers'</span>));
    <span class="hljs-keyword">$this</span>-&gt;assertTrue($user-&gt;addFavoriteMovie(<span class="hljs-string">'Justice League'</span>));

    <span class="hljs-keyword">$this</span>-&gt;assertTrue($user-&gt;removeFavoriteMovie(<span class="hljs-string">'Avengers'</span>));
    <span class="hljs-keyword">$this</span>-&gt;assertNotContains(<span class="hljs-string">'Avengers'</span>, $user-&gt;favorite_movies);
    <span class="hljs-keyword">$this</span>-&gt;assertCount(<span class="hljs-number">1</span>, $user-&gt;favorite_movies);
}
</code></pre>
<p>Here, we're adding some movies to the list. Then, we remove one of them, and confirm that the function returned true. Next, we confirm the removal by checking that the value is no longer in the list. Finally, we confirm that we have only one movie in the list, instead of two.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Now you know how to set up PHPUnit in your projects and how to test and ensure that you're building world class software. You can find all the code for this article <a target="_blank" href="https://github.com/Zubs/php-testing">here</a>.</p>
<p>If you have any questions or relevant advice, please get in touch with me to share them.</p>
<p>To read more of my articles or follow my work, you can connect with me on <a target="_blank" href="https://www.linkedin.com/in/idris-aweda-zubair-5433121a3/">LinkedIn</a>, <a target="_blank" href="https://twitter.com/AwedaIdris">Twitter</a>, and <a target="_blank" href="https://github.com/Zubs">Github</a>. It’s quick, it’s easy, and it’s free!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Laravel Subdomains – How to Create and Manage Subdomains in Your Apps ]]>
                </title>
                <description>
                    <![CDATA[ Modern web applications usually perform more than one function. They often have more than one section, offer more than one service, and have a couple of clients. But the more functionality the app has, the clumsier your route paths will get.  What if... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/laravel-subdomians/</link>
                <guid isPermaLink="false">66c4c69f1b22d2d8d9040eca</guid>
                
                    <category>
                        <![CDATA[ Laravel ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Applications ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Zubair Idris Aweda ]]>
                </dc:creator>
                <pubDate>Thu, 16 Sep 2021 17:19:06 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/09/subdomain-structure.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Modern web applications usually perform more than one function. They often have more than one section, offer more than one service, and have a couple of clients.</p>
<p>But the more functionality the app has, the clumsier your route paths will get. </p>
<p>What if there was a way to separate all these parts into smaller components with better and cleaner routes? Something that users could easily access and use independently, under the same website?</p>
<p>Fortunately, there is such a way: <strong>Subdomains</strong>.</p>
<h2 id="heading-what-is-a-subdomain">What is a Subdomain?</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/image-75.png" alt="Image" width="600" height="400" loading="lazy">
<em>Credit: <a target="_blank" href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fblog.electroica.com%2Fgoogles-top-searches-india-2019%2F&amp;psig=AOvVaw2bx9ZwYjA8ldb4CuGhccN-&amp;ust=1631749915996000&amp;source=images&amp;cd=vfe&amp;ved=0CAwQjhxqFwoTCMiBuKbU__ICFQAAAAAdAAAAABAh">Electroica Blog</a></em></p>
<p>Here's a <a target="_blank" href="https://www.domain.com/blog/subdomain/">basic definition of a subdomain</a>:</p>
<blockquote>
<p>A subdomain is, as the name would suggest, an additional section of your main <strong>domain name</strong>. You create subdomains to help organize and navigate to different sections of your main website. Within your main domain, you can have as many subdomains as necessary to get to all of the different pages of your website.</p>
</blockquote>
<p>So let's say you have a website called mysite.com. You have a blog section, a store section, and a general website section for about and contact pages. The website could have subdomains like blog.mysite.com and store.mysite.com, where the main website would use the main domain.</p>
<h2 id="heading-why-should-you-use-subdomains">Why Should You Use Subdomains?</h2>
<p>Subdomains are pretty useful, and here are some of their main advantages:</p>
<ul>
<li>Users can easily remember you website domains, which means they'll likely use your site more.</li>
<li>You'd be able to split your large application into smaller groups, so it will be easier to manage, debug, and update or upgrade.</li>
<li>Subdomains also allow for personalisation – for example, a blog app could give each user their own subdomain (like <em>username.domain.com</em>).</li>
<li>Subdomains also let developers test version of their application before pushing to production. You could have a <em>beta.site.com</em> to preview changes before deploying them to the main site.</li>
</ul>
<p>Let's see how all this works by building an actual project and testing it out.</p>
<h2 id="heading-how-to-create-new-laravel-project">How to Create New Laravel Project</h2>
<p>I have <a target="_blank" href="https://www.docker.com/">Docker</a> setup on my laptop, so I'll be using the <a target="_blank" href="https://laravel.com/docs/8.x/sail">Sail</a> setup that <a target="_blank" href="https://laravel.com/docs/8.x/">Laravel</a> ships with.</p>
<pre><code class="lang-bash">curl -s <span class="hljs-string">"https://laravel.build/example-app"</span> | bash
</code></pre>
<blockquote>
<p><em>You can use any other method you feel comfortable with. See the <a target="_blank" href="https://laravel.com/docs/8.x/installation">docs</a> for help.</em></p>
</blockquote>
<h3 id="heading-start-the-laravel-server">Start the Laravel Server</h3>
<pre><code class="lang-bash">./vendor/bin/sail up -d
</code></pre>
<h2 id="heading-how-to-configure-the-route-files">How to Configure the Route Files</h2>
<p>In your <code>web.php</code> file, you can define individual routes with their domain (or subdomain) like this:</p>
<pre><code class="lang-php">Route::get(<span class="hljs-string">'/'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-string">'First sub domain'</span>;
})-&gt;domain(<span class="hljs-string">'blog.'</span> . env(<span class="hljs-string">'APP_URL'</span>));
</code></pre>
<p>Now you can access the page at <em>blog.domain.com</em>.</p>
<p>But more often than not, you'll have more than one path in an application, like a domain and subdomains. So, it's a good idea to use a route group to cover all the routes in the same domain or subdomain.</p>
<pre><code class="lang-php">Route::domain(<span class="hljs-string">'blog.'</span> . env(<span class="hljs-string">'APP_URL'</span>))-&gt;group(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    Route::get(<span class="hljs-string">'posts'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">'Second subdomain landing page'</span>;
    });
    Route::get(<span class="hljs-string">'post/{id}'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">$id</span>) </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">'Post '</span> . $id . <span class="hljs-string">' in second subdomain'</span>;
    });
});
</code></pre>
<p>Now, all the routes for the domain can be handled in one place.</p>
<h2 id="heading-how-to-make-subdomains-dynamic">How to Make Subdomains Dynamic</h2>
<p>As I mentioned earlier, you can use subdomains to allow personalisation in web applications, so they need to be dynamic. For example, <a target="_blank" href="https://medium.com">Medium</a> gives authors domains like <em>username.domain.com</em>.</p>
<p>You can do this easily in Laravel as subdomains may be assigned route parameters just like route URIs. This allows you to capture a portion of the subdomain for usage in your route closure or controller.</p>
<pre><code class="lang-php">Route::domain(<span class="hljs-string">'{username}.'</span> . env(<span class="hljs-string">'APP_URL'</span>))-&gt;group(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    Route::get(<span class="hljs-string">'post/{id}'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">$username, $id</span>) </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">'User '</span> . $username . <span class="hljs-string">' is trying to read post '</span> . $id;
    });
});
</code></pre>
<p>In this example, you could have a domain like <em>zubair.domain.com</em> with route parameters, too<em>.</em></p>
<h2 id="heading-route-service-providers">Route Service Providers</h2>
<p>For very large applications, the <code>web.php</code> could get a bit messy if the routes keep increasing. It is best to split the routes into different files, preferably by subdomain.</p>
<p>In your <code>RouteServiceProvider.php</code> file, you'll see this code in the <code>boot</code> method:</p>
<pre><code class="lang-php"><span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">boot</span>(<span class="hljs-params"></span>)
    </span>{
        <span class="hljs-keyword">$this</span>-&gt;configureRateLimiting();

        <span class="hljs-keyword">$this</span>-&gt;routes(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
            Route::prefix(<span class="hljs-string">'api'</span>)
                -&gt;middleware(<span class="hljs-string">'api'</span>)
                -&gt;namespace(<span class="hljs-keyword">$this</span>-&gt;namespace)
                -&gt;group(base_path(<span class="hljs-string">'routes/api.php'</span>));

            Route::middleware(<span class="hljs-string">'web'</span>)
                -&gt;namespace(<span class="hljs-keyword">$this</span>-&gt;namespace)
                -&gt;group(base_path(<span class="hljs-string">'routes/web.php'</span>));
        });
    }
</code></pre>
<p>This is Laravel's default route configuration to separate API routes from web routes. We'll use this same file to separate subdomains.</p>
<p>Add the following to the method:</p>
<pre><code class="lang-php">Route::domain(<span class="hljs-string">'blog.'</span> . env(<span class="hljs-string">'APP_URL'</span>))
                -&gt;middleware(<span class="hljs-string">'web'</span>)
                -&gt;namespace(<span class="hljs-keyword">$this</span>-&gt;namespace)
                -&gt;group(base_path(<span class="hljs-string">'routes/blog.php'</span>));
</code></pre>
<p>This is telling Laravel that whenever someone hits the <em>blog.domain.com</em> endpoint, look for the route in the blog.php (that we are yet to create).</p>
<p>We can go on to create the <code>blog.php</code> file in the <code>routes</code> folder, and add the following content:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>

<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Support</span>\<span class="hljs-title">Facades</span>\<span class="hljs-title">Route</span>;

Route::get(<span class="hljs-string">'/'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-string">'Route using separate file'</span>;
});
</code></pre>
<p>At this point, you're done with all the code! All that's left is some server configuration.</p>
<h2 id="heading-server-configuration">Server Configuration</h2>
<p>If you're using a service such as <a target="_blank" href="https://laravel.com/docs/8.x/valet">Laravel Valet</a>, it is way easier to setup.</p>
<p>In the root directory of your project, run:</p>
<pre><code class="lang-bash">valet link domain
valet link blog.domain
</code></pre>
<p>And if you're not using Laravel Valet, you can add this to your <code>/etc/hosts/</code> file:</p>
<pre><code><span class="hljs-number">127.0</span><span class="hljs-number">.0</span><span class="hljs-number">.1</span>       domain.test
<span class="hljs-number">127.0</span><span class="hljs-number">.0</span><span class="hljs-number">.1</span>       blog.domain.test
</code></pre><p>This is basically just mapping the domain to the IP.</p>
<h2 id="heading-summary"><strong>Summary</strong></h2>
<p>Now you know how to set up and manage subdomains in your Laravel apps. You can find all the code for this article <a target="_blank" href="https://github.com/Zubs/subdomain-test">here</a>.</p>
<p>If you have any questions or relevant advice, please get in touch with me to share them.</p>
<p>To read more of my articles or follow my work, you can connect with me on <a target="_blank" href="https://www.linkedin.com/in/idris-aweda-zubair-5433121a3/">LinkedIn</a>, <a target="_blank" href="https://twitter.com/AwedaIdris">Twitter</a>, and <a target="_blank" href="https://github.com/Zubs">Github</a>. It’s quick, it’s easy, and it’s free!</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
