<?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[ SQLite - 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[ SQLite - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Mon, 25 May 2026 05:06:09 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/sqlite/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ A Brief Introduction to SQLite ]]>
                </title>
                <description>
                    <![CDATA[ SQLite is one of the most underappreciated tools in a developer's toolkit. It's a full-featured relational database that runs directly in your application. No server setup. No configuration files. No network protocols. Just a simple library that give... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/a-brief-introduction-to-sqlite/</link>
                <guid isPermaLink="false">68cd625e82b856dadd4cceba</guid>
                
                    <category>
                        <![CDATA[ SQL ]]>
                    </category>
                
                    <category>
                        <![CDATA[ SQLite ]]>
                    </category>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Mark Mahoney ]]>
                </dc:creator>
                <pubDate>Fri, 19 Sep 2025 14:02:06 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1758290415152/439fa61c-9342-47cb-867a-0416fe6bd6cf.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p><a target="_blank" href="https://sqlite.org/">SQLite</a> is one of the most underappreciated tools in a developer's toolkit. It's a full-featured relational database that runs directly in your application. No server setup. No configuration files. No network protocols. Just a simple library that gives you the power of an ACID compliant RDBMS right where you need it.</p>
<p>SQLite powers more applications than you might think. It's in every smartphone, most web browsers, and countless desktop applications. Your phone probably has hundreds of SQLite databases on it right now. Despite handling billions of databases worldwide, many developers aren't familiar with all of the cool things that you can do with SQLite.</p>
<p>This tutorial introduces SQLite through practical examples in C/C++, Python, and Java. You can pick and choose the languages that suit your needs. No language wars here. You'll learn how to integrate SQLite into real applications. Whether you're building a desktop app, a web API, or just need local data storage without the drama of a full database server, SQLite has your back.</p>
<h2 id="heading-code-playbacks">Code Playbacks</h2>
<p>Code playbacks are a unique way to learn about programming. They are guided walkthroughs of code, allowing you to see not just the code itself but also the thought process behind it. This approach helps you understand not only what the code does, but why it was written that way. Here is a short video to show how to move through a code playback:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/uYbHqCNjVDM" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<p>By registering on <a target="_blank" href="https://playbackpress.com/books">Playback Press</a>, you'll gain access to an AI assistant that can answer your questions about the code. This makes learning even more interactive and personalized. Watch this video to see how to work with it:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/WAPql5KZFR4" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<h2 id="heading-a-brief-introduction-to-sqlite">A Brief Introduction to SQLite</h2>
<p>You can find my entire collection of SQLite code playbacks in my free book, <a target="_blank" href="https://playbackpress.com/books/sqlitebook">"Programming with SQLite"</a>.</p>
<p>Here's what you'll learn:</p>
<h3 id="heading-chapter-1-database-design-and-sql">Chapter 1: Database Design and SQL</h3>
<p>In this chapter, I cover the basics of relational database design and SQL. I keep it simple and practical. If you'd like more introductory SQL content like this go to my <a target="_blank" href="https://playbackpress.com/books/sqlbook">Intro SQL</a> book. If you'd like some SQL problems to work through, check out <a target="_blank" href="https://playbackpress.com/books/workedsqlbook">30 Worked SQL Examples</a>. If you already dream in <code>SELECT</code> statements, skip ahead to the chapter that best suits your needs.</p>
<ul>
<li><p><a target="_blank" href="https://playbackpress.com/books/sqlitebook/chapter/1/1">1.1 Database Design and Basic SQL</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/sqlitebook/chapter/1/2">1.2 One-to-Many Relationships and More SQL</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/sqlitebook/chapter/1/3">1.3 Many-to-Many Relationships and Even More SQL</a></p>
</li>
</ul>
<h3 id="heading-chapter-2-sqlite-in-cc">Chapter 2: SQLite in C/C++</h3>
<p>In this chapter, I discuss how to use the low level SQLite API from a C or C++ program. You have a lot of power when using the API and I cover ACID transactions. Yes, we're going to talk about pointers and memory management. Even if you're not a C/C++ programmer and haven't touched a pointer since college, I recommend looking at this chapter. Understanding what's happening under the hood will make the other chapters clearer. Plus, you can impress your friends at parties by casually mentioning you know how database transactions really work.</p>
<ul>
<li><p><a target="_blank" href="https://playbackpress.com/books/sqlitebook/chapter/2/1">2.1 Using the SQLite C/C++ API</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/sqlitebook/chapter/2/2">2.2 An Object Oriented Auction Program</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/sqlitebook/chapter/2/3">2.3 SQLite Transactions</a></p>
</li>
</ul>
<h3 id="heading-chapter-3-sqlite-in-python">Chapter 3: SQLite in Python</h3>
<p>Learn how to use SQLite in any Python program including Flask web apps. No ORMs hiding what's really happening. Just clean, direct database access. I cover how to query and create SQLite databases and then show how to build an API using <a target="_blank" href="https://flask.palletsprojects.com/en/stable/">Flask</a>. By the end, you'll have a working web API that didn't require installing PostgreSQL, configuring connection pools, or sacrificing a weekend to database administration.</p>
<ul>
<li><p><a target="_blank" href="https://playbackpress.com/books/sqlitebook/chapter/3/1">3.1 Using a SQLite Database in a Python Program</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/sqlitebook/chapter/3/2">3.2 Creating SQLite Databases</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/sqlitebook/chapter/3/3">3.3 Using SQLite in a Flask Web Application</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/sqlitebook/chapter/3/4">3.4 Creating a Web API with Flask and SQLite</a></p>
</li>
</ul>
<h3 id="heading-chapter-4-sqlite-in-java">Chapter 4: SQLite in Java</h3>
<p>In this final chapter I give an example in Java using JDBC. Because sometimes you need to write enterprise code, and SQLite works there too. Who says you need Oracle for everything?</p>
<ul>
<li><a target="_blank" href="https://playbackpress.com/books/sqlitebook/chapter/4/1">4.1 Using a SQLite Database in a Java Program</a></li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Ready to explore SQLite? Start with the first playback and see how fun database programming can be. Each example builds on the previous one, giving you practical experience with real code. Real code solving real problems.</p>
<p>I'd love to hear your thoughts! Feel free to share your comments, questions, or feedback via email: <a target="_blank" href="mailto:mark@playbackpress.com">mark@playbackpress.com</a>. Your input helps me improve and create even better content.</p>
<p>If you've found this tutorial helpful, consider supporting my work through <a target="_blank" href="https://github.com/sponsors/markm208">GitHub Sponsors</a>. Your contributions help cover hosting costs and keep Playback Press free for everyone. Thank you for helping me continue creating educational resources for the developer community!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ An Animated Introduction to SQL – Learn to Query Relational Databases ]]>
                </title>
                <description>
                    <![CDATA[ In this tutorial, you’ll learn about the Structured Query Language (SQL), the standard language used to query relational databases. SQL is not a traditional programming language. In Python or Java, you write step-by-step instructions that tell the co... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/an-animated-introduction-to-sql-learn-to-query-relational-databases/</link>
                <guid isPermaLink="false">67ffd01c61bb8e3a320b1eac</guid>
                
                    <category>
                        <![CDATA[ SQL ]]>
                    </category>
                
                    <category>
                        <![CDATA[ SQLite ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Mark Mahoney ]]>
                </dc:creator>
                <pubDate>Wed, 16 Apr 2025 15:43:24 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1744818155429/10b16956-a249-4815-b50a-594b58330a01.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this tutorial, you’ll learn about the <a target="_blank" href="https://www.freecodecamp.org/news/what-is-sql-database-definition-for-beginners/">Structured Query Language (SQL)</a>, the standard language used to query relational databases.</p>
<p>SQL is not a traditional programming language. In Python or Java, you write step-by-step instructions that tell the computer exactly <strong>how</strong> to do something. This is called <strong>imperative</strong> programming.</p>
<p>SQL works differently. First, you understand what data is stored in your tables. Then you write a query describing <strong>what</strong> data you want and you give it to a database management system. The database management system figures out <strong>how</strong> to get it. This <strong>declarative</strong> style is part of what makes SQL powerful (and fun to use).</p>
<p>You don’t need to be a programmer to learn SQL, but having some programming experience helps. Concepts like conditional logic and comparing values to see if something is true or false will feel familiar if you’ve coded before.</p>
<p>If you want an introduction to the basics, check out some of my programming language tutorials listed below.</p>
<h2 id="heading-tutorial-structure"><strong>Tutorial Structure</strong></h2>
<p>This tutorial is built around three books of interactive code playbacks I use in my database courses:</p>
<ul>
<li><p><a target="_blank" href="https://playbackpress.com/books/sqlbook">Database Design and SQL for Beginners</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/workedsqlbook">Worked SQL Examples</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/sqlitebook">Programming with SQLite</a></p>
</li>
</ul>
<p>Each section of this tutorial includes worked examples where I show how I write SQL step-by-step, explaining my thought process along the way. You’ll see me experiment, refine, and build queries piece by piece, just like a real developer would. I rely heavily on Entity-Relationship Diagrams and Schemas to help me visualize the data stored in the databases.</p>
<p>Here’s how the tutorial is organized:</p>
<h3 id="heading-part-1-a-whirlwind-tour-of-sql"><strong>Part 1: A Whirlwind Tour of SQL</strong></h3>
<p>(from <a target="_blank" href="https://playbackpress.com/books/sqlbook">Database Design and SQL for Beginners</a>)</p>
<p>I start by exploring a simple database for a fictional pet adoption center called the <em>Paw Prints Adoption Center</em>. I introduce essential concepts like:</p>
<ul>
<li><p>Entity-Relationship (ER) diagrams</p>
</li>
<li><p>Schemas</p>
</li>
<li><p>Table structure and relationships</p>
</li>
</ul>
<p>This foundation sets the stage for everything that follows. If you're new to database design, spend some time here before moving on.</p>
<h3 id="heading-part-2-core-sql-concepts-and-keywords"><strong>Part 2: Core SQL Concepts and Keywords</strong></h3>
<p>(also from <a target="_blank" href="https://playbackpress.com/books/sqlbook">Database Design and SQL for Beginners</a>)</p>
<p>I cover the most important SQL keywords and ideas. Each topic is explained in its own playback with examples:</p>
<ul>
<li><p><code>CREATE TABLE</code>, <code>ALTER TABLE</code></p>
</li>
<li><p><code>SELECT</code>, <code>FROM</code>, <code>WHERE</code>, <code>JOIN</code></p>
</li>
<li><p><code>ORDER BY</code>, <code>GROUP BY</code>, <code>HAVING</code></p>
</li>
<li><p><code>INSERT</code>, <code>UPDATE</code>, <code>DELETE</code></p>
</li>
<li><p>Nested queries, Common Table Expressions, and set operations (<code>UNION</code>, <code>INTERSECT</code>, <code>EXCEPT</code>)</p>
</li>
<li><p>Indexes and transactions</p>
</li>
</ul>
<p>This section works as a reference. If you're stuck on a query or forget what a keyword does, come back here.</p>
<h3 id="heading-part-3-practice-problems"><strong>Part 3: Practice Problems</strong></h3>
<p>(from <a target="_blank" href="https://playbackpress.com/books/workedsqlbook">Worked SQL Examples</a>)</p>
<p>Practice is how you really learn. I’ve included 36 practice problems using the Paw Prints database and a new university database. Each problem has an animated playback showing how I worked through the solution step-by-step.</p>
<p>Try writing your own query before watching the solution. Struggling with the problem first will help you learn much more than just watching me provide the answer.</p>
<p>These problems build your skills gradually and help reinforce the use of ER diagrams and schemas in real scenarios.</p>
<h3 id="heading-part-4-using-sqlite-in-programs"><strong>Part 4: Using SQLite in Programs</strong></h3>
<p>(from <a target="_blank" href="https://playbackpress.com/books/sqlitebook">Programming with SQLite</a>)</p>
<p>In this final optional section, I show how to connect SQL to real code. You’ll learn how to use the <a target="_blank" href="https://sqlite.org/">SQLite</a> database in:</p>
<ul>
<li><p>C/C++</p>
</li>
<li><p>Python and Flask</p>
</li>
<li><p>Java</p>
</li>
</ul>
<h3 id="heading-running-queries"><strong>Running Queries</strong></h3>
<p>A database management system (DBMS) is the software used to manage and query data in a database. Many DBMSs require significant configuration and often a separate server to respond to query requests. Setting these up can be challenging for newcomers.</p>
<p><a target="_blank" href="https://sqlite.org/">SQLite</a> is a simple DBMS that doesn’t require much setup. It’s a great tool to start with. It doesn’t need a standalone server and stores the entire database in a single file.</p>
<p>To make it easier to view and edit your databases, I recommend using <a target="_blank" href="https://sqlitebrowser.org/">DB Browser for SQLite</a>. It’s a free, open-source tool with a simple interface and all of SQLite’s functionality built in. You can open database files, browse tables, run queries, and edit data using an intuitive user interface. It’s especially useful when you’re learning and want to quickly see how your queries affect the data.</p>
<h3 id="heading-optional-web-based-alternative-to-db-browser"><strong>Optional: Web-Based Alternative to DB Browser</strong></h3>
<p>If you prefer not to install any software, you can use a web-based tool like <a target="_blank" href="https://inloop.github.io/sqlite-viewer/">SQLite Viewer</a> or <a target="_blank" href="https://sqliteonline.com/">SQLite Online</a>. These let you upload a <code>.sqlite</code> file, run queries, and explore a database from your browser.</p>
<ul>
<li><p><a target="_blank" href="https://inloop.github.io/sqlite-viewer/">SQLite Viewer</a>: A simple, read-only viewer. Good for inspecting tables and testing basic queries.</p>
</li>
<li><p><a target="_blank" href="https://sqliteonline.com/">SQLite Online</a>: A full-featured SQLite IDE. You can create databases, upload files, run queries, and even save your work.</p>
</li>
</ul>
<p>Both tools are great for quick experiments or checking your work without installing anything.</p>
<h3 id="heading-code-playbacks"><strong>Code Playbacks</strong></h3>
<p>This tutorial is not a traditional video or static text. Each section includes links to interactive <strong>code playbacks</strong> that animate how the code or query was built, step-by-step. You can pause and rewind to see each change as it happens.</p>
<p>Each playback includes a narrative, screenshots, whiteboard-style drawings, and self-grading multiple-choice questions to reinforce what you’ve learned.</p>
<p>If you haven’t seen a code playback before, don’t worry. They’re easy to use and allow you to see how queries evolve over time. Here’s a short video showing how to view a code playback:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/uYbHqCNjVDM" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<h3 id="heading-playback-press"><strong>Playback Press</strong></h3>
<p><a target="_blank" href="https://playbackpress.com/books">Playback Press</a> is the platform where I publish my interactive code walkthroughs. Each book includes step-by-step animations, AI tutoring, and built-in quizzes.</p>
<p>I also created <a target="_blank" href="https://markm208.github.io/">Storyteller</a>, the free, open-source tool that powers these playbacks.</p>
<h3 id="heading-ai-tutor"><strong>AI Tutor</strong></h3>
<p>While you're viewing a code playback, you can ask an AI tutor questions about the queries. It gives clear, focused answers and doesn’t rush you. You can also ask it to create new self-grading multiple-choice questions to test your understanding.</p>
<p>To use the AI tutor and quizzes, create a free account on Playback Press and add one of the books to your bookshelf.</p>
<h2 id="heading-table-of-contents"><strong>Table of Contents</strong></h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-part-1-a-whirlwind-tour-of-sql-1">Part 1: A Whirlwind Tour of SQL</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-part-2-a-beginners-reference-to-sql">Part 2: A Beginner’s Reference to SQL</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-part-3-practice-problems-paw-prints-and-university-databases">Part 3: Practice Problems — Paw Prints and University Databases</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-part-4-using-sqlite-in-programs-1">Part 4: Using SQLite in Programs</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-comments-and-feedback">Comments and Feedback</a></p>
</li>
</ul>
<h2 id="heading-part-1-a-whirlwind-tour-of-sql-1"><strong>Part 1: A Whirlwind Tour of SQL</strong></h2>
<p>When someone is asked to manage some data, most people's first instinct is to use a spreadsheet. Spreadsheets are easy to use and flexible. But as your data grows more complex, they start to show some weaknesses.</p>
<p>One major issue is redundant data. When the same piece of information appears in multiple places, there's a risk that one copy might change while the others stay the same. This can lead to inconsistencies, errors, and confusing results.</p>
<p>Relational databases help solve this by organizing data in a structured way that reduces redundancy by design. Before building a database, it’s helpful to model the data using an Entity-Relationship (ER) diagram.</p>
<h3 id="heading-entity-relationship-diagrams"><strong>Entity-Relationship Diagrams</strong></h3>
<p>An ER diagram is a planning tool used to visualize the structure of a database. It helps you figure out what kinds of data you need to store and how those pieces of data relate to each other.</p>
<ul>
<li><p><strong>Entities</strong> are the main objects or concepts in your system, like <code>Person</code>, <code>Course</code>, or <code>Dog</code>. Entities have attributes that describe them. A <code>Person</code> might have <code>name</code>, <code>date of birth</code>, and <code>address</code> attributes, for example.</p>
</li>
<li><p><strong>Relationships</strong> describe how entities are connected. For example, a <code>Person</code> might <em>adopt</em> a <code>Dog</code>, or a <code>Student</code> might <em>enroll in</em> a <code>Course</code>.</p>
</li>
</ul>
<p>By laying this out in a diagram, you can clearly see what data is being stored and how the entities are related to each other. This makes it easier to design the tables in your database correctly.</p>
<p>Here is an example of an ER diagram used in this part of the tutorial:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1744664220972/dc57e1fa-bad9-42b0-9158-0f2649c4f282.png" alt="An Entity-Relationship Diagram for the Paw Prints Database" class="image--center mx-auto" width="988" height="1188" loading="lazy"></p>
<h3 id="heading-schemas"><strong>Schemas</strong></h3>
<p>A <strong>schema</strong> is another way to describe the structure of a database. It shows the same information as the ER diagram, but in a more technical and precise format focused on how the data will actually be stored. Each element of a schema will become a table in a database.</p>
<p>Instead of lines connecting boxes, a schema uses primary keys and foreign keys:</p>
<ul>
<li><p>A <strong>primary key</strong> uniquely identifies each row in a table. Primary keys have a solid underline.</p>
</li>
<li><p>A <strong>foreign key</strong> refers to the primary key in another table, linking the two together. Foreign keys have a dashed underline.</p>
</li>
</ul>
<p>Here is an example of a schema used in this part of the tutorial:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1744664247677/146dff90-e366-4ba2-b584-07d5ff42cca9.jpeg" alt="A Schema for the Paw Prints database" class="image--center mx-auto" width="1803" height="1753" loading="lazy"></p>
<p>While an ER diagram is more visual and conceptual, a schema is more concrete and closer to the actual implementation in the DBMS. You’ll see both used throughout this tutorial as I move from planning to writing SQL.</p>
<h3 id="heading-try-it-explore-a-relational-database-in-action"><strong>Try It: Explore a Relational Database in Action</strong></h3>
<p>To see how these concepts work in practice, take a look at the following three code playbacks. They walk through the design of a relational database for a fictional pet adoption center called <strong>Paw Prints</strong>. These examples will help you understand how entities, relationships, and schemas come together in a real database and how to write simple SQL queries to explore that data.</p>
<p>Start with the first playback and move through all three in order:</p>
<ol>
<li><h4 id="heading-database-design-and-simple-sqlhttpsplaybackpresscombookssqlbookchapter11-introduces-the-paw-prints-database-and-shows-how-to-write-basic-sql-queries"><a target="_blank" href="https://playbackpress.com/books/sqlbook/chapter/1/1"><strong>Database Design and Simple SQL</strong></a><strong>:</strong> Introduces the Paw Prints database and shows how to write basic SQL queries.</h4>
</li>
<li><h4 id="heading-one-to-many-relationships-and-more-sqlhttpsplaybackpresscombookssqlbookchapter12-covers-one-to-many-relationships-and-how-to-join-related-tables"><a target="_blank" href="https://playbackpress.com/books/sqlbook/chapter/1/2"><strong>One-to-Many Relationships and More SQL</strong></a><strong>:</strong> Covers one-to-many relationships and how to join related tables.</h4>
</li>
<li><h4 id="heading-many-to-many-relationships-and-even-more-sqlhttpsplaybackpresscombookssqlbookchapter13-shows-how-to-handle-many-to-many-relationships-using-join-tables-and-more-advanced-queries"><a target="_blank" href="https://playbackpress.com/books/sqlbook/chapter/1/3"><strong>Many-to-Many Relationships and Even More SQL</strong></a><strong>:</strong> Shows how to handle many-to-many relationships using join tables and more advanced queries.</h4>
</li>
</ol>
<p>As you watch, pause to make sure you understand how the data is structured and how each SQL query is written. You can always refer back to this section later if something in the next chapters isn’t clear.</p>
<h2 id="heading-part-2-a-beginners-reference-to-sql"><strong>Part 2: A Beginner’s Reference to SQL</strong></h2>
<p>This section takes a closer look at the core SQL commands introduced in the whirlwind tour. Each playback focuses on one topic and shows how to use it through step-by-step examples. I continue to use the Paw Prints database in these examples.</p>
<p>Think of this as a reference section. You don’t need to go through everything in order but you may want to go through them all at least once before beginning to practice in part 3. Come back here whenever you need a refresher on a particular SQL concept.</p>
<p>Here are the key concepts we’ll cover:</p>
<h4 id="heading-create-table-and-alter-tablehttpsplaybackpresscombookssqlbookchapter21"><a target="_blank" href="https://playbackpress.com/books/sqlbook/chapter/2/1"><strong>CREATE TABLE and ALTER TABLE</strong></a></h4>
<p>Learn how to define tables in a relational database. This playback shows how to create tables from scratch and how to change them later using <code>ALTER TABLE</code>.</p>
<h4 id="heading-inserthttpsplaybackpresscombookssqlbookchapter22"><a target="_blank" href="https://playbackpress.com/books/sqlbook/chapter/2/2"><strong>INSERT</strong></a></h4>
<p>See how to add new rows of data to a table. This example shows how to use the <code>INSERT</code> command and make sure your data matches the table structure.</p>
<h4 id="heading-selecthttpsplaybackpresscombookssqlbookchapter23"><a target="_blank" href="https://playbackpress.com/books/sqlbook/chapter/2/3"><strong>SELECT</strong></a></h4>
<p>This playback introduces the <code>SELECT</code> keyword in SQL. You’ll learn how to retrieve specific columns (or attributes) from a table and see what the result set looks like.</p>
<h4 id="heading-fromhttpsplaybackpresscombookssqlbookchapter24"><a target="_blank" href="https://playbackpress.com/books/sqlbook/chapter/2/4"><strong>FROM</strong></a></h4>
<p>Explore how the <code>FROM</code> clause specifies which tables your data comes from. This sets the stage for combining data from multiple sources using a Cartesian product. You’ll also see how to <code>JOIN</code> tables together.</p>
<h4 id="heading-wherehttpsplaybackpresscombookssqlbookchapter25"><a target="_blank" href="https://playbackpress.com/books/sqlbook/chapter/2/5"><strong>WHERE</strong></a></h4>
<p>Learn how to filter results using conditions. The <code>WHERE</code> clause helps narrow down the rows returned by a query. This playback also shows how to join tables by matching foreign keys to primary keys.</p>
<h4 id="heading-update-and-deletehttpsplaybackpresscombookssqlbookchapter26"><a target="_blank" href="https://playbackpress.com/books/sqlbook/chapter/2/6"><strong>UPDATE and DELETE</strong></a></h4>
<p>Learn how to change existing data in the database with <code>UPDATE</code> and remove data using <code>DELETE</code>. You’ll also see how to avoid accidental changes by using <code>WHERE</code> conditions carefully.</p>
<h4 id="heading-order-byhttpsplaybackpresscombookssqlbookchapter27"><a target="_blank" href="https://playbackpress.com/books/sqlbook/chapter/2/7"><strong>ORDER BY</strong></a></h4>
<p>Sort your results using <code>ORDER BY</code>. You’ll learn how to control the order of your output using one or more attributes.</p>
<h4 id="heading-aggregate-operators-group-by-and-havinghttpsplaybackpresscombookssqlbookchapter28"><a target="_blank" href="https://playbackpress.com/books/sqlbook/chapter/2/8"><strong>Aggregate Operators, GROUP BY, and HAVING</strong></a></h4>
<p>Group rows and calculate summary values using aggregate functions like <code>COUNT</code>, <code>AVG</code>, <code>MIN</code>, <code>MAX</code>, and <code>SUM</code>. This playback also shows how to use <code>GROUP BY</code> and <code>HAVING</code> to work with grouped results.</p>
<h4 id="heading-nested-queries-with-in-and-common-table-expressionshttpsplaybackpresscombookssqlbookchapter29"><a target="_blank" href="https://playbackpress.com/books/sqlbook/chapter/2/9"><strong>Nested Queries with IN and Common Table Expressions</strong></a></h4>
<p>Learn how to use nested queries – queries inside other queries – to build more flexible logic. This playback also shows how to write cleaner queries using Common Table Expressions (CTEs).</p>
<h4 id="heading-union-intersect-excepthttpsplaybackpresscombookssqlbookchapter210"><a target="_blank" href="https://playbackpress.com/books/sqlbook/chapter/2/10"><strong>UNION, INTERSECT, EXCEPT</strong></a></h4>
<p>See how to combine the results of multiple queries. This example shows how <code>UNION</code>, <code>INTERSECT</code>, and <code>EXCEPT</code> help you work with data from different queries as if it were one set.</p>
<h4 id="heading-transactionshttpsplaybackpresscombookssqlbookchapter211"><a target="_blank" href="https://playbackpress.com/books/sqlbook/chapter/2/11"><strong>Transactions</strong></a></h4>
<p>Learn how to group multiple SQL commands into a single <strong>transaction</strong>, so they all succeed or fail together. Transactions help protect your data from partial updates.</p>
<h4 id="heading-create-indexhttpsplaybackpresscombookssqlbookchapter212"><a target="_blank" href="https://playbackpress.com/books/sqlbook/chapter/2/12"><strong>CREATE INDEX</strong></a></h4>
<p>Improve query performance using indexes. This playback shows how to create an index on one or more columns and explains why that makes certain queries run faster.</p>
<h2 id="heading-part-3-practice-problems-paw-prints-and-university-databases"><strong>Part 3: Practice Problems — Paw Prints and University Databases</strong></h2>
<p>Now it’s time to apply what you’ve learned.</p>
<p>Below are six practice problems that use the Paw Prints database from earlier examples. If you haven't recreated it yourself, here is a link to the SQLite file <a target="_blank" href="https://markm208.github.io/sqlbook/dogsFinal.sqlite">dogsFinal.sqlite.</a> Each one asks a specific question that requires you to write a SQL query to find the answer. Try solving each one on your own before watching the solution.</p>
<p>Don’t worry if you don’t get it right on the first try. Writing SQL often involves trial and error, even for experienced developers. The goal is to think through the problem and make progress, not to be perfect. Start small and build your queries up through an iterative process.</p>
<p>Click each link to view the playback after you've made your attempt:</p>
<ol>
<li><h4 id="heading-which-dogs-have-had-the-most-visitshttpsplaybackpresscombookssqlbookchapter31"><a target="_blank" href="https://playbackpress.com/books/sqlbook/chapter/3/1"><strong>Which Dogs Have Had the Most Visits?</strong></a></h4>
</li>
</ol>
<p>Figure out how to count visits for each dog and sort them to find the most frequently visited ones.</p>
<ol start="2">
<li><h4 id="heading-number-of-adoptions-and-average-agehttpsplaybackpresscombookssqlbookchapter32"><a target="_blank" href="https://playbackpress.com/books/sqlbook/chapter/3/2"><strong>Number of Adoptions and Average Age</strong></a></h4>
</li>
</ol>
<p>Find the total number of adoptions and the average age of adopted dogs. You'll need to filter the data appropriately.</p>
<ol start="3">
<li><h4 id="heading-locations-with-leastmost-aggressive-dogshttpsplaybackpresscombookssqlbookchapter33"><a target="_blank" href="https://playbackpress.com/books/sqlbook/chapter/3/3"><strong>Locations with Least/Most Aggressive Dogs</strong></a></h4>
</li>
</ol>
<p>Use grouping to compare aggression levels across locations and determine where the most and fewest aggressive dogs are housed.</p>
<ol start="4">
<li><h4 id="heading-average-time-to-adoption-by-locationhttpsplaybackpresscombookssqlbookchapter34"><a target="_blank" href="https://playbackpress.com/books/sqlbook/chapter/3/4"><strong>Average Time to Adoption By Location</strong></a></h4>
</li>
</ol>
<p>Calculate the average time it takes for dogs to be adopted, broken down by location.</p>
<ol start="5">
<li><h4 id="heading-finding-available-capacity-at-each-locationhttpsplaybackpresscombookssqlbookchapter35"><a target="_blank" href="https://playbackpress.com/books/sqlbook/chapter/3/5"><strong>Finding Available Capacity at Each Location</strong></a></h4>
</li>
</ol>
<p>Determine how much space is left at each shelter location by comparing total capacity to current occupancy.</p>
<ol start="6">
<li><h4 id="heading-who-visited-then-adopted-an-aggressive-doghttpsplaybackpresscombookssqlbookchapter36"><a target="_blank" href="https://playbackpress.com/books/sqlbook/chapter/3/6"><strong>Who Visited then Adopted an Aggressive Dog</strong></a></h4>
</li>
</ol>
<p>This complex query asks you to track user actions over time, first visiting, then adopting an aggressive dog. A good challenge!</p>
<h3 id="heading-university-database"><strong>University Database</strong></h3>
<p>Next, you’ll work with a more complex database that models a university’s course and grading system. You’ll use it to analyze real-world relationships between students, professors, courses, and departments.</p>
<p>Download the SQLite version of the database here:<br><a target="_blank" href="https://markm208.github.io/workedsqlbook/studentGrades.sqlite">studentGrades.sqlite</a></p>
<p>Here are the <strong>entities</strong> in the database:</p>
<ul>
<li><p><code>Students</code></p>
</li>
<li><p><code>Sections</code></p>
</li>
<li><p><code>Courses</code></p>
</li>
<li><p><code>Professors</code></p>
</li>
<li><p><code>Departments</code></p>
</li>
</ul>
<p>And here are the <strong>relationships</strong> between them:</p>
<ul>
<li><p>Each student takes zero or more sections. (Every student receives a grade.)</p>
</li>
<li><p>Each section has zero or more students taking it.</p>
</li>
<li><p>Each section is an instance of a course.</p>
</li>
<li><p>Each course has zero or more sections.</p>
</li>
<li><p>Each section is taught by a single professor.</p>
</li>
<li><p>Each professor teaches zero or more sections.</p>
</li>
<li><p>Each professor belongs to zero or more departments.</p>
</li>
<li><p>Each department has zero or more professors.</p>
</li>
<li><p>Each department has, at most, one professor who is its chairperson.</p>
</li>
<li><p>Each professor may chair, at most, one department.</p>
</li>
<li><p>Each course is offered by a department.</p>
</li>
<li><p>Each department offers zero or more courses.</p>
</li>
</ul>
<p>The code playbacks highlight how I use <strong>ER diagrams</strong> and <strong>schemas</strong> to help me build my queries. You can preview them here:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1744665047915/c0c0c31a-8463-4d01-a15c-930d6e24b574.jpeg" alt="An Entity-Relationship Diagram for the University database" class="image--center mx-auto" width="1350" height="1781" loading="lazy"></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1744665070077/fd9c60be-0140-4281-ba8c-a3216001a043.jpeg" alt="A Schema for the University database" class="image--center mx-auto" width="1328" height="1677" loading="lazy"></p>
<p>Try each query on your own before watching the solution.</p>
<ol start="7">
<li><h4 id="heading-list-every-course-name-section-number-and-professor-name-in-chronological-order-for-every-section-that-has-ever-been-offeredhttpsplaybackpresscombooksworkedsqlbookchapter11"><a target="_blank" href="https://playbackpress.com/books/workedsqlbook/chapter/1/1"><strong>List every course name, section number, and professor name in chronological order for every section that has ever been offered</strong></a></h4>
</li>
<li><h4 id="heading-list-every-course-name-and-section-number-for-every-course-offered-by-the-computer-science-departmenthttpsplaybackpresscombooksworkedsqlbookchapter12"><a target="_blank" href="https://playbackpress.com/books/workedsqlbook/chapter/1/2"><strong>List every course name and section number for every course offered by the computer science department</strong></a></h4>
</li>
<li><h4 id="heading-find-the-name-of-every-professor-who-has-ever-taught-csci111httpsplaybackpresscombooksworkedsqlbookchapter13"><a target="_blank" href="https://playbackpress.com/books/workedsqlbook/chapter/1/3"><strong>Find the name of every professor who has ever taught CSCI111</strong></a></h4>
</li>
<li><h4 id="heading-list-all-of-the-professor-names-and-their-departmentshttpsplaybackpresscombooksworkedsqlbookchapter14"><a target="_blank" href="https://playbackpress.com/books/workedsqlbook/chapter/1/4"><strong>List all of the professor names and their departments</strong></a></h4>
</li>
<li><h4 id="heading-list-the-names-of-the-professors-who-have-taught-both-csci111-and-csci112httpsplaybackpresscombooksworkedsqlbookchapter15"><a target="_blank" href="https://playbackpress.com/books/workedsqlbook/chapter/1/5"><strong>List the names of the professors who have taught both CSCI111 and CSCI112</strong></a></h4>
</li>
<li><h4 id="heading-list-the-names-of-all-of-the-students-of-professor-mark-mahoney-who-are-greater-than-or-equal-to-21-years-oldhttpsplaybackpresscombooksworkedsqlbookchapter21"><a target="_blank" href="https://playbackpress.com/books/workedsqlbook/chapter/2/1"><strong>List the names of all of the students of professor Mark Mahoney who are greater than or equal to 21 years old</strong></a></h4>
</li>
<li><h4 id="heading-list-the-names-of-all-of-the-students-who-are-taught-by-a-department-chairhttpsplaybackpresscombooksworkedsqlbookchapter22"><a target="_blank" href="https://playbackpress.com/books/workedsqlbook/chapter/2/2"><strong>List the names of all of the students who are taught by a department chair</strong></a></h4>
</li>
<li><h4 id="heading-list-all-of-the-course-names-and-section-numbers-of-every-course-ever-taught-by-a-department-chairhttpsplaybackpresscombooksworkedsqlbookchapter23"><a target="_blank" href="https://playbackpress.com/books/workedsqlbook/chapter/2/3"><strong>List all of the course names and section numbers of every course ever taught by a department chair</strong></a></h4>
</li>
<li><h4 id="heading-list-all-of-the-courses-with-the-oldest-studenthttpsplaybackpresscombooksworkedsqlbookchapter24"><a target="_blank" href="https://playbackpress.com/books/workedsqlbook/chapter/2/4"><strong>List all of the courses with the oldest student</strong></a></h4>
</li>
<li><h4 id="heading-list-all-of-the-courses-and-section-numbers-with-the-youngest-average-student-agehttpsplaybackpresscombooksworkedsqlbookchapter25"><a target="_blank" href="https://playbackpress.com/books/workedsqlbook/chapter/2/5"><strong>List all of the courses and section numbers with the youngest average student age</strong></a></h4>
</li>
<li><h4 id="heading-list-all-of-the-course-names-and-section-numbers-of-courses-with-less-than-four-creditshttpsplaybackpresscombooksworkedsqlbookchapter31"><a target="_blank" href="https://playbackpress.com/books/workedsqlbook/chapter/3/1"><strong>List all of the course names and section numbers of courses with less than four credits</strong></a></h4>
</li>
<li><h4 id="heading-list-all-of-the-course-names-and-section-numbers-with-the-smallest-enrollmenthttpsplaybackpresscombooksworkedsqlbookchapter32"><a target="_blank" href="https://playbackpress.com/books/workedsqlbook/chapter/3/2"><strong>List all of the course names and section numbers with the smallest enrollment</strong></a></h4>
</li>
<li><h4 id="heading-list-all-of-the-student-names-who-have-taken-more-than-one-course-with-mark-mahoneyhttpsplaybackpresscombooksworkedsqlbookchapter33"><a target="_blank" href="https://playbackpress.com/books/workedsqlbook/chapter/3/3"><strong>List all of the student names who have taken more than one course with Mark Mahoney</strong></a></h4>
</li>
<li><h4 id="heading-list-all-of-the-student-names-who-have-taken-a-course-with-both-mark-mahoney-and-eric-whendonhttpsplaybackpresscombooksworkedsqlbookchapter34"><a target="_blank" href="https://playbackpress.com/books/workedsqlbook/chapter/3/4"><strong>List all of the student names who have taken a course with both Mark Mahoney and Eric Whendon</strong></a></h4>
</li>
<li><h4 id="heading-list-all-the-course-names-and-section-numbers-that-had-two-or-more-students-earn-ashttpsplaybackpresscombooksworkedsqlbookchapter35"><a target="_blank" href="https://playbackpress.com/books/workedsqlbook/chapter/3/5"><strong>List all the course names and section numbers that had two or more students earn A's</strong></a></h4>
</li>
<li><h4 id="heading-find-the-names-of-all-the-students-who-have-taken-csci111httpsplaybackpresscombooksworkedsqlbookchapter41"><a target="_blank" href="https://playbackpress.com/books/workedsqlbook/chapter/4/1"><strong>Find the names of all the students who have taken CSCI111</strong></a></h4>
</li>
<li><h4 id="heading-find-the-names-of-all-professors-in-the-computer-science-department-who-are-not-chairs-of-a-departmenthttpsplaybackpresscombooksworkedsqlbookchapter42"><a target="_blank" href="https://playbackpress.com/books/workedsqlbook/chapter/4/2"><strong>Find the names of all professors in the computer science department who are not chairs of a department</strong></a></h4>
</li>
<li><h4 id="heading-find-the-names-of-all-professors-who-are-the-chair-of-a-departmenthttpsplaybackpresscombooksworkedsqlbookchapter43"><a target="_blank" href="https://playbackpress.com/books/workedsqlbook/chapter/4/3"><strong>Find the names of all professors who are the chair of a department</strong></a></h4>
</li>
<li><h4 id="heading-find-the-ssn-first-and-last-name-course-name-and-grade-earned-for-all-courses-taken-in-spring-2007httpsplaybackpresscombooksworkedsqlbookchapter44"><a target="_blank" href="https://playbackpress.com/books/workedsqlbook/chapter/4/4"><strong>Find the ssn, first and last name, course name, and grade earned for all courses taken in spring 2007</strong></a></h4>
</li>
<li><h4 id="heading-find-the-course-name-and-section-number-of-all-the-courses-that-have-ever-been-offered-in-the-fallhttpsplaybackpresscombooksworkedsqlbookchapter45"><a target="_blank" href="https://playbackpress.com/books/workedsqlbook/chapter/4/5"><strong>Find the course name and section number of all the courses that have ever been offered in the fall</strong></a></h4>
</li>
<li><h4 id="heading-find-the-names-of-all-of-the-professors-teaching-in-spring-2007httpsplaybackpresscombooksworkedsqlbookchapter51"><a target="_blank" href="https://playbackpress.com/books/workedsqlbook/chapter/5/1"><strong>Find the names of all of the professors teaching in spring 2007</strong></a></h4>
</li>
<li><h4 id="heading-find-the-names-of-all-of-the-students-who-have-received-an-a-and-a-b-in-any-coursehttpsplaybackpresscombooksworkedsqlbookchapter52"><a target="_blank" href="https://playbackpress.com/books/workedsqlbook/chapter/5/2"><strong>Find the names of all of the students who have received an A and a B in any course</strong></a></h4>
</li>
<li><h4 id="heading-find-out-how-many-students-have-ever-taken-csci111httpsplaybackpresscombooksworkedsqlbookchapter53"><a target="_blank" href="https://playbackpress.com/books/workedsqlbook/chapter/5/3"><strong>Find out how many students have ever taken CSCI111</strong></a></h4>
</li>
<li><h4 id="heading-find-the-average-age-of-all-students-who-ever-had-a-course-with-mark-mahoneyhttpsplaybackpresscombooksworkedsqlbookchapter54"><a target="_blank" href="https://playbackpress.com/books/workedsqlbook/chapter/5/4"><strong>Find the average age of all students who ever had a course with Mark Mahoney</strong></a></h4>
</li>
<li><h4 id="heading-find-the-names-of-all-of-the-professors-who-have-never-taught-a-coursehttpsplaybackpresscombooksworkedsqlbookchapter55"><a target="_blank" href="https://playbackpress.com/books/workedsqlbook/chapter/5/5"><strong>Find the names of all of the professors who have never taught a course</strong></a></h4>
</li>
<li><h4 id="heading-find-the-names-of-all-of-the-professors-who-have-taught-may-joneshttpsplaybackpresscombooksworkedsqlbookchapter61"><a target="_blank" href="https://playbackpress.com/books/workedsqlbook/chapter/6/1"><strong>Find the names of all of the professors who have taught May Jones</strong></a></h4>
</li>
<li><h4 id="heading-find-the-names-of-the-students-who-have-had-a-course-in-fall-2006-or-spring-2007httpsplaybackpresscombooksworkedsqlbookchapter62"><a target="_blank" href="https://playbackpress.com/books/workedsqlbook/chapter/6/2"><strong>Find the names of the students who have had a course in Fall 2006 or Spring 2007</strong></a></h4>
</li>
<li><h4 id="heading-find-the-names-of-the-students-who-have-taken-a-course-from-a-professor-who-has-more-than-one-appointment-to-a-departmenthttpsplaybackpresscombooksworkedsqlbookchapter63"><a target="_blank" href="https://playbackpress.com/books/workedsqlbook/chapter/6/3"><strong>Find the names of the students who have taken a course from a professor who has more than one appointment to a department</strong></a></h4>
</li>
<li><h4 id="heading-find-the-average-age-of-students-who-took-courses-in-spring-2007httpsplaybackpresscombooksworkedsqlbookchapter64"><a target="_blank" href="https://playbackpress.com/books/workedsqlbook/chapter/6/4"><strong>Find the average age of students who took courses in Spring 2007</strong></a></h4>
</li>
<li><h4 id="heading-find-the-sum-of-all-of-the-credit-hours-offered-by-the-computer-science-department-in-2007httpsplaybackpresscombooksworkedsqlbookchapter65"><a target="_blank" href="https://playbackpress.com/books/workedsqlbook/chapter/6/5"><strong>Find the sum of all of the credit hours offered by the computer science department in 2007</strong></a></h4>
</li>
</ol>
<h2 id="heading-part-4-using-sqlite-in-programs-1"><strong>Part 4: Using SQLite in Programs</strong></h2>
<p>So far, you’ve learned how to write SQL queries and design relational databases. In this optional section, you’ll see how to use SQLite in actual code. Each playback walks through a working program that reads from and writes to a SQLite database.</p>
<h3 id="heading-why-use-sqlite-in-programs"><strong>Why Use SQLite in Programs?</strong></h3>
<p>SQLite’s simplicity makes it a great choice for quick projects, prototypes, and small applications. You don’t need to run a server, and everything is stored in a single file.</p>
<p>These playbacks show how to embed SQL directly into your code, so your programs can store and retrieve data as part of their normal workflow. I really love using it in my projects!</p>
<p>Here’s an overview of the playbacks:</p>
<h3 id="heading-cc"><strong>C/C++</strong></h3>
<ol>
<li><h4 id="heading-the-c-sqlite-apihttpsplaybackpresscombookssqlitebookchapter21"><a target="_blank" href="https://playbackpress.com/books/sqlitebook/chapter/2/1"><strong>The C++ SQLite API</strong></a></h4>
</li>
</ol>
<p>Shows how to set up and use the SQLite C++ API. You’ll open a database, run basic queries, and handle results.</p>
<ol start="2">
<li><h4 id="heading-an-object-oriented-auction-programhttpsplaybackpresscombookssqlitebookchapter22"><a target="_blank" href="https://playbackpress.com/books/sqlitebook/chapter/2/2"><strong>An Object-Oriented Auction Program</strong></a></h4>
</li>
</ol>
<p>Builds a more complex C++ program that tracks bids, items, and users. This example shows how to structure a real-world application with SQLite.</p>
<ol start="3">
<li><h4 id="heading-sqlite-transactionshttpsplaybackpresscombookssqlitebookchapter23"><a target="_blank" href="https://playbackpress.com/books/sqlitebook/chapter/2/3"><strong>SQLite Transactions</strong></a></h4>
</li>
</ol>
<p>Explains how to group multiple database operations into a single transaction. This protects your data from partial updates.</p>
<h3 id="heading-python-and-flask"><strong>Python and Flask</strong></h3>
<ol>
<li><h4 id="heading-querying-a-sqlite-databasehttpsplaybackpresscombookssqlitebookchapter31"><a target="_blank" href="https://playbackpress.com/books/sqlitebook/chapter/3/1"><strong>Querying a SQLite Database</strong></a></h4>
</li>
</ol>
<p>Connects a Python script to a SQLite database, runs queries, and processes the results using Python’s built-in libraries.</p>
<ol start="2">
<li><h4 id="heading-creating-sqlite-databaseshttpsplaybackpresscombookssqlitebookchapter32"><a target="_blank" href="https://playbackpress.com/books/sqlitebook/chapter/3/2"><strong>Creating SQLite Databases</strong></a></h4>
</li>
</ol>
<p>Shows how to create new SQLite databases directly from Python, defining tables and inserting initial data.</p>
<ol start="3">
<li><h4 id="heading-flask-basicshttpsplaybackpresscombookssqlitebookchapter33"><a target="_blank" href="https://playbackpress.com/books/sqlitebook/chapter/3/3"><strong>Flask Basics</strong></a></h4>
</li>
</ol>
<p>Introduces Flask. You’ll see how to build a simple web application that can serve pages and connect to your SQLite database.</p>
<ol start="4">
<li><h4 id="heading-creating-an-apihttpsplaybackpresscombookssqlitebookchapter34"><a target="_blank" href="https://playbackpress.com/books/sqlitebook/chapter/3/4"><strong>Creating an API</strong></a></h4>
</li>
</ol>
<p>Takes Flask further by creating a RESTful API that interacts with a SQLite database, letting you perform CRUD operations on a SQLite database.</p>
<h3 id="heading-java"><strong>Java</strong></h3>
<ol>
<li><h4 id="heading-using-a-sqlite-database-in-a-java-programhttpsplaybackpresscombookssqlitebookchapter41"><a target="_blank" href="https://playbackpress.com/books/sqlitebook/chapter/4/1"><strong>Using a SQLite Database in a Java Program</strong></a></h4>
</li>
</ol>
<p>Shows how to integrate the SQLite driver into a Java application. You’ll learn how to open a connection, run queries, and handle exceptions properly.</p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>By now, you’ve learned how to read and write real SQL. You’ve seen how to design a database, how to write queries that retrieve and modify data, and how to tackle increasingly complex questions using the tools SQL gives you.</p>
<p>If you worked through the practice problems you’ve already done what many developers do on the job: examine unfamiliar data, figure out the relationships, and write queries to answer real questions.</p>
<p>SQL is a skill that gets sharper the more you use it. Don’t worry if you still feel a little unsure. Repetition and exploration will build your confidence. Keep experimenting, break things, and try to fix them. That’s how you really learn.</p>
<p>If you’re planning to use SQL in your own projects, try building a small database from scratch or connecting SQLite to one of your programs. You’ll learn a lot by seeing what questions your own data brings up.</p>
<p>Thanks for reading. I hope these playbacks helped make SQL a little easier to understand. Good luck with your next SQL project.</p>
<h2 id="heading-comments-and-feedback"><strong>Comments and Feedback</strong></h2>
<p>You can find all of these code playbacks and more in one of my free books:</p>
<ul>
<li><p><a target="_blank" href="https://playbackpress.com/books/sqlbook">Database Design and SQL for Beginners</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/workedsqlbook">Worked SQL Examples</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/sqlitebook">Programming with SQLite</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cppbook/">An Animated Introduction to Programming in C++</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/pybook">An Animated Introduction to Programming with Python</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/webdevbook">An Introduction to Web Development from Back to Front</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/cljbook">An Animated Introduction to Clojure</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/exbook">An Animated Introduction to Elixir</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/rubybook">A Brief Introduction to Ruby</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/flutterbook">Mobile App Development with Dart and Flutter</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/patternsbook">OO Design Patterns with Java</a></p>
</li>
<li><p><a target="_blank" href="https://playbackpress.com/books/wordzearchbook">How I Built It: Word Zearch</a></p>
</li>
</ul>
<p>Comments and feedback are welcome anytime: <a target="_blank" href="mailto:mark@playbackpress.com">mark@playbackpress.com</a>.</p>
<p>If you'd like to support my work and help keep Playback Press free for all, consider donating using <a target="_blank" href="https://github.com/sponsors/markm208">GitHub Sponsors</a>. I use all of the donations for hosting costs. Your support helps me continue creating educational content like this. Thank you!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Work with SQLite in Python – A Handbook for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ SQLite is one of the most popular relational database management systems (RDBMS). It’s lightweight, meaning that it doesn’t take up much space on your system. One of its best features is that it’s serverless, so you don’t need to install or manage a ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/work-with-sqlite-in-python-handbook/</link>
                <guid isPermaLink="false">66fd1605986ae3c9e56b8ba4</guid>
                
                    <category>
                        <![CDATA[ SQLite ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ database ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ashutosh Krishna ]]>
                </dc:creator>
                <pubDate>Wed, 02 Oct 2024 09:44:37 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1727862097228/24433377-ebb8-49b5-b0ee-5736f629399d.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>SQLite is one of the most popular relational database management systems (RDBMS). It’s lightweight, meaning that it doesn’t take up much space on your system. One of its best features is that it’s serverless, so you don’t need to install or manage a separate server to use it.</p>
<p>Instead, it stores everything in a simple file on your computer. It also requires zero configuration, so there’s no complicated setup process, making it perfect for beginners and small projects.</p>
<p>SQLite is a great choice for small to medium applications because it’s easy to use, fast, and can handle most tasks that bigger databases can do, but without the hassle of managing extra software. Whether you're building a personal project or prototyping a new app, SQLite is a solid option to get things up and running quickly.</p>
<p>In this tutorial, you'll learn how to work with SQLite using Python. Here’s what we’re going to cover in this tutorial:</p>
<ul>
<li><p><a class="post-section-overview" href="#heading-how-to-set-up-your-python-environment">How to Set Up Your Python Environment</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-create-an-sqlite-database">How to Create an SQLite Database</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-create-database-tables">How to Create Database Tables</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-insert-data-into-a-table">How to Insert Data into a Table</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-query-data">How to Query Data</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-update-and-delete-data">How to Update and Delete Data</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-use-transactions">How to Use Transactions</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-optimize-sqlite-query-performance-with-indexing">How to Optimize SQLite Query Performance with Indexing</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-handle-errors-and-exceptions">How to Handle Errors and Exceptions</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-export-and-import-data-bonus-section">How to Export and Import Data [Bonus Section]</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-wrapping-up">Wrapping Up</a></p>
</li>
</ul>
<p>This tutorial is perfect for anyone who wants to get started with databases without diving into complex setups.</p>
<h2 id="heading-how-to-set-up-your-python-environment">How to Set Up Your Python Environment</h2>
<p>Before working with SQLite, let’s ensure your Python environment is ready. Here’s how to set everything up.</p>
<h3 id="heading-installing-python">Installing Python</h3>
<p>If you don’t have Python installed on your system yet, you can download it from the official <a target="_blank" href="https://www.python.org/downloads/">Python website</a>. Follow the installation instructions for your operating system (Windows, macOS, or Linux).</p>
<p>To check if Python is installed, open your terminal (or command prompt) and type:</p>
<pre><code class="lang-bash">python --version
</code></pre>
<p>This should show the current version of Python installed. If it’s not installed, follow the instructions on the Python website.</p>
<h3 id="heading-installing-sqlite3-module">Installing SQLite3 Module</h3>
<p>The good news is that SQLite3 comes built-in with Python! You don’t need to install it separately because it’s included in the standard Python library. This means you can start using it right away without any additional setup.</p>
<h3 id="heading-how-to-create-a-virtual-environment-optional-but-recommended">How to Create a Virtual Environment (Optional but Recommended)</h3>
<p>It’s a good idea to create a virtual environment for each project to keep your dependencies organized. A virtual environment is like a clean slate where you can install packages without affecting your global Python installation.</p>
<p>To create a virtual environment, follow these steps:</p>
<ol>
<li><p>First, open your terminal or command prompt and navigate to the directory where you want to create your project.</p>
</li>
<li><p>Run the following command to create a virtual environment:</p>
</li>
</ol>
<pre><code class="lang-bash">python -m venv env
</code></pre>
<p>Here, <code>env</code> is the name of the virtual environment. You can name it anything you like.</p>
<ol start="3">
<li>Activate the virtual environment:</li>
</ol>
<pre><code class="lang-bash"><span class="hljs-comment"># Use the command for Windows</span>
env\Scripts\activate

<span class="hljs-comment"># Use the command for macOS/Linux:</span>
env/bin/activate
</code></pre>
<p>After activating the virtual environment, you’ll notice that your terminal prompt changes, showing the name of the virtual environment. This means you’re now working inside it.</p>
<h3 id="heading-installing-necessary-libraries">Installing Necessary Libraries</h3>
<p>We’ll need a few additional libraries for this project. Specifically, we’ll use:</p>
<ul>
<li><p><code>pandas</code>: This is an optional library for handling and displaying data in tabular format, useful for advanced use cases.</p>
</li>
<li><p><code>faker</code>: This library will help us generate fake data, like random names and addresses, which we can insert into our database for testing.</p>
</li>
</ul>
<p>To install <code>pandas</code> and <code>faker</code>, simply run the following commands:</p>
<pre><code class="lang-bash">pip install pandas faker
</code></pre>
<p>This installs both <code>pandas</code> and <code>faker</code> into your virtual environment. With this, your environment is set up, and you’re ready to start creating and managing your SQLite database in Python!</p>
<h2 id="heading-how-to-create-an-sqlite-database">How to Create an SQLite Database</h2>
<p>A database is a structured way to store and manage data so that it can be easily accessed, updated, and organized. It’s like a digital filing system that allows you to efficiently store large amounts of data, whether it’s for a simple app or a more complex system. Databases use tables to organize data, with rows and columns representing individual records and their attributes.</p>
<h3 id="heading-how-sqlite-databases-work">How SQLite Databases Work</h3>
<p>Unlike most other database systems, SQLite is a serverless database. This means that it doesn’t require setting up or managing a server, making it lightweight and easy to use. All the data is stored in a single file on your computer, which you can easily move, share, or back up. Despite its simplicity, SQLite is powerful enough to handle many common database tasks and is widely used in mobile apps, embedded systems, and small to medium-sized projects.</p>
<h3 id="heading-how-to-create-a-new-sqlite-database">How to Create a New SQLite Database</h3>
<p>Let’s create a new SQLite database and learn how to interact with it using Python’s <code>sqlite3</code> library.</p>
<h4 id="heading-connecting-to-the-database">Connecting to the Database</h4>
<p>Since <code>sqlite3</code> is pre-installed, you just need to import it in your Python script. To create a new database or connect to an existing one, we use the <code>sqlite3.connect()</code> method. This method takes the name of the database file as an argument. If the file doesn’t exist, SQLite will automatically create it.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sqlite3

<span class="hljs-comment"># Connect to the SQLite database (or create it if it doesn't exist)</span>
connection = sqlite3.connect(<span class="hljs-string">'my_database.db'</span>)
</code></pre>
<p>In this example, a file named <code>my_database.db</code> is created in the same directory as your script. If the file already exists, SQLite will just open the connection to it.</p>
<h4 id="heading-creating-a-cursor">Creating a Cursor</h4>
<p>Once you have a connection, the next step is to create a cursor object. The cursor is responsible for executing SQL commands and queries on the database.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Create a cursor object</span>
cursor = connection.cursor()
</code></pre>
<h4 id="heading-closing-the-connection">Closing the Connection</h4>
<p>After you’ve finished working with the database, it’s important to close the connection to free up any resources. You can close the connection with the following command:</p>
<pre><code class="lang-python"><span class="hljs-comment"># Close the database connection</span>
connection.close()
</code></pre>
<p>However, you should only close the connection once you’re done with all your operations.</p>
<p>When you run your Python script, a file named <code>my_database.db</code> will be created in your current working directory. You’ve now successfully created your first SQLite database!</p>
<h3 id="heading-how-to-use-context-manager-to-open-and-close-connections">How to Use Context Manager to Open and Close Connections</h3>
<p>Python provides a more efficient and cleaner way to handle database connections using the <code>with</code> statement, also known as a context manager. The <code>with</code> statement automatically opens and closes the connection, ensuring that the connection is properly closed even if an error occurs during the database operations. This eliminates the need to manually call <code>connection.close()</code>.</p>
<p>Here’s how you can use the <code>with</code> statement to handle database connections:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sqlite3

<span class="hljs-comment"># Step 1: Use 'with' to connect to the database (or create one) and automatically close it when done</span>
<span class="hljs-keyword">with</span> sqlite3.connect(<span class="hljs-string">'my_database.db'</span>) <span class="hljs-keyword">as</span> connection:

    <span class="hljs-comment"># Step 2: Create a cursor object to interact with the database</span>
    cursor = connection.cursor()

    print(<span class="hljs-string">"Database created and connected successfully!"</span>)

<span class="hljs-comment"># No need to call connection.close(); it's done automatically!</span>
</code></pre>
<p>From now on, we’ll use the <code>with</code> statement in our upcoming code examples to manage database connections efficiently. This will make the code more concise and easier to maintain.</p>
<h2 id="heading-how-to-create-database-tables">How to Create Database Tables</h2>
<p>Now that we’ve created an SQLite database and connected to it, the next step is to create tables inside the database. A table is where we’ll store our data, organized in rows (records) and columns (attributes). For this example, we’ll create a table called <code>Students</code> to store information about students, which we’ll reuse in upcoming sections.</p>
<p>To create a table, we use SQL's <code>CREATE TABLE</code> statement. This command defines the table structure, including the column names and the data types for each column.</p>
<p>Here’s a simple SQL command to create a <code>Students</code> table with the following fields:</p>
<ul>
<li><p><code>id</code>: A unique identifier for each student (an integer).</p>
</li>
<li><p><strong>name</strong>: The student's name (text).</p>
</li>
<li><p><strong>age</strong>: The student's age (an integer).</p>
</li>
<li><p><strong>email</strong>: The student's email address (text).</p>
</li>
</ul>
<p>The SQL command to create this table would look like this:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> Students (
    <span class="hljs-keyword">id</span> <span class="hljs-built_in">INTEGER</span> PRIMARY <span class="hljs-keyword">KEY</span> AUTOINCREMENT,
    <span class="hljs-keyword">name</span> <span class="hljs-built_in">TEXT</span> <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>,
    age <span class="hljs-built_in">INTEGER</span>,
    email <span class="hljs-built_in">TEXT</span>
);
</code></pre>
<p>We can execute this <code>CREATE TABLE</code> SQL command in Python using the <code>sqlite3</code> library. Let’s see how to do that.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sqlite3

<span class="hljs-comment"># Use 'with' to connect to the SQLite database and automatically close the connection when done</span>
<span class="hljs-keyword">with</span> sqlite3.connect(<span class="hljs-string">'my_database.db'</span>) <span class="hljs-keyword">as</span> connection:

    <span class="hljs-comment"># Create a cursor object</span>
    cursor = connection.cursor()

    <span class="hljs-comment"># Write the SQL command to create the Students table</span>
    create_table_query = <span class="hljs-string">'''
    CREATE TABLE IF NOT EXISTS Students (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT NOT NULL,
        age INTEGER,
        email TEXT
    );
    '''</span>

    <span class="hljs-comment"># Execute the SQL command</span>
    cursor.execute(create_table_query)

    <span class="hljs-comment"># Commit the changes</span>
    connection.commit()

    <span class="hljs-comment"># Print a confirmation message</span>
    print(<span class="hljs-string">"Table 'Students' created successfully!"</span>)
</code></pre>
<ul>
<li><p><code>IF NOT EXISTS</code>: This ensures that the table is only created if it doesn’t already exist, preventing errors if the table has been created before.</p>
</li>
<li><p><code>connection.commit()</code>: This saves (commits) the changes to the database.</p>
</li>
</ul>
<p>When you run the Python code above, it will create the <code>Students</code> table in the <code>my_database.db</code> database file. You’ll also see a message in the terminal confirming that the table has been created successfully.</p>
<p>If you’re using Visual Studio Code, you can install the <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=qwtel.sqlite-viewer">SQLite Viewer</a> extension to view SQLite databases.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1727514353100/522fc6f1-0363-41ca-a76a-b730470cb64a.png" alt="SQLite Viewer - VS Code Extension" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<h3 id="heading-data-types-in-sqlite-and-their-mapping-to-python">Data Types in SQLite and Their Mapping to Python</h3>
<p>SQLite supports several data types, which we need to understand when defining our tables. Here’s a quick overview of common SQLite data types and how they map to Python types:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>SQLite Data Type</td><td>Description</td><td>Python Equivalent</td></tr>
</thead>
<tbody>
<tr>
<td><strong>INTEGER</strong></td><td>Whole numbers</td><td><code>int</code></td></tr>
<tr>
<td><strong>TEXT</strong></td><td>Text strings</td><td><code>str</code></td></tr>
<tr>
<td><strong>REAL</strong></td><td>Floating-point numbers</td><td><code>float</code></td></tr>
<tr>
<td><strong>BLOB</strong></td><td>Binary data (e.g., images, files)</td><td><code>bytes</code></td></tr>
<tr>
<td><strong>NULL</strong></td><td>Represents no value or missing data</td><td><code>None</code></td></tr>
</tbody>
</table>
</div><p>In our <code>Students</code> table:</p>
<ul>
<li><p><code>id</code> is of type <code>INTEGER</code>, which maps to Python’s <code>int</code>.</p>
</li>
<li><p><code>name</code> and <code>email</code> are of type <code>TEXT</code>, which map to Python’s <code>str</code>.</p>
</li>
<li><p><code>age</code> is also of type <code>INTEGER</code>, mapping to Python’s <code>int</code>.</p>
</li>
</ul>
<h2 id="heading-how-to-insert-data-into-a-table">How to Insert Data into a Table</h2>
<p>Now that we have our <code>Students</code> table created, it’s time to start inserting data into the database. In this section, we’ll cover how to insert both single and multiple records using Python and SQLite, and how to avoid common security issues like SQL injection by using parameterized queries.</p>
<h3 id="heading-how-to-insert-a-single-record">How to Insert a Single Record</h3>
<p>To insert data into the database, we use the <code>INSERT INTO</code> SQL command. Let’s start by inserting a single record into our <code>Students</code> table.</p>
<p>Here’s the basic SQL syntax for inserting a single record:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span> Students (<span class="hljs-keyword">name</span>, age, email) 
<span class="hljs-keyword">VALUES</span> (<span class="hljs-string">'John Doe'</span>, <span class="hljs-number">20</span>, <span class="hljs-string">'johndoe@example.com'</span>);
</code></pre>
<p>However, instead of writing SQL directly in our Python script with hardcoded values, we’ll use parameterized queries to make our code more secure and flexible. Parameterized queries help prevent SQL injection, a common attack where malicious users can manipulate the SQL query by passing harmful input.</p>
<p>Here’s how we can insert a single record into the <code>Students</code> table using a parameterized query:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sqlite3

<span class="hljs-comment"># Use 'with' to open and close the connection automatically</span>
<span class="hljs-keyword">with</span> sqlite3.connect(<span class="hljs-string">'my_database.db'</span>) <span class="hljs-keyword">as</span> connection:
    cursor = connection.cursor()

    <span class="hljs-comment"># Insert a record into the Students table</span>
    insert_query = <span class="hljs-string">'''
    INSERT INTO Students (name, age, email) 
    VALUES (?, ?, ?);
    '''</span>
    student_data = (<span class="hljs-string">'Jane Doe'</span>, <span class="hljs-number">23</span>, <span class="hljs-string">'jane@example.com'</span>)

    cursor.execute(insert_query, student_data)

    <span class="hljs-comment"># Commit the changes automatically</span>
    connection.commit()

    <span class="hljs-comment"># No need to call connection.close(); it's done automatically!</span>
    print(<span class="hljs-string">"Record inserted successfully!"</span>)
</code></pre>
<p>The <code>?</code> placeholders represent the values to be inserted into the table. The actual values are passed as a tuple (<code>student_data</code>) in the <code>cursor.execute()</code> method.</p>
<h3 id="heading-how-to-insert-multiple-records">How to Insert Multiple Records</h3>
<p>If you want to insert multiple records at once, you can use the <code>executemany()</code> method in Python. This method takes a list of tuples, where each tuple represents one record.</p>
<p>To make our example more dynamic, we can use the <code>Faker</code> library to generate random student data. This is useful for testing and simulating real-world scenarios.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> faker <span class="hljs-keyword">import</span> Faker
<span class="hljs-keyword">import</span> sqlite3

<span class="hljs-comment"># Initialize Faker</span>
fake = Faker([<span class="hljs-string">'en_IN'</span>])

<span class="hljs-comment"># Use 'with' to open and close the connection automatically</span>
<span class="hljs-keyword">with</span> sqlite3.connect(<span class="hljs-string">'my_database.db'</span>) <span class="hljs-keyword">as</span> connection:
    cursor = connection.cursor()

    <span class="hljs-comment"># Insert a record into the Students table</span>
    insert_query = <span class="hljs-string">'''
    INSERT INTO Students (name, age, email) 
    VALUES (?, ?, ?);
    '''</span>
    students_data = [(fake.name(), fake.random_int(
        min=<span class="hljs-number">18</span>, max=<span class="hljs-number">25</span>), fake.email()) <span class="hljs-keyword">for</span> _ <span class="hljs-keyword">in</span> range(<span class="hljs-number">5</span>)]

    <span class="hljs-comment"># Execute the query for multiple records</span>
    cursor.executemany(insert_query, students_data)

    <span class="hljs-comment"># Commit the changes</span>
    connection.commit()

    <span class="hljs-comment"># Print confirmation message</span>
    print(<span class="hljs-string">"Fake student records inserted successfully!"</span>)
</code></pre>
<p>In this code:</p>
<ul>
<li><p><code>Faker()</code> generates random names, ages, and emails for students. Passing the locale(<code>[‘en_IN’]</code>) is optional.</p>
</li>
<li><p><code>cursor.executemany()</code>: This method allows us to insert multiple records at once, making the code more efficient.</p>
</li>
<li><p><code>students_data</code>: A list of tuples where each tuple represents one student’s data.</p>
</li>
</ul>
<h3 id="heading-how-to-handle-common-issues-sql-injection">How to Handle Common Issues: SQL Injection</h3>
<p>SQL injection is a security vulnerability where attackers can insert or manipulate SQL queries by providing harmful input. For example, an attacker might try to inject code like <code>'; DROP TABLE Students; --</code> to delete the table.</p>
<p>By using parameterized queries (as demonstrated above), we avoid this issue. The <code>?</code> placeholders in parameterized queries ensure that input values are treated as data, not as part of the SQL command. This makes it impossible for malicious code to be executed.</p>
<h2 id="heading-how-to-query-data">How to Query Data</h2>
<p>Now that we’ve inserted some data into our <code>Students</code> table, let’s learn how to retrieve the data from the table. We'll explore different methods for fetching data in Python, including <code>fetchone()</code>, <code>fetchall()</code>, and <code>fetchmany()</code>.</p>
<p>To query data from a table, we use the <code>SELECT</code> statement. Here’s a simple SQL command to select all columns from the <code>Students</code> table:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> Students;
</code></pre>
<p>This command retrieves all records and columns from the <code>Students</code> table. We can execute this <code>SELECT</code> query in Python and fetch the results.</p>
<h3 id="heading-how-to-fetch-all-records">How to Fetch All Records</h3>
<p>Here’s how we can fetch all records from the <code>Students</code> table:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sqlite3

<span class="hljs-comment"># Use 'with' to connect to the SQLite database</span>
<span class="hljs-keyword">with</span> sqlite3.connect(<span class="hljs-string">'my_database.db'</span>) <span class="hljs-keyword">as</span> connection:

    <span class="hljs-comment"># Create a cursor object</span>
    cursor = connection.cursor()

    <span class="hljs-comment"># Write the SQL command to select all records from the Students table</span>
    select_query = <span class="hljs-string">"SELECT * FROM Students;"</span>

    <span class="hljs-comment"># Execute the SQL command</span>
    cursor.execute(select_query)

    <span class="hljs-comment"># Fetch all records</span>
    all_students = cursor.fetchall()

    <span class="hljs-comment"># Display results in the terminal</span>
    print(<span class="hljs-string">"All Students:"</span>)
    <span class="hljs-keyword">for</span> student <span class="hljs-keyword">in</span> all_students:
        print(student)
</code></pre>
<p>In this example, the <code>fetchall()</code> method retrieves all rows returned by the query as a list of tuples.</p>
<pre><code class="lang-bash">All Students:
(1, <span class="hljs-string">'Jane Doe'</span>, 23, <span class="hljs-string">'jane@example.com'</span>)
(2, <span class="hljs-string">'Bahadurjit Sabharwal'</span>, 18, <span class="hljs-string">'tristanupadhyay@example.net'</span>)
(3, <span class="hljs-string">'Zayyan Arya'</span>, 20, <span class="hljs-string">'yashawinibhakta@example.org'</span>)
(4, <span class="hljs-string">'Hemani Shukla'</span>, 18, <span class="hljs-string">'gaurikanarula@example.com'</span>)
(5, <span class="hljs-string">'Warda Kara'</span>, 20, <span class="hljs-string">'npatil@example.net'</span>)
(6, <span class="hljs-string">'Mitali Nazareth'</span>, 19, <span class="hljs-string">'sparekh@example.org'</span>)
</code></pre>
<h3 id="heading-how-to-fetch-a-single-record">How to Fetch a Single Record</h3>
<p>If you want to retrieve only one record, you can use the <code>fetchone()</code> method:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sqlite3

<span class="hljs-comment"># Use 'with' to connect to the SQLite database</span>
<span class="hljs-keyword">with</span> sqlite3.connect(<span class="hljs-string">'my_database.db'</span>) <span class="hljs-keyword">as</span> connection:

    <span class="hljs-comment"># Create a cursor object</span>
    cursor = connection.cursor()

    <span class="hljs-comment"># Write the SQL command to select all records from the Students table</span>
    select_query = <span class="hljs-string">"SELECT * FROM Students;"</span>

    <span class="hljs-comment"># Execute the SQL command</span>
    cursor.execute(select_query)

    <span class="hljs-comment"># Fetch one record</span>
    student = cursor.fetchone()

    <span class="hljs-comment"># Display the result</span>
    print(<span class="hljs-string">"First Student:"</span>)
    print(student)
</code></pre>
<p>Output:</p>
<pre><code class="lang-bash">First Student:
(1, <span class="hljs-string">'Jane Doe'</span>, 23, <span class="hljs-string">'jane@example.com'</span>)
</code></pre>
<h3 id="heading-how-to-fetch-multiple-records">How to Fetch Multiple Records</h3>
<p>To fetch a specific number of records, you can use <code>fetchmany(size)</code>:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sqlite3

<span class="hljs-comment"># Use 'with' to connect to the SQLite database</span>
<span class="hljs-keyword">with</span> sqlite3.connect(<span class="hljs-string">'my_database.db'</span>) <span class="hljs-keyword">as</span> connection:

    <span class="hljs-comment"># Create a cursor object</span>
    cursor = connection.cursor()

    <span class="hljs-comment"># Write the SQL command to select all records from the Students table</span>
    select_query = <span class="hljs-string">"SELECT * FROM Students;"</span>

    <span class="hljs-comment"># Execute the SQL command</span>
    cursor.execute(select_query)

    <span class="hljs-comment"># Fetch three records</span>
    three_students = cursor.fetchmany(<span class="hljs-number">3</span>)

    <span class="hljs-comment"># Display results</span>
    print(<span class="hljs-string">"Three Students:"</span>)
    <span class="hljs-keyword">for</span> student <span class="hljs-keyword">in</span> three_students:
        print(student)
</code></pre>
<p>Output:</p>
<pre><code class="lang-bash">Three Students:
(1, <span class="hljs-string">'Jane Doe'</span>, 23, <span class="hljs-string">'jane@example.com'</span>)
(2, <span class="hljs-string">'Bahadurjit Sabharwal'</span>, 18, <span class="hljs-string">'tristanupadhyay@example.net'</span>)
(3, <span class="hljs-string">'Zayyan Arya'</span>, 20, <span class="hljs-string">'yashawinibhakta@example.org'</span>)
</code></pre>
<h3 id="heading-how-to-use-pandas-for-better-data-presentation">How to Use <code>pandas</code> for Better Data Presentation</h3>
<p>For better data presentation, we can use the <code>pandas</code> library to create a <code>DataFrame</code> from our query results. This makes it easier to manipulate and visualize the data.</p>
<p>Here’s how to fetch all records and display them as a pandas DataFrame:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sqlite3
<span class="hljs-keyword">import</span> pandas <span class="hljs-keyword">as</span> pd

<span class="hljs-comment"># Use 'with' to connect to the SQLite database</span>
<span class="hljs-keyword">with</span> sqlite3.connect(<span class="hljs-string">'my_database.db'</span>) <span class="hljs-keyword">as</span> connection:
    <span class="hljs-comment"># Write the SQL command to select all records from the Students table</span>
    select_query = <span class="hljs-string">"SELECT * FROM Students;"</span>

    <span class="hljs-comment"># Use pandas to read SQL query directly into a DataFrame</span>
    df = pd.read_sql_query(select_query, connection)

<span class="hljs-comment"># Display the DataFrame</span>
print(<span class="hljs-string">"All Students as DataFrame:"</span>)
print(df)
</code></pre>
<p>Output:</p>
<pre><code class="lang-bash">All Students as DataFrame:
   id                  name  age                        email
0   1              Jane Doe   23             jane@example.com
1   2  Bahadurjit Sabharwal   18  tristanupadhyay@example.net
2   3           Zayyan Arya   20  yashawinibhakta@example.org
3   4         Hemani Shukla   18    gaurikanarula@example.com
4   5            Warda Kara   20           npatil@example.net
5   6       Mitali Nazareth   19          sparekh@example.org
</code></pre>
<p>The <code>pd.read_sql_query()</code> function executes the SQL query and directly returns the results as a pandas DataFrame.</p>
<h2 id="heading-how-to-update-and-delete-data">How to Update and Delete Data</h2>
<p>In this section, we’ll learn how to update existing records and delete records from our <code>Students</code> table using SQL commands in Python. This is essential for managing and maintaining your data effectively.</p>
<h3 id="heading-updating-existing-records">Updating Existing Records</h3>
<p>To modify existing records in a database, we use the SQL <code>UPDATE</code> command. This command allows us to change the values of specific columns in one or more rows based on a specified condition.</p>
<p>For example, if we want to update a student's age, the SQL command would look like this:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">UPDATE</span> Students 
<span class="hljs-keyword">SET</span> age = <span class="hljs-number">21</span> 
<span class="hljs-keyword">WHERE</span> <span class="hljs-keyword">name</span> = <span class="hljs-string">'Jane Doe'</span>;
</code></pre>
<p>Now, let’s write Python code to update a specific student's age in our <code>Students</code> table.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sqlite3

<span class="hljs-comment"># Use 'with' to connect to the SQLite database</span>
<span class="hljs-keyword">with</span> sqlite3.connect(<span class="hljs-string">'my_database.db'</span>) <span class="hljs-keyword">as</span> connection:
    cursor = connection.cursor()

    <span class="hljs-comment"># SQL command to update a student's age</span>
    update_query = <span class="hljs-string">'''
    UPDATE Students 
    SET age = ? 
    WHERE name = ?;
    '''</span>

    <span class="hljs-comment"># Data for the update</span>
    new_age = <span class="hljs-number">21</span>
    student_name = <span class="hljs-string">'Jane Doe'</span>

    <span class="hljs-comment"># Execute the SQL command with the data</span>
    cursor.execute(update_query, (new_age, student_name))

    <span class="hljs-comment"># Commit the changes to save the update</span>
    connection.commit()

    <span class="hljs-comment"># Print a confirmation message</span>
    print(<span class="hljs-string">f"Updated age for <span class="hljs-subst">{student_name}</span> to <span class="hljs-subst">{new_age}</span>."</span>)
</code></pre>
<p>In this example, we used parameterized queries to prevent SQL injection.</p>
<h3 id="heading-how-to-delete-records-from-the-table">How to Delete Records from the Table</h3>
<p>To remove records from a database, we use the SQL <code>DELETE</code> command. This command allows us to delete one or more rows based on a specified condition.</p>
<p>For example, if we want to delete a student named 'Jane Doe', the SQL command would look like this:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">DELETE</span> <span class="hljs-keyword">FROM</span> Students 
<span class="hljs-keyword">WHERE</span> <span class="hljs-keyword">name</span> = <span class="hljs-string">'Jane Doe'</span>;
</code></pre>
<p>Let’s write Python code to delete a specific student from our <code>Students</code> table using the <code>with</code> statement.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sqlite3

<span class="hljs-comment"># Use 'with' to connect to the SQLite database</span>
<span class="hljs-keyword">with</span> sqlite3.connect(<span class="hljs-string">'my_database.db'</span>) <span class="hljs-keyword">as</span> connection:
    cursor = connection.cursor()

    <span class="hljs-comment"># SQL command to delete a student</span>
    delete_query = <span class="hljs-string">'''
    DELETE FROM Students 
    WHERE name = ?;
    '''</span>

    <span class="hljs-comment"># Name of the student to be deleted</span>
    student_name = <span class="hljs-string">'Jane Doe'</span>

    <span class="hljs-comment"># Execute the SQL command with the data</span>
    cursor.execute(delete_query, (student_name,))

    <span class="hljs-comment"># Commit the changes to save the deletion</span>
    connection.commit()

    <span class="hljs-comment"># Print a confirmation message</span>
    print(<span class="hljs-string">f"Deleted student record for <span class="hljs-subst">{student_name}</span>."</span>)
</code></pre>
<h4 id="heading-important-considerations">Important Considerations</h4>
<ul>
<li><p><strong>Conditions</strong>: Always use the <code>WHERE</code> clause when updating or deleting records to avoid modifying or removing all rows in the table. Without a <code>WHERE</code> clause, the command affects every row in the table.</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1727519069500/f22be4cc-e75f-4492-af01-ed08f31361f3.jpeg" alt="357089 rows affected Meme" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
</li>
<li><p><strong>Backup</strong>: It’s good practice to back up your database before performing updates or deletions, especially in production environments.</p>
</li>
</ul>
<h2 id="heading-how-to-use-transactions">How to Use Transactions</h2>
<p>A transaction is a sequence of one or more SQL operations that are treated as a single unit of work. In the context of a database, a transaction allows you to perform multiple operations that either all succeed or none at all. This ensures that your database remains in a consistent state, even in the face of errors or unexpected issues.</p>
<p>For example, if you are transferring money between two bank accounts, you would want both the debit from one account and the credit to the other to succeed or fail together. If one operation fails, the other should not be executed to maintain consistency.</p>
<h3 id="heading-why-use-transactions">Why Use Transactions?</h3>
<ol>
<li><p><strong>Atomicity</strong>: Transactions ensure that a series of operations are treated as a single unit. If one operation fails, none of the operations will be applied to the database.</p>
</li>
<li><p><strong>Consistency</strong>: Transactions help maintain the integrity of the database by ensuring that all rules and constraints are followed.</p>
</li>
<li><p><strong>Isolation</strong>: Each transaction operates independently of others, preventing unintended interference.</p>
</li>
<li><p><strong>Durability</strong>: Once a transaction is committed, the changes are permanent, even in the event of a system failure.</p>
</li>
</ol>
<h3 id="heading-when-to-use-transactions">When to Use Transactions?</h3>
<p>You should use transactions when:</p>
<ul>
<li><p>Performing multiple related operations that must succeed or fail together.</p>
</li>
<li><p>Modifying critical data that requires consistency and integrity.</p>
</li>
<li><p>Working with operations that can potentially fail, such as financial transactions or data migrations.</p>
</li>
</ul>
<h3 id="heading-how-to-manage-transactions-in-python">How to Manage Transactions in Python</h3>
<p>In SQLite, transactions are managed using the <code>BEGIN</code>, <code>COMMIT</code>, and <code>ROLLBACK</code> commands. However, when using the <code>sqlite3</code> module in Python, you typically manage transactions through the connection object.</p>
<h5 id="heading-starting-a-transaction">Starting a Transaction</h5>
<p>A transaction begins implicitly when you execute any SQL statement. To start a transaction explicitly, you can use the <code>BEGIN</code> command:</p>
<pre><code class="lang-python">cursor.execute(<span class="hljs-string">"BEGIN;"</span>)
</code></pre>
<p>However, it’s usually unnecessary to start a transaction manually, as SQLite starts a transaction automatically when you execute an SQL statement.</p>
<h5 id="heading-how-to-commit-a-transaction">How to Commit a Transaction</h5>
<p>To save all changes made during a transaction, you use the <code>commit()</code> method. This makes all modifications permanent in the database.</p>
<pre><code class="lang-python">connection.commit()
</code></pre>
<p>We have already used the <code>commit()</code> method in the above provided examples.</p>
<h5 id="heading-rolling-back-a-transaction">Rolling Back a Transaction</h5>
<p>If something goes wrong and you want to revert the changes made during a transaction, you can use the <code>rollback()</code> method. This will undo all changes made since the transaction started.</p>
<pre><code class="lang-python">connection.rollback()
</code></pre>
<h3 id="heading-example-of-using-transactions-in-python">Example of Using Transactions in Python</h3>
<p>To illustrate the use of transactions in a real-world scenario, we’ll create a new table called <code>Customers</code> to manage customer accounts. In this example, we’ll assume each customer has a <code>balance</code>. We will add two customers to this table and perform a funds transfer operation between them.</p>
<p>First, let's create the <code>Customers</code> table and insert two customers:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sqlite3

<span class="hljs-comment"># Create the Customers table and add two customers</span>
<span class="hljs-keyword">with</span> sqlite3.connect(<span class="hljs-string">'my_database.db'</span>) <span class="hljs-keyword">as</span> connection:
    cursor = connection.cursor()

    <span class="hljs-comment"># Create Customers table</span>
    create_customers_table = <span class="hljs-string">'''
    CREATE TABLE IF NOT EXISTS Customers (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT NOT NULL UNIQUE,
        balance REAL NOT NULL
    );
    '''</span>
    cursor.execute(create_customers_table)

    <span class="hljs-comment"># Insert two customers</span>
    cursor.execute(
        <span class="hljs-string">"INSERT INTO Customers (name, balance) VALUES (?, ?);"</span>, (<span class="hljs-string">'Ashutosh'</span>, <span class="hljs-number">100.0</span>))
    cursor.execute(
        <span class="hljs-string">"INSERT INTO Customers (name, balance) VALUES (?, ?);"</span>, (<span class="hljs-string">'Krishna'</span>, <span class="hljs-number">50.0</span>))

    connection.commit()
</code></pre>
<p>Now, let’s perform the funds transfer operation between Ashutosh and Krishna:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sqlite3


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">transfer_funds</span>(<span class="hljs-params">from_customer, to_customer, amount</span>):</span>
    <span class="hljs-keyword">with</span> sqlite3.connect(<span class="hljs-string">'my_database.db'</span>) <span class="hljs-keyword">as</span> connection:
        cursor = connection.cursor()

        <span class="hljs-keyword">try</span>:
            <span class="hljs-comment"># Start a transaction</span>
            cursor.execute(<span class="hljs-string">"BEGIN;"</span>)

            <span class="hljs-comment"># Deduct amount from the sender</span>
            cursor.execute(
                <span class="hljs-string">"UPDATE Customers SET balance = balance - ? WHERE name = ?;"</span>, (amount, from_customer))
            <span class="hljs-comment"># Add amount to the receiver</span>
            cursor.execute(
                <span class="hljs-string">"UPDATE Customers SET balance = balance + ? WHERE name = ?;"</span>, (amount, to_customer))

            <span class="hljs-comment"># Commit the changes</span>
            connection.commit()
            print(
                <span class="hljs-string">f"Transferred <span class="hljs-subst">{amount}</span> from <span class="hljs-subst">{from_customer}</span> to <span class="hljs-subst">{to_customer}</span>."</span>)

        <span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e:
            <span class="hljs-comment"># If an error occurs, rollback the transaction</span>
            connection.rollback()
            print(<span class="hljs-string">f"Transaction failed: <span class="hljs-subst">{e}</span>"</span>)


<span class="hljs-comment"># Example usage</span>
transfer_funds(<span class="hljs-string">'Ashutosh'</span>, <span class="hljs-string">'Krishna'</span>, <span class="hljs-number">80.0</span>)
</code></pre>
<p>In this example, we first created a <code>Customers</code> table and inserted two customers, Ashutosh with a balance of ₹100, and Krishna with a balance of ₹50. We then performed a funds transfer of ₹80 from Ashutosh to Krishna. By using transactions, we ensure that both the debit from Ashutosh's account and the credit to Krishna's account are executed as a single atomic operation, maintaining data integrity in the event of any errors. If the transfer fails (for example, due to insufficient funds), the transaction will roll back, leaving both accounts unchanged.</p>
<h2 id="heading-how-to-optimize-sqlite-query-performance-with-indexing">How to Optimize SQLite Query Performance with Indexing</h2>
<p>Indexing is a powerful technique used in databases to improve query performance. An index is essentially a data structure that stores the location of rows based on specific column values, much like an index at the back of a book helps you quickly locate a topic.</p>
<p>Without an index, SQLite has to scan the entire table row by row to find the relevant data, which becomes inefficient as the dataset grows. By using an index, SQLite can jump directly to the rows you need, significantly speeding up query execution.</p>
<h3 id="heading-how-to-populate-the-database-with-fake-data">How to Populate the Database with Fake Data</h3>
<p>To effectively test the impact of indexing, we need a sizable dataset. Instead of manually adding records, we can use the <code>faker</code> library to quickly generate fake data. In this section, we’ll generate 10,000 fake records and insert them into our <code>Students</code> table. This will simulate a real-world scenario where databases grow large, and query performance becomes important.</p>
<p>We will use the <code>executemany()</code> method to insert the records as below:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sqlite3
<span class="hljs-keyword">from</span> faker <span class="hljs-keyword">import</span> Faker

<span class="hljs-comment"># Initialize the Faker library</span>
fake = Faker([<span class="hljs-string">'en_IN'</span>])


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">insert_fake_students</span>(<span class="hljs-params">num_records</span>):</span>
    <span class="hljs-string">"""Generate and insert fake student data into the Students table."""</span>
    fake_data = [(fake.name(), fake.random_int(min=<span class="hljs-number">18</span>, max=<span class="hljs-number">25</span>),
                  fake.email()) <span class="hljs-keyword">for</span> _ <span class="hljs-keyword">in</span> range(num_records)]

    <span class="hljs-comment"># Use 'with' to handle the database connection</span>
    <span class="hljs-keyword">with</span> sqlite3.connect(<span class="hljs-string">'my_database.db'</span>) <span class="hljs-keyword">as</span> connection:
        cursor = connection.cursor()

        <span class="hljs-comment"># Insert fake data into the Students table</span>
        cursor.executemany(<span class="hljs-string">'''
        INSERT INTO Students (name, age, email) 
        VALUES (?, ?, ?);
        '''</span>, fake_data)

        connection.commit()

    print(<span class="hljs-string">f"<span class="hljs-subst">{num_records}</span> fake student records inserted successfully."</span>)


<span class="hljs-comment"># Insert 10,000 fake records into the Students table</span>
insert_fake_students(<span class="hljs-number">10000</span>)
</code></pre>
<p>By running this script, 10,000 fake student records will be added to the <code>Students</code> table. In the next section, we'll query the database and compare the performance of queries with and without indexing.</p>
<h3 id="heading-how-to-query-without-indexes">How to Query Without Indexes</h3>
<p>In this section, we’ll query the <code>Students</code> table without any indexes to observe how SQLite performs when there are no optimizations in place. This will serve as a baseline to compare the performance when we add indexes later.</p>
<p>Without indexes, SQLite performs a full table scan, which means that it must check every row in the table to find matching results. For small datasets, this is manageable, but as the number of records grows, the time taken to search increases dramatically. Let’s see this in action by running a basic <code>SELECT</code> query to search for a specific student by name and measure how long it takes.</p>
<p>First, we’ll query the <code>Students</code> table by looking for a student with a specific name. We’ll log the time taken to execute the query using Python’s <code>time</code> module to measure the performance.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sqlite3
<span class="hljs-keyword">import</span> time


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">query_without_index</span>(<span class="hljs-params">search_name</span>):</span>
    <span class="hljs-string">"""Query the Students table by name without an index and measure the time taken."""</span>

    <span class="hljs-comment"># Connect to the database using 'with'</span>
    <span class="hljs-keyword">with</span> sqlite3.connect(<span class="hljs-string">'my_database.db'</span>) <span class="hljs-keyword">as</span> connection:
        cursor = connection.cursor()

        <span class="hljs-comment"># Measure the start time</span>
        start_time = time.perf_counter_ns()

        <span class="hljs-comment"># Perform a SELECT query to find a student by name</span>
        cursor.execute(<span class="hljs-string">'''
        SELECT * FROM Students WHERE name = ?;
        '''</span>, (search_name,))

        <span class="hljs-comment"># Fetch all results (there should be only one or a few in practice)</span>
        results = cursor.fetchall()

        <span class="hljs-comment"># Measure the end time</span>
        end_time = time.perf_counter_ns()

        <span class="hljs-comment"># Calculate the total time taken</span>
        elapsed_time = (end_time - start_time) / <span class="hljs-number">1000</span>

        <span class="hljs-comment"># Display the results and the time taken</span>
        print(<span class="hljs-string">f"Query completed in <span class="hljs-subst">{elapsed_time:<span class="hljs-number">.5</span>f}</span> microseconds."</span>)
        print(<span class="hljs-string">"Results:"</span>, results)


<span class="hljs-comment"># Example: Searching for a student by name</span>
query_without_index(<span class="hljs-string">'Ojasvi Dhawan'</span>)
</code></pre>
<p>Here’s the output:</p>
<pre><code class="lang-bash">Query completed <span class="hljs-keyword">in</span> 1578.10000 microseconds.
Results: [(104, <span class="hljs-string">'Ojasvi Dhawan'</span>, 21, <span class="hljs-string">'lavanya26@example.com'</span>)]
</code></pre>
<p>By running the above script, you'll see how long it takes to search the <code>Students</code> table without any indexes. For example, if there are 10,000 records in the table, the query might take 1000-2000 microseconds depending on the size of the table and your hardware. This may not seem too slow for a small dataset, but the performance will degrade as more records are added.</p>
<p>We use <code>time.perf_counter_ns()</code> to measure the time taken for the query execution in nanoseconds. This method is highly accurate for benchmarking small time intervals. We convert the time to microseconds(<code>us</code>) for easier readability.</p>
<h3 id="heading-introducing-the-query-plan">Introducing the Query Plan</h3>
<p>When working with databases, understanding how queries are executed can help you identify performance bottlenecks and optimize your code. SQLite provides a helpful tool for this called <code>EXPLAIN QUERY PLAN</code>, which allows you to analyze the steps SQLite takes to retrieve data.</p>
<p>In this section, we’ll introduce how to use <code>EXPLAIN QUERY PLAN</code> to visualize and understand the inner workings of a query—specifically, how SQLite performs a full table scan when no index is present.</p>
<p>Let’s use <code>EXPLAIN QUERY PLAN</code> to see how SQLite retrieves data from the <code>Students</code> table without any indexes. We’ll search for a student by name, and the query plan will reveal the steps SQLite takes to find the matching rows.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sqlite3


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">explain_query</span>(<span class="hljs-params">search_name</span>):</span>
    <span class="hljs-string">"""Explain the query execution plan for a SELECT query without an index."""</span>

    <span class="hljs-keyword">with</span> sqlite3.connect(<span class="hljs-string">'my_database.db'</span>) <span class="hljs-keyword">as</span> connection:
        cursor = connection.cursor()

        <span class="hljs-comment"># Use EXPLAIN QUERY PLAN to analyze how the query is executed</span>
        cursor.execute(<span class="hljs-string">'''
        EXPLAIN QUERY PLAN
        SELECT * FROM Students WHERE name = ?;
        '''</span>, (search_name,))

        <span class="hljs-comment"># Fetch and display the query plan</span>
        query_plan = cursor.fetchall()

        print(<span class="hljs-string">"Query Plan:"</span>)
        <span class="hljs-keyword">for</span> step <span class="hljs-keyword">in</span> query_plan:
            print(step)


<span class="hljs-comment"># Example: Analyzing the query plan for searching by name</span>
explain_query(<span class="hljs-string">'Ojasvi Dhawan'</span>)
</code></pre>
<p>When you run this code, SQLite will return a breakdown of how it plans to execute the query. Here’s an example of what the output might look like:</p>
<pre><code class="lang-bash">Query Plan:
(2, 0, 0, <span class="hljs-string">'SCAN Students'</span>)
</code></pre>
<p>This indicates that SQLite is scanning the entire <code>Students</code> table (a full table scan) to find the rows where the <code>name</code> column matches the provided value (<code>Ojasvi Dhawan</code>). Since there is no index on the <code>name</code> column, SQLite must examine each row in the table.</p>
<h3 id="heading-how-to-create-an-index">How to Create an Index</h3>
<p>Creating an index on a column allows SQLite to find rows more quickly during query operations. Instead of scanning the entire table, SQLite can use the index to jump directly to the relevant rows, significantly speeding up queries—especially those involving large datasets.</p>
<p>To create an index, use the following SQL command:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">INDEX</span> <span class="hljs-keyword">IF</span> <span class="hljs-keyword">NOT</span> <span class="hljs-keyword">EXISTS</span> <span class="hljs-keyword">index</span>-<span class="hljs-keyword">name</span> <span class="hljs-keyword">ON</span> <span class="hljs-keyword">table</span> (<span class="hljs-keyword">column</span>(s));
</code></pre>
<p>In this example, we will create an index on the <code>name</code> column of the <code>Students</code> table. Here’s how you can do it using Python:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sqlite3
<span class="hljs-keyword">import</span> time


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">create_index</span>():</span>
    <span class="hljs-string">"""Create an index on the name column of the Students table."""</span>
    <span class="hljs-keyword">with</span> sqlite3.connect(<span class="hljs-string">'my_database.db'</span>) <span class="hljs-keyword">as</span> connection:
        cursor = connection.cursor()

        <span class="hljs-comment"># SQL command to create an index on the name column</span>
        create_index_query = <span class="hljs-string">'''
        CREATE INDEX IF NOT EXISTS idx_name ON Students (name);
        '''</span>

        <span class="hljs-comment"># Measure the start time</span>
        start_time = time.perf_counter_ns()

        <span class="hljs-comment"># Execute the SQL command to create the index</span>
        cursor.execute(create_index_query)

        <span class="hljs-comment"># Measure the start time</span>
        end_time = time.perf_counter_ns()

        <span class="hljs-comment"># Commit the changes</span>
        connection.commit()

        print(<span class="hljs-string">"Index on 'name' column created successfully!"</span>)

        <span class="hljs-comment"># Calculate the total time taken</span>
        elapsed_time = (end_time - start_time) / <span class="hljs-number">1000</span>

        <span class="hljs-comment"># Display the results and the time taken</span>
        print(<span class="hljs-string">f"Query completed in <span class="hljs-subst">{elapsed_time:<span class="hljs-number">.5</span>f}</span> microseconds."</span>)


<span class="hljs-comment"># Call the function to create the index</span>
create_index()
</code></pre>
<p>Output:</p>
<pre><code class="lang-bash">Index on <span class="hljs-string">'name'</span> column created successfully!
Query completed <span class="hljs-keyword">in</span> 102768.60000 microseconds.
</code></pre>
<p>Even though creating the index takes this long (102768.6 microseconds), it's a one-time operation. You will still get substantial speed-up when running multiple queries. In the following sections, we will query the database again to observe the performance improvements made possible by this index.</p>
<h3 id="heading-how-to-query-with-indexes">How to Query with Indexes</h3>
<p>In this section, we will perform the same <code>SELECT</code> query we executed earlier, but this time we will take advantage of the index we created on the <code>name</code> column of the <code>Students</code> table. We'll measure and log the execution time to observe the performance improvements provided by the index.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sqlite3
<span class="hljs-keyword">import</span> time


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">query_with_index</span>(<span class="hljs-params">student_name</span>):</span>
    <span class="hljs-string">"""Query the Students table using an index on the name column."""</span>
    <span class="hljs-keyword">with</span> sqlite3.connect(<span class="hljs-string">'my_database.db'</span>) <span class="hljs-keyword">as</span> connection:
        cursor = connection.cursor()

        <span class="hljs-comment"># SQL command to select a student by name</span>
        select_query = <span class="hljs-string">'SELECT * FROM Students WHERE name = ?;'</span>

        <span class="hljs-comment"># Measure the execution time</span>
        start_time = time.perf_counter_ns()  <span class="hljs-comment"># Start the timer</span>

        <span class="hljs-comment"># Execute the query with the provided student name</span>
        cursor.execute(select_query, (student_name,))
        result = cursor.fetchall()  <span class="hljs-comment"># Fetch all results</span>

        end_time = time.perf_counter_ns()  <span class="hljs-comment"># End the timer</span>

        <span class="hljs-comment"># Calculate the elapsed time in microseconds</span>
        execution_time = (end_time - start_time) / <span class="hljs-number">1000</span>

        <span class="hljs-comment"># Display results and execution time</span>
        print(<span class="hljs-string">f"Query result: <span class="hljs-subst">{result}</span>"</span>)
        print(<span class="hljs-string">f"Execution time with index: <span class="hljs-subst">{execution_time:<span class="hljs-number">.5</span>f}</span> microseconds"</span>)


<span class="hljs-comment"># Example: Searching for a student by name</span>
query_with_index(<span class="hljs-string">'Ojasvi Dhawan'</span>)
</code></pre>
<p>Here’s what we get in the output:</p>
<pre><code class="lang-bash">Query result: [(104, <span class="hljs-string">'Ojasvi Dhawan'</span>, 21, <span class="hljs-string">'lavanya26@example.com'</span>)]
Execution time with index: 390.70000 microseconds
</code></pre>
<p>We can observe a significant reduction in execution time compared to when the query was performed without an index.</p>
<p>Let’s analyze the query execution plan for the query with the index on the <code>name</code> column of the <code>Students</code> table. If you execute the same script again to explain the query, you’ll get the below output:</p>
<pre><code class="lang-bash">Query Plan:
(3, 0, 0, <span class="hljs-string">'SEARCH Students USING INDEX idx_name (name=?)'</span>)
</code></pre>
<p>The plan now shows that the query uses the index <code>idx_name</code>, significantly reducing the number of rows that need to be scanned, which leads to faster query execution.</p>
<h3 id="heading-comparing-performance-results">Comparing Performance Results</h3>
<p>Now, let's summarize the performance results we obtained when querying with and without indexes.</p>
<h4 id="heading-execution-time-comparison">Execution Time Comparison</h4>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Query Type</td><td>Execution Time (microseconds)</td></tr>
</thead>
<tbody>
<tr>
<td>Without Index</td><td>1578.1</td></tr>
<tr>
<td>With Index</td><td>390.7</td></tr>
</tbody>
</table>
</div><h4 id="heading-performance-improvement-summary">Performance Improvement Summary</h4>
<ul>
<li><p>The query with the index is approximately 4.04 times faster than the query without the index.</p>
</li>
<li><p>The execution time improved by about 75.24% after adding the index.</p>
</li>
</ul>
<h3 id="heading-best-practices-for-using-indexes">Best Practices for Using Indexes</h3>
<p>Indexes can significantly enhance the performance of your SQLite database, but they should be used judiciously. Here are some best practices to consider when working with indexes:</p>
<h4 id="heading-when-and-why-to-use-indexes">When and Why to Use Indexes</h4>
<ol>
<li><p><strong>Frequent Query Columns</strong>: Use indexes on columns that are frequently used in <code>SELECT</code> queries, especially those used in <code>WHERE</code>, <code>JOIN</code>, and <code>ORDER BY</code> clauses. This is because indexing these columns can drastically reduce query execution time.</p>
</li>
<li><p><strong>Uniqueness Constraints</strong>: When you have columns that must hold unique values (like usernames or email addresses), creating an index can enforce this constraint efficiently.</p>
</li>
<li><p><strong>Large Datasets</strong>: For tables with a large number of records, indexes become increasingly beneficial. They enable quick lookups, which is essential for maintaining performance as your data grows.</p>
</li>
<li><p><strong>Composite Indexes</strong>: Consider creating composite indexes for queries that filter or sort by multiple columns. For example, if you often search for students by both <code>name</code> and <code>age</code>, an index on both columns can optimize such queries.</p>
</li>
</ol>
<h4 id="heading-potential-downsides-of-indexes">Potential Downsides of Indexes</h4>
<p>While indexes provide significant advantages, there are some potential downsides:</p>
<ol>
<li><p><strong>Slower Insert/Update Operations</strong>: When you insert or update records in a table with indexes, SQLite must also update the index, which can slow down these operations. This is because each insert or update requires additional overhead to maintain the index structure.</p>
</li>
<li><p><strong>Increased Storage Requirements</strong>: Indexes consume additional disk space. For large tables, the storage cost can be substantial. Consider this when designing your database schema, especially for systems with limited storage resources.</p>
</li>
<li><p><strong>Complex Index Management</strong>: Having too many indexes can complicate database management. It may lead to situations where you have redundant indexes, which can degrade performance rather than enhance it. Regularly reviewing and optimizing your indexes is a good practice.</p>
</li>
</ol>
<p>Indexes are powerful tools for optimizing database queries, but they require careful consideration. Striking a balance between improved read performance and the potential overhead on write operations is key. Here are some strategies for achieving this balance:</p>
<ul>
<li><p><strong>Monitor Query Performance</strong>: Use SQLite’s <code>EXPLAIN QUERY PLAN</code> to analyze how your queries perform with and without indexes. This can help identify which indexes are beneficial and which may be unnecessary.</p>
</li>
<li><p><strong>Regular Maintenance</strong>: Periodically review your indexes and assess whether they are still needed. Remove redundant or rarely used indexes to streamline your database operations.</p>
</li>
<li><p><strong>Test and Evaluate</strong>: Before implementing indexes in a production environment, conduct thorough testing to understand their impact on both read and write operations.</p>
</li>
</ul>
<p>By following these best practices, you can leverage the benefits of indexing while minimizing potential drawbacks, ultimately enhancing the performance and efficiency of your SQLite database.</p>
<h2 id="heading-how-to-handle-errors-and-exceptions">How to Handle Errors and Exceptions</h2>
<p>In this section, we’ll discuss how to handle errors and exceptions when working with SQLite in Python. Proper error handling is crucial for maintaining the integrity of your database and ensuring that your application behaves predictably.</p>
<h3 id="heading-common-errors-in-sqlite-operations">Common Errors in SQLite Operations</h3>
<p>When interacting with an SQLite database, several common errors may arise:</p>
<ol>
<li><p><strong>Constraint Violations</strong>: This occurs when you try to insert or update data that violates a database constraint, such as primary key uniqueness or foreign key constraints. For example, trying to insert a duplicate primary key will trigger an error.</p>
</li>
<li><p><strong>Data Type Mismatches</strong>: Attempting to insert data of the wrong type (for example, inserting a string where a number is expected) can lead to an error.</p>
</li>
<li><p><strong>Database Locked Errors</strong>: If a database is being written to by another process or connection, trying to access it can result in a "database is locked" error.</p>
</li>
<li><p><strong>Syntax Errors</strong>: Mistakes in your SQL syntax will result in errors when you try to execute your commands.</p>
</li>
</ol>
<h3 id="heading-how-to-use-pythons-exception-handling">How to Use Python's Exception Handling</h3>
<p>Python’s built-in <a target="_blank" href="https://blog.ashutoshkrris.in/exception-handling-in-python">exception handling</a> mechanisms (<code>try</code> and <code>except</code>) are essential for managing errors in SQLite operations. By using these constructs, you can catch exceptions and respond appropriately without crashing your program.</p>
<p>Here’s a basic example of how to handle errors when inserting data into the database:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sqlite3


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">add_customer_with_error_handling</span>(<span class="hljs-params">name, balance</span>):</span>
    <span class="hljs-string">"""Add a new customer with error handling."""</span>
    <span class="hljs-keyword">try</span>:
        <span class="hljs-keyword">with</span> sqlite3.connect(<span class="hljs-string">'my_database.db'</span>) <span class="hljs-keyword">as</span> connection:
            cursor = connection.cursor()
            cursor.execute(
                <span class="hljs-string">"INSERT INTO Customers (name, balance) VALUES (?, ?);"</span>, (name, balance))
            connection.commit()
            print(<span class="hljs-string">f"Added customer: <span class="hljs-subst">{name}</span> with balance: <span class="hljs-subst">{balance}</span>"</span>)

    <span class="hljs-keyword">except</span> sqlite3.IntegrityError <span class="hljs-keyword">as</span> e:
        print(<span class="hljs-string">f"Error: Integrity constraint violated - <span class="hljs-subst">{e}</span>"</span>)

    <span class="hljs-keyword">except</span> sqlite3.OperationalError <span class="hljs-keyword">as</span> e:
        print(<span class="hljs-string">f"Error: Operational issue - <span class="hljs-subst">{e}</span>"</span>)

    <span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e:
        print(<span class="hljs-string">f"An unexpected error occurred: <span class="hljs-subst">{e}</span>"</span>)


<span class="hljs-comment"># Example usage</span>
add_customer_with_error_handling(<span class="hljs-string">'Vishakha'</span>, <span class="hljs-number">100.0</span>)  <span class="hljs-comment"># Valid</span>
add_customer_with_error_handling(<span class="hljs-string">'Vishakha'</span>, <span class="hljs-number">150.0</span>)  <span class="hljs-comment"># Duplicate entry</span>
</code></pre>
<p>In this example:</p>
<ul>
<li><p>We catch <code>IntegrityError</code>, which is raised for violations like unique constraints.</p>
</li>
<li><p>We catch <code>OperationalError</code> for general database-related issues (like database locked errors).</p>
</li>
<li><p>We also have a generic <code>except</code> block to handle any unexpected exceptions.</p>
</li>
</ul>
<p>Output:</p>
<pre><code class="lang-bash">Added customer: Vishakha with balance: 100.0
Error: Integrity constraint violated - UNIQUE constraint failed: Customers.name
</code></pre>
<h3 id="heading-best-practices-for-ensuring-database-integrity">Best Practices for Ensuring Database Integrity</h3>
<ol>
<li><p><strong>Use Transactions</strong>: Always use transactions (as discussed in the previous section) when performing multiple related operations. This helps ensure that either all operations succeed or none do, maintaining consistency.</p>
</li>
<li><p><strong>Validate Input Data</strong>: Before executing SQL commands, validate the input data to ensure it meets the expected criteria (for example, correct types, within allowable ranges).</p>
</li>
<li><p><strong>Catch Specific Exceptions</strong>: Always catch specific exceptions to handle different types of errors appropriately. This allows for clearer error handling and debugging.</p>
</li>
<li><p><strong>Log Errors</strong>: Instead of just printing errors to the console, consider logging them to a file or monitoring system. This will help you track issues in production.</p>
</li>
<li><p><strong>Graceful Degradation</strong>: Design your application to handle errors gracefully. If an operation fails, provide meaningful feedback to the user rather than crashing the application.</p>
</li>
<li><p><strong>Regularly Backup Data</strong>: Regularly back up your database to prevent data loss in case of critical failures or corruption.</p>
</li>
<li><p><strong>Use Prepared Statements</strong>: Prepared statements help prevent SQL injection attacks and can also provide better performance for repeated queries.</p>
</li>
</ol>
<h2 id="heading-how-to-export-and-import-data-bonus-section">How to Export and Import Data [Bonus Section]</h2>
<p>In this section, we will learn how to export data from an SQLite database to common formats like CSV and JSON, as well as how to import data into SQLite from these formats using Python. This is useful for data sharing, backup, and integration with other applications.</p>
<h3 id="heading-exporting-data-from-sqlite-to-csv">Exporting Data from SQLite to CSV</h3>
<p>Exporting data to a CSV (Comma-Separated Values) file is straightforward with Python’s built-in libraries. CSV files are widely used for data storage and exchange, making them a convenient format for exporting data.</p>
<p>Here’s how to export data from an SQLite table to a CSV file:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sqlite3
<span class="hljs-keyword">import</span> csv

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">export_to_csv</span>(<span class="hljs-params">file_name</span>):</span>
    <span class="hljs-string">"""Export data from the Customers table to a CSV file."""</span>
    <span class="hljs-keyword">with</span> sqlite3.connect(<span class="hljs-string">'my_database.db'</span>) <span class="hljs-keyword">as</span> connection:
        cursor = connection.cursor()

        <span class="hljs-comment"># Execute a query to fetch all customer data</span>
        cursor.execute(<span class="hljs-string">"SELECT * FROM Customers;"</span>)
        customers = cursor.fetchall()

        <span class="hljs-comment"># Write data to CSV</span>
        <span class="hljs-keyword">with</span> open(file_name, <span class="hljs-string">'w'</span>, newline=<span class="hljs-string">''</span>) <span class="hljs-keyword">as</span> csv_file:
            csv_writer = csv.writer(csv_file)
            csv_writer.writerow([<span class="hljs-string">'ID'</span>, <span class="hljs-string">'Name'</span>, <span class="hljs-string">'Balance'</span>])  <span class="hljs-comment"># Writing header</span>
            csv_writer.writerows(customers)  <span class="hljs-comment"># Writing data rows</span>

        print(<span class="hljs-string">f"Data exported successfully to <span class="hljs-subst">{file_name}</span>."</span>)

<span class="hljs-comment"># Example usage</span>
export_to_csv(<span class="hljs-string">'customers.csv'</span>)
</code></pre>
<h3 id="heading-how-to-export-data-to-json">How to Export Data to JSON</h3>
<p>Similarly, you can export data to a <a target="_blank" href="https://blog.ashutoshkrris.in/a-beginners-guide-to-the-json-module-in-python">JSON</a> (JavaScript Object Notation) file, which is a popular format for data interchange, especially in web applications.</p>
<p>Here’s an example of how to export data to JSON:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> json
<span class="hljs-keyword">import</span> sqlite3


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">export_to_json</span>(<span class="hljs-params">file_name</span>):</span>
    <span class="hljs-string">"""Export data from the Customers table to a JSON file."""</span>
    <span class="hljs-keyword">with</span> sqlite3.connect(<span class="hljs-string">'my_database.db'</span>) <span class="hljs-keyword">as</span> connection:
        cursor = connection.cursor()

        <span class="hljs-comment"># Execute a query to fetch all customer data</span>
        cursor.execute(<span class="hljs-string">"SELECT * FROM Customers;"</span>)
        customers = cursor.fetchall()

        <span class="hljs-comment"># Convert data to a list of dictionaries</span>
        customers_list = [{<span class="hljs-string">'ID'</span>: customer[<span class="hljs-number">0</span>], <span class="hljs-string">'Name'</span>: customer[<span class="hljs-number">1</span>],
                           <span class="hljs-string">'Balance'</span>: customer[<span class="hljs-number">2</span>]} <span class="hljs-keyword">for</span> customer <span class="hljs-keyword">in</span> customers]

        <span class="hljs-comment"># Write data to JSON</span>
        <span class="hljs-keyword">with</span> open(file_name, <span class="hljs-string">'w'</span>) <span class="hljs-keyword">as</span> json_file:
            json.dump(customers_list, json_file, indent=<span class="hljs-number">4</span>)

        print(<span class="hljs-string">f"Data exported successfully to <span class="hljs-subst">{file_name}</span>."</span>)


<span class="hljs-comment"># Example usage</span>
export_to_json(<span class="hljs-string">'customers.json'</span>)
</code></pre>
<h3 id="heading-how-to-import-data-into-sqlite-from-csv">How to Import Data into SQLite from CSV</h3>
<p>You can also import data from a CSV file into an SQLite database. This is useful for populating your database with existing datasets.</p>
<p>Here's how to import data from a CSV file:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> csv
<span class="hljs-keyword">import</span> sqlite3


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">import_from_csv</span>(<span class="hljs-params">file_name</span>):</span>
    <span class="hljs-string">"""Import data from a CSV file into the Customers table."""</span>
    <span class="hljs-keyword">with</span> sqlite3.connect(<span class="hljs-string">'my_database.db'</span>) <span class="hljs-keyword">as</span> connection:
        cursor = connection.cursor()

        <span class="hljs-comment"># Open the CSV file for reading</span>
        <span class="hljs-keyword">with</span> open(file_name, <span class="hljs-string">'r'</span>) <span class="hljs-keyword">as</span> csv_file:
            csv_reader = csv.reader(csv_file)
            next(csv_reader)  <span class="hljs-comment"># Skip the header row</span>

            <span class="hljs-comment"># Insert each row into the Customers table</span>
            <span class="hljs-keyword">for</span> row <span class="hljs-keyword">in</span> csv_reader:
                cursor.execute(
                    <span class="hljs-string">"INSERT INTO Customers (name, balance) VALUES (?, ?);"</span>, (row[<span class="hljs-number">1</span>], row[<span class="hljs-number">2</span>]))

        connection.commit()
        print(<span class="hljs-string">f"Data imported successfully from <span class="hljs-subst">{file_name}</span>."</span>)


<span class="hljs-comment"># Example usage</span>
import_from_csv(<span class="hljs-string">'customer_data.csv'</span>)
</code></pre>
<h3 id="heading-how-to-import-data-into-sqlite-from-json">How to Import Data into SQLite from JSON</h3>
<p>Similarly, importing data from a JSON file is simple. You can read the JSON file and insert the data into your SQLite table.</p>
<p>Here's how to do it:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> json
<span class="hljs-keyword">import</span> sqlite3


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">import_from_json</span>(<span class="hljs-params">file_name</span>):</span>
    <span class="hljs-string">"""Import data from a JSON file into the Customers table."""</span>
    <span class="hljs-keyword">with</span> sqlite3.connect(<span class="hljs-string">'my_database.db'</span>) <span class="hljs-keyword">as</span> connection:
        cursor = connection.cursor()

        <span class="hljs-comment"># Open the JSON file for reading</span>
        <span class="hljs-keyword">with</span> open(file_name, <span class="hljs-string">'r'</span>) <span class="hljs-keyword">as</span> json_file:
            customers_list = json.load(json_file)

            <span class="hljs-comment"># Insert each customer into the Customers table</span>
            <span class="hljs-keyword">for</span> customer <span class="hljs-keyword">in</span> customers_list:
                cursor.execute(<span class="hljs-string">"INSERT INTO Customers (name, balance) VALUES (?, ?);"</span>, (customer[<span class="hljs-string">'Name'</span>], customer[<span class="hljs-string">'Balance'</span>]))

        connection.commit()
        print(<span class="hljs-string">f"Data imported successfully from <span class="hljs-subst">{file_name}</span>."</span>)


<span class="hljs-comment"># Example usage</span>
import_from_json(<span class="hljs-string">'customer_data.json'</span>)
</code></pre>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>And that’s a wrap! This guide has introduced you to the fundamentals of working with SQLite in Python, covering everything from setting up your environment to querying and manipulating data, as well as exporting and importing information. I hope you found it helpful and that it has sparked your interest in using SQLite for your projects.</p>
<p>Now it's time to put your newfound knowledge into practice! I encourage you to create your project using SQLite and Python. Whether it’s a simple application for managing your library, a budgeting tool, or something unique, the possibilities are endless.</p>
<p>Once you’ve completed your project, share it on Twitter and tag me! I’d love to see what you’ve created and celebrate your accomplishments.</p>
<p>You can find all the code from this tutorial on <a target="_blank" href="https://github.com/ashutoshkrris/sqlite-tutorial">GitHub</a>. Thank you for following along, and happy coding!</p>
<blockquote>
<p>Generate Table of Contents for your freeCodeCamp articles for free using the <a target="_blank" href="https://toc-generator.ashutoshkrris.in/freecodecamp">TOC Generator</a> tool.</p>
</blockquote>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use SQLite with Python ]]>
                </title>
                <description>
                    <![CDATA[ Databases are a crucial component in software development. After all, we need to collect data in a location where we can digitally access it for reading, writing, updating, and deleting. In this tutorial, you'll learn how to use SQLite with Python. L... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/sqlite-python-beginners-tutorial/</link>
                <guid isPermaLink="false">66b8dd3b19f41bae75f28f4a</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ SQLite ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Eesa Zahed ]]>
                </dc:creator>
                <pubDate>Tue, 21 Feb 2023 21:41:41 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/02/218187404-b5da9bc5-a6aa-446f-a8d5-5805344d091e.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Databases are a crucial component in software development. After all, we need to collect data in a location where we can digitally access it for reading, writing, updating, and deleting.</p>
<p>In this tutorial, you'll learn how to use SQLite with Python. Learning SQLite is a great way to learn how databases operate and how to perform basic CRUD (create, read, update, delete) operations. </p>
<p>Many software developer positions involve working with databases, and if you ever consider creating a full-scale application (such as a social media app or an online game), you'll definitely need a database too. </p>
<p>This tutorial will explain many basic concepts and simple operations, so that you can understand how to work with databases better.</p>
<h2 id="heading-what-is-sqlite">What is SQLite?</h2>
<p>SQLite is an embedded SQL (Structured Query Language) database engine library that works with many languages. </p>
<p>According to the <a target="_blank" href="https://www.sqlite.org/arch.html">official website</a>, SQL text is compiled into bytecode, which is then run by a virtual machine. Therefore, it is extremely fast and can efficiently handle complex queries.</p>
<p>A SQLite database is stored as a disk file, similar to a CSV (comma-separated values) file. But SQLite has many advantages over using a CSV file:</p>
<ul>
<li>It is written using C. C is a statically-typed, compiled language which is much faster than most languages, including Python.</li>
<li>It’s lightweight, so it performs better and faster than reading from a CSV file.</li>
<li>It’s easy to set up</li>
<li>It can handle more complex queries.</li>
<li>It’s more useful to learn, in case you are ever tasked with using SQL or MySQL in the future.</li>
</ul>
<h2 id="heading-how-to-setup-sqlite">How to Setup SQLite</h2>
<p>Here is an example of using SQLite with Python. I’m using <a target="_blank" href="https://replit.com">Replit’s online IDE</a>, but you are welcome to follow along on any IDE you like. </p>
<p>First, I’ll create a Python project with a <code>main.py</code> file. I’ll be using CS50’s SQL library, which you can install by running <code>pip3 install cs50</code>.</p>
<p>The first step is to create a database.db file in the root directory, which you can do by entering the following command in the terminal:</p>
<pre><code>touch database.db
</code></pre><p>At this point, the following code should be added to main.py:</p>
<pre><code><span class="hljs-keyword">from</span> cs50 <span class="hljs-keyword">import</span> SQL

db = SQL(<span class="hljs-string">"sqlite:///database.db"</span>)
</code></pre><h3 id="heading-how-to-create-a-database-table">How to create a database table</h3>
<p>The next step is to create a table in the database. SQL stores data in tables, which are similar to tables found in Excel or Google Sheets. The code for this is:</p>
<pre><code>db.execute(<span class="hljs-string">"CREATE TABLE IF NOT EXISTS users (name TEXT, age NUMBER, fav_food STRING)"</span>)
</code></pre><p>To break this down, db is the database that the data is written to. Next, a command gets executed. If the table <code>users</code> doesn’t exist, create a table with the name users, with the column names <code>name</code>, <code>age</code>, and <code>fav_food</code>, with the data types for each value specified.</p>
<h3 id="heading-how-to-write-to-the-database">How to write to the database</h3>
<p>You can use the INSERT operation to add a user.</p>
<pre><code>db.execute(<span class="hljs-string">"INSERT INTO users (name, age, fav_food) VALUES(?, ?, ?)"</span>, <span class="hljs-string">"eesa"</span>, <span class="hljs-number">14</span>, <span class="hljs-string">"pizza"</span>)
</code></pre><p>The value “eesa” gets inserted into the name column, the value 14 is inserted into the age column, and the value “pizza” is inserted into the fav_food column.</p>
<p>The code for adding another user (in this case, Bob), would be this:</p>
<pre><code>db.execute(<span class="hljs-string">"INSERT INTO users (name, age, fav_food) VALUES(?, ?, ?)"</span>, <span class="hljs-string">"bob"</span>, <span class="hljs-number">20</span>, <span class="hljs-string">"burgers"</span>)
</code></pre><h3 id="heading-how-to-read-from-the-database">How to read from the database</h3>
<p>After this, we can attempt to read all the users from the database. You can do this by running the following code.</p>
<pre><code>people = db.execute(<span class="hljs-string">"SELECT * FROM users"</span>)
print(people) # [{<span class="hljs-string">'name'</span>: <span class="hljs-string">'eesa'</span>, <span class="hljs-string">'age'</span>: <span class="hljs-number">14</span>, <span class="hljs-string">'fav_food'</span>: <span class="hljs-string">'pizza'</span>}]
</code></pre><p>The code above is fairly straightforward. The * in the SELECT statement selects everything that’s in the database.</p>
<p>To only select specific values, you can use the DISTINCT statement. Say for example, you only want the favorite food of each user. You can do this by running the following code:</p>
<pre><code>people = db.execute(<span class="hljs-string">"SELECT DISTINCT fav_food FROM users"</span>)
print(people)
</code></pre><p>You can also separate values using commas in a SELECT DISTINCT query:</p>
<pre><code>people = db.execute(<span class="hljs-string">"SELECT DISTINCT age, fav_food FROM users"</span>)
print(people)
</code></pre><p>What if we wanted to just read the data for Bob, and ignore everyone else? You can do this by using the SQL WHERE Clause:</p>
<pre><code>people = db.execute(<span class="hljs-string">"SELECT * FROM users WHERE name='bob'"</span>)
print(people)
</code></pre><p>How about for more complex queries? You can do this using the AND, OR and NOT syntax. You can separate WHERE clauses with these keywords for more complex queries.</p>
<pre><code>people = db.execute(<span class="hljs-string">"SELECT * FROM users WHERE name='bob' AND age=20"</span>)
print(people)
</code></pre><p>This will print out the data for Bob, because Bob is 20. </p>
<h3 id="heading-how-to-update-a-row-in-the-database">How to update a row in the database</h3>
<p>To update a row, you can use the UPDATE statement like this:</p>
<pre><code>db.execute(<span class="hljs-string">"UPDATE users SET fav_food='shawarma' WHERE name='eesa'"</span>)
</code></pre><h3 id="heading-how-to-delete-a-row-in-the-database">How to delete a row in the database</h3>
<p>To delete a row, use the DELETE Syntax (as you might’ve guessed). It looks like this:</p>
<pre><code>db.execute(<span class="hljs-string">"DELETE FROM users WHERE name='bob'"</span>) # goodbye bob

people = db.execute(<span class="hljs-string">"SELECT * FROM users"</span>)
print(people) # [{<span class="hljs-string">'name'</span>: <span class="hljs-string">'eesa'</span>, <span class="hljs-string">'age'</span>: <span class="hljs-number">14</span>, <span class="hljs-string">'fav_food'</span>: <span class="hljs-string">'shawarma'</span>}]
</code></pre><p>To delete all the rows in the table, just remove the WHERE clause:</p>
<pre><code>db.execute(<span class="hljs-string">"DELETE FROM users"</span>) # :(

people = db.execute(<span class="hljs-string">"SELECT * FROM users"</span>)
print(people) # []
</code></pre><h2 id="heading-conclusion">Conclusion</h2>
<p>And that’s it for now. For more information on SQLite, I'd recommend checking out the <a target="_blank" href="https://docs.python.org/3/library/sqlite3.html">official documentation</a>. I wish you the best in creating amazing things!</p>
<p>Feel free to check out my <a target="_blank" href="https://github.com/eesazahed">GitHub</a> and <a target="_blank" href="https://replit.com/@eesazahed">Replit</a> to view my projects.</p>
<p>If you'd like to reach out, my email address is eszhd1 (at) gmail.com</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Build a Node.js Database using Prisma and SQLite ]]>
                </title>
                <description>
                    <![CDATA[ Lately I've been seeing many tweets and articles about Prisma. It's a modern ORM (Object-Relational-Mapping tool) that works with Node.jsand TypeScript. Yes, this library will help you build and manage your Node.js database – and it's compatible with... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/build-nodejs-database-using-prisma-orm/</link>
                <guid isPermaLink="false">66bb9200a5fd14123a8b4a34</guid>
                
                    <category>
                        <![CDATA[ database ]]>
                    </category>
                
                    <category>
                        <![CDATA[ node js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ SQLite ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Gaël Thomas ]]>
                </dc:creator>
                <pubDate>Wed, 11 Aug 2021 15:24:42 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/08/manage-node-js-database-prisma-orm.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Lately I've been seeing many tweets and articles about <a target="_blank" href="https://www.prisma.io/">Prisma</a>. It's a modern <a target="_blank" href="https://blog.bitsrc.io/what-is-an-orm-and-why-you-should-use-it-b2b6f75f5e2a">ORM</a> (Object-Relational-Mapping tool) that works with Node.jsand TypeScript.</p>
<p>Yes, this library will help you build and manage your Node.js database – and it's compatible with TypeScript! It will generate all the types of your entities automatically.</p>
<p>The schema definition is easy to read by humans – no more headache there. You will see how that works in the coming sections.</p>
<p>Also, the ORM works well with Next.js, GraphQL, Nest.Js, Express.js, Apollo, and Hapi.</p>
<p>To summarize, Prisma is a modern ORM that plays nice with all the trending tech stacks.</p>
<p>That is why I decided to try it and to replace my previous database management library: <a target="_blank" href="https://typeorm.io/">TypeORM</a>.</p>
<blockquote>
<p>"Prisma helps app developers build faster and make fewer errors with an open source ORM for PostgreSQL, MySQL and SQLite." – <a target="_blank" href="https://www.prisma.io/">Prisma homepage</a></p>
</blockquote>
<h2 id="heading-lets-build-a-simple-twitter-database-using-node-prisma-and-sqlite">Let's build a simple Twitter database using Node, Prisma, and SQLite</h2>
<p>Time to practice. I will show you how to build your first Node.js database using Prisma. To keep this introduction accessible, we will use Node with SQLite.</p>
<p>SQLite is a self-contained database engine. This means that you don't need to configure a database on your computer. The project will run by itself if you follow the steps of this tutorial.</p>
<p>If, in the future, you want to use Prisma with a PostgreSQL database, here is a <a target="_blank" href="https://herewecode.io/blog/create-a-postgresql-database-using-docker-compose/">tutorial on creating a PostgreSQL database using Docker-Compose</a>.</p>
<h3 id="heading-prerequisites">Prerequisites</h3>
<ul>
<li><strong>Node.js (12.2 or higher)</strong></li>
</ul>
<p>Before getting started, take the time to double-check if you have version 12.2 or higher of <a target="_blank" href="https://nodejs.org/en/">Node.js</a>. If you don't, just update your Node before starting the next section.</p>
<blockquote>
<p><strong>Note:</strong> If you want to check your Node.js version, you can type: <code>node -v</code> in a terminal. The output will be the version.</p>
</blockquote>
<ul>
<li><strong>Basic SQL knowledge</strong></li>
</ul>
<p>Even though I'm taking a simple approach to this new library, I recommend that you have basic SQL knowledge to fully understand the tutorial.</p>
<blockquote>
<p><strong>Note:</strong> You don't need to be an expert! Only the basics like creating a table and making some requests are essential here.</p>
</blockquote>
<h2 id="heading-how-to-set-up-a-basic-twitter-project">How to Set Up a Basic Twitter Project</h2>
<p>First, you need to create a new folder for this project and move into it:</p>
<pre><code class="lang-shell">$ mkdir minimalistic-twitter
$ cd minimalistic-twitter
</code></pre>
<p>Then, we will install all the mandatory dependencies such as TypeScript and Prisma.</p>
<pre><code class="lang-shell">$ npm init -y
$ npm install prisma typescript ts-node @types/node --save-dev
$ npm install @prisma/client
</code></pre>
<p>From now, you should see a <code>node_modules</code> folder and a <code>package.json</code> file in your repository.</p>
<p>Before moving on to the Prisma initialization, the last configuration step is to create a configuration for TypeScript at the repository root.</p>
<p>To do so, you can create a <code>tsconfig.json</code> and paste the following configuration:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"compilerOptions"</span>: {
    <span class="hljs-attr">"sourceMap"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">"outDir"</span>: <span class="hljs-string">"dist"</span>,
    <span class="hljs-attr">"strict"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">"lib"</span>: [<span class="hljs-string">"esnext"</span>],
    <span class="hljs-attr">"esModuleInterop"</span>: <span class="hljs-literal">true</span>
  }
}
</code></pre>
<p>There we go! It's time to use Prisma in our project. In the <code>minimalistic-twitter</code> folder, you can use the following command to prompt the Prisma help output.</p>
<pre><code class="lang-shell">$ npx prisma
</code></pre>
<p>Now, the last step before building our minimalistic Twitter app is to initialize the database configuration.</p>
<p>We will use the <code>init</code> command but with a <code>--datasource-provider</code> parameter to set the database type. Otherwise, by default, <code>init</code> will create a PostgreSQL database.</p>
<pre><code class="lang-shell">$ npx prisma init --datasource-provider sqlite
</code></pre>
<p>When the command finishes executing, you should find in your repository a <code>.env</code> file and a <code>prisma</code> folder with a <code>schema.prisma</code> file inside of it.</p>
<p>The <code>schema.prisma</code> file contains all the instructions to connect to your database. Later it will also include the instructions to generate your database tables.</p>
<p>The <code>.env</code> file contains all the environment variable that your project needs to run. For Prisma, the only variable is <code>DATABASE_URL</code>. Its value is set to <code>./dev.db</code> .</p>
<p>The <code>dev.db</code> file will be the self-contained database file.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/Screenshot-2021-08-07-at-23.56.14.png" alt="Project tree after the project initialization" width="600" height="400" loading="lazy">
<em>Project tree after the project initialization</em></p>
<p>If you have the same output, congrats, it means that your project is ready! 🎉</p>
<h2 id="heading-how-to-build-our-first-model-user">How to Build Our First Model – User</h2>
<p>Our basic Twitter database will consist of two main entities:</p>
<ul>
<li>A user entity with the user information and its tweets</li>
<li>A tweet entity with the tweet content and its author</li>
</ul>
<p>First, we'll focus on user entity creation. Each of them has:</p>
<ul>
<li>an id</li>
<li>a unique email (two users can't have the same email)</li>
<li>a username</li>
<li>a list of tweets</li>
</ul>
<p>With Prisma, if we want to define a new schema (model), we need to do it in the <code>schema.prisma</code> file.</p>
<p>To define an entity, we will use the <code>model</code> instruction as below. You can reproduce it after the database connection instruction in your <code>schema.prisma</code> file.</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// After the database connection</span>

model User {
  <span class="hljs-comment">// We set an `id` variable</span>
  <span class="hljs-comment">// With an `Int` type (number)</span>
  <span class="hljs-comment">// Then, we set the Prisma decorators:</span>
  <span class="hljs-comment">// - @id (because it's an ID)</span>
  <span class="hljs-comment">// - @default(autoincrement()) (default value is auto-incremented)</span>
  id Int <span class="hljs-meta">@id</span> <span class="hljs-meta">@default</span>(autoincrement())

  <span class="hljs-comment">// We set an `email` variable</span>
  <span class="hljs-comment">// With a `String` type</span>
  <span class="hljs-comment">// Then, we set the Prisma decorator:</span>
  <span class="hljs-comment">// - @unique (because we want the user to be unique</span>
  <span class="hljs-comment">// based on the email - two users can't have the same)</span>
  email <span class="hljs-built_in">String</span> <span class="hljs-meta">@unique</span>

  <span class="hljs-comment">// We set a `username` variable</span>
  <span class="hljs-comment">// With a `String` type</span>
  username <span class="hljs-built_in">String</span>

  <span class="hljs-comment">// We set a `tweets` variable</span>
  <span class="hljs-comment">// With a `Tweet[]` type (one-to-many relationship)</span>
  <span class="hljs-comment">// Because each user can have between</span>
  <span class="hljs-comment">// 0 and an infinite number of tweets</span>
  tweets Tweet[]
}
</code></pre>
<p>As you might notice, we don't have the <code>Tweet</code> model yet. It will be our next step.</p>
<h2 id="heading-how-to-build-our-second-model-tweet">How to Build Our Second Model – Tweet</h2>
<p>Now that we have users, we need tweets. Let's follow the same process as before, but this time for the <code>Tweet</code> entity.</p>
<p>Each of them has:</p>
<ul>
<li>an id</li>
<li>a creation date</li>
<li>a text</li>
<li>an userId (tweet's author)</li>
</ul>
<p>Below, you will find the entity. You can reproduce it after the <code>User</code> model declaration in your <code>schema.prisma</code> file.</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// After the database connection</span>

<span class="hljs-comment">// After the User model</span>

model Tweet {
  <span class="hljs-comment">// We set an `id` variable</span>
  <span class="hljs-comment">// With an `Int` type (number)</span>
  <span class="hljs-comment">// Then, we set the Prisma decorators:</span>
  <span class="hljs-comment">// - @id (because it's an ID)</span>
  <span class="hljs-comment">// - @default(autoincrement()) (default value is auto-incremented)</span>
  id Int <span class="hljs-meta">@id</span> <span class="hljs-meta">@default</span>(autoincrement())

  <span class="hljs-comment">// Save the tweet creation time</span>
  createdAt DateTime <span class="hljs-meta">@default</span>(now())

  <span class="hljs-comment">// We set a `text` variable</span>
  <span class="hljs-comment">// With a `String` type</span>
  text <span class="hljs-built_in">String</span>

  <span class="hljs-comment">// We set a `userId` variable</span>
  <span class="hljs-comment">// With an `Int` type (number)</span>
  <span class="hljs-comment">// It will link the `id` of the `User` model</span>
  userId Int

  <span class="hljs-comment">// We set a `user` variable</span>
  <span class="hljs-comment">// With a `User` type (many-to-one relationship)</span>
  <span class="hljs-comment">// Because each tweet has an author</span>
  <span class="hljs-comment">// This author is a `User`</span>
  <span class="hljs-comment">// We link the `User` to a `Tweet` based on:</span>
  <span class="hljs-comment">// - the `userId` in the `Tweet` model</span>
  <span class="hljs-comment">// - the `id` in the `User` model</span>
  user User <span class="hljs-meta">@relation</span>(fields: [userId], references: [id])
}
</code></pre>
<h2 id="heading-how-to-generate-our-first-database-migration">How to Generate our First Database Migration</h2>
<p>The first thing we need to do before using our database is to generate it. To do so, we will use another command of the Prisma CLI. This command will allow us to create migrations.</p>
<p>If we have a look at the documentation about the <code>migrate</code> command, we'll see the following:</p>
<blockquote>
<p>"Prisma Migrate is an imperative database schema migration tool that enables you to: <strong>Keep your database schema in sync with your Prisma schema as it evolves _and m_aintain existing data in your database</strong>." – <a target="_blank" href="https://www.prisma.io/docs/concepts/components/prisma-schema/">Prisma migrate documentation</a></p>
</blockquote>
<p>The idea here is to save our first database implementation. You can do it by typing the command below in your terminal:</p>
<pre><code class="lang-shell">npx prisma migrate dev --name initialize
</code></pre>
<p><strong>Note:</strong> You can enter the name of your choice after the <code>--name</code> parameter. Keep in mind that the migration name is helpful to remember the changes you made.</p>
<p>If your migration command is successful, it means that all the instructions in <code>schema.prisma</code> are correct. ✅</p>
<p>Your project tree should now be similar to the image below (except for the migration hash).</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/Screenshot-2021-08-08-at-00.41.22.png" alt="Project tree after the migration generation" width="600" height="400" loading="lazy">
<em>Project tree after the migration generation</em></p>
<p><strong>Note:</strong> In the <code>migration.sql</code> file, you will find the SQL queries to generate your database.</p>
<p>Your database is ready! 🚀 It's time to try it, add some users, and let them tweet.</p>
<h2 id="heading-how-to-test-our-node-js-sqlite-project">How to Test our Node JS SQLite Project</h2>
<p>So, will the users now be able to tweet? Let's try to run some queries on our database. We'll create an <code>index.ts</code> file at the repository root, and we'll write some instructions into it.</p>
<p>First, we need to import and initialize the database connection. Based on the <a target="_blank" href="https://www.prisma.io/docs/getting-started/quickstart/">Prisma Quickstart documentation</a>, we create a <code>prisma</code> variable to interact with the database and a function to write our test code:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { PrismaClient } <span class="hljs-keyword">from</span> <span class="hljs-string">"@prisma/client"</span>;

<span class="hljs-keyword">const</span> prisma = <span class="hljs-keyword">new</span> PrismaClient();

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">main</span>(<span class="hljs-params"></span>) </span>{}

main()
  .catch(<span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
    <span class="hljs-keyword">throw</span> e;
  })
  .finally(<span class="hljs-keyword">async</span> () =&gt; {
    <span class="hljs-keyword">await</span> prisma.$disconnect();
  });
</code></pre>
<p>We're ready to fill the <code>main</code> function with some instructions.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { PrismaClient } <span class="hljs-keyword">from</span> <span class="hljs-string">"@prisma/client"</span>;

<span class="hljs-keyword">const</span> prisma = <span class="hljs-keyword">new</span> PrismaClient();

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">main</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// We create a new user</span>
  <span class="hljs-keyword">const</span> newUser = <span class="hljs-keyword">await</span> prisma.user.create({
    data: {
      email: <span class="hljs-string">"hello@herewecode.io"</span>,
      username: <span class="hljs-string">"gaelgthomas"</span>, <span class="hljs-comment">// &lt;- it's also my Twitter username 😄</span>
    },
  });

  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"New User:"</span>);
  <span class="hljs-built_in">console</span>.log(newUser);

  <span class="hljs-comment">// We create a new tweet and we link it to our new user</span>
  <span class="hljs-keyword">const</span> firstTweet = <span class="hljs-keyword">await</span> prisma.tweet.create({
    data: {
      text: <span class="hljs-string">"Hello world!"</span>,
      userId: newUser.id,
    },
  });

  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"First tweet:"</span>);
  <span class="hljs-built_in">console</span>.log(firstTweet);

  <span class="hljs-comment">// We fetch the new user again (by its unique email address)</span>
  <span class="hljs-comment">// and we ask to fetch its tweets at the same time</span>
  <span class="hljs-keyword">const</span> newUserWithTweets = <span class="hljs-keyword">await</span> prisma.user.findUnique({
    where: {
      email: <span class="hljs-string">"hello@herewecode.io"</span>,
    },
    include: { tweets: <span class="hljs-literal">true</span> },
  });

  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"User object with Tweets:"</span>);
  <span class="hljs-built_in">console</span>.dir(newUserWithTweets);
}

main()
  .catch(<span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
    <span class="hljs-keyword">throw</span> e;
  })
  .finally(<span class="hljs-keyword">async</span> () =&gt; {
    <span class="hljs-keyword">await</span> prisma.$disconnect();
  });
</code></pre>
<p><strong>Note:</strong> If you want to discover the different instructions you can use, a good Prisma documentation page is <a target="_blank" href="https://www.prisma.io/docs/concepts/components/prisma-client/crud">the CRUD one</a>.</p>
<p>Time to run the <code>index.ts</code> file.</p>
<p>Before doing it, open your <code>package.json</code> file and search for the <code>scripts</code> section. You will need to add a command to start the project using <code>ts-node</code>.</p>
<p>If you want, you can replace your <code>scripts</code> section with the following code:</p>
<pre><code class="lang-json"><span class="hljs-string">"scripts"</span>: {
  <span class="hljs-attr">"dev"</span>: <span class="hljs-string">"ts-node ./index.ts"</span>,
  <span class="hljs-attr">"test"</span>: <span class="hljs-string">"echo \"Error: no test specified\" &amp;&amp; exit 1"</span>
},
</code></pre>
<p>Then, in your terminal, you can type the command below and read the output to see if everything is working well:</p>
<pre><code class="lang-shell">$ npm run dev
</code></pre>
<p><strong>Note</strong>: In the command above, we run the dev script from our package.json.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/Screenshot-2021-08-08-at-01.04.59.png" alt="NPM test output using Prisma" width="600" height="400" loading="lazy">
<em>NPM test output using Prisma</em></p>
<p>It's working! You got your first user and tweet. 👏 Now that you've set up your first database using Prisma, you can add some features to it. Here are some ideas:</p>
<ul>
<li>add more information in the User entity (birthday, address, biography, and so on)</li>
<li>add a like system (each tweet can have likes, each user can have a liked tweet list)</li>
</ul>
<h3 id="heading-the-code-is-available-on-github-node-js-with-prisma-and-sqlite"><strong>The Code is available on Github – Node JS with Prisma and SQLite</strong></h3>
<p>If you want to get the complete code, you can find it on my GitHub.</p>
<p><strong>-&gt;</strong> <a target="_blank" href="https://github.com/gaelgthomas/prisma-sqlite-example">GitHub: Prisma SQLite example</a></p>
<p><strong>Thanks for reading until the end!</strong></p>
<p>I hope you will use Prisma in one of your next projects. 🎉</p>
<p>I'm starting to tweet more consistently. If you want to get more tips and resources about web programming -&gt; <a target="_blank" href="https://twitter.com/gaelgthomas">Find me on my Twitter 🐦</a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Python SQL – How to use the SQLite, MySQL, and PostgreSQL Databases with Python ]]>
                </title>
                <description>
                    <![CDATA[ By Daniel Chae One of my greatest joys as a developer is learning how different technologies intersect.  Over the years I've had the opportunity to work with different types of software and tools. Of the many tools I've used, Python and Structured Qu... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/python-sql-how-to-use-sql-databases-with-python/</link>
                <guid isPermaLink="false">66d45e0ad1ffc3d3eb89ddc3</guid>
                
                    <category>
                        <![CDATA[ database ]]>
                    </category>
                
                    <category>
                        <![CDATA[ MySQL ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ SQL ]]>
                    </category>
                
                    <category>
                        <![CDATA[ SQLite ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 25 Mar 2021 19:38:59 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/03/max-duzij-qAjJk-un3BI-unsplash-1.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Daniel Chae</p>
<p>One of my greatest joys as a developer is learning how different technologies intersect. </p>
<p>Over the years I've had the opportunity to work with different types of software and tools. Of the many tools I've used, Python and Structured Query Language (SQL) are two of my favorites. </p>
<p>In this article I'm going to share with you how Python and the different SQL databases interact. </p>
<p>I'll talk about the most popular databases, SQLite, MySQL, and PostgreSQL. I'll explain the key differences of each database and the corresponding use cases. And I'll end the article with some Python code. </p>
<p>The code will show you how to write a SQL query to pull data from a PostgreSQL database and store the data in a pandas data frame.</p>
<p><em>If you aren't familiar with relational databases (RDBMS), I suggest you check out Sameer's article on basic RDBMS terminology <a target="_blank" href="https://www.freecodecamp.org/news/sql-and-databases-explained-in-plain-english/">here</a>. The rest of the article will use terms referenced in Sameer's article.</em> </p>
<h2 id="heading-popular-sql-databases">Popular SQL Databases</h2>
<h3 id="heading-sqlite">SQLite</h3>
<p>SQLite is best known for being an integrated database. This means that you don't have to install an extra application or use a separate server to run the database. </p>
<p>If you're creating an MVP or don't need a ton of data storage space, you'll want to go with a SQLite database. </p>
<p>The pros are that you can move faster with a SQLite database relative to MySQL and PostgreSQL. That said, you'll be stuck with limited functionality. You won't be able to customize features or add a ton of multi-user functionality.</p>
<h3 id="heading-mysqlpostgresql">MySQL/PostgreSQL</h3>
<p>There are distinct differences between MySQL and PostgreSQL. That said, given the context of the article, they fit into a similar category. </p>
<p>Both database types are great for enterprise solutions. If you need to scale fast, MySQL and PostgreSQL are your best bet. They'll provide long-term infrastructure and bolster your security. </p>
<p>Another reason they're great for enterprises is that they can handle high performance activities. Longer insert, update, and select statements need a lot of computing power. You'll be able to write those statements with less latency than what a SQLite database would give you.</p>
<h2 id="heading-why-connect-python-and-a-sql-database">Why Connect Python and a SQL Database?</h2>
<p>You might be wondering, "why should I care about connecting Python and a SQL database?"</p>
<p>There are many use cases for when someone would want to connect Python to a SQL database. As I mentioned earlier, you might be working on a web application. In this case, you'd need to connect a SQL database so you can store the data coming from the web application. </p>
<p>Perhaps you work in data engineering and you need to build an automated ETL pipeline. Connecting Python to a SQL database will allow you to use Python for its automation capabilities. You'll also be able to communicate between different data sources. You won't have to switch between different programming languages. </p>
<p>Connecting Python and a SQL database will also make your data science work more convenient. You'll be able to use your Python skills to manipulate data from a SQL database. You won't need a CSV file.</p>
<h2 id="heading-how-python-and-sql-databases-connect">How Python and SQL Databases Connect</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/Untitled-design-1-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Python and SQL databases connect through custom Python libraries. You can import these libraries into your Python script. </p>
<p>Database-specific Python libraries serve as supplemental instructions. These instructions guide your computer on how it can interact with your SQL database. Otherwise, your Python code will be a foreign language to the database you're trying to connect to.</p>
<h3 id="heading-how-to-setup-the-project">How to Setup the Project</h3>
<p>Let's take a PostgreSQL database, AWS Redshift, for example. First, you'll want to import the psycopg library. It's a universal Python library for PostgreSQL databases. </p>
<pre><code class="lang-setup">#Library for connecting to AWS Redshift
import psycopg

#Library for reading the config file, which is in JSON
import json

#Data manipulation library
import pandas as pd
</code></pre>
<p>You'll notice we also imported the JSON and pandas libraries. We imported JSON because creating a JSON config file is a secure way to store your database credentials. We don't want anyone else eyeing those! </p>
<p>The pandas library will enable you to use all of pandas' statistical capabilities for your Python script. In this instance, the library will enable Python to store the data your SQL query returns into a data frame. </p>
<p>Next, you'll want to access your config file. The <code>json.load()</code> function reads the JSON file so you can access your database credentials in the next step.</p>
<p>```setup (continued)
config_file = open(r"C:\Users\yourname\config.json")
config = json.load(config_file)</p>
<pre><code>
Now that your Python script can access your <span class="hljs-built_in">JSON</span> config file, you<span class="hljs-string">'ll want to create a database connection. You'</span>ll need to read and use the credentials <span class="hljs-keyword">from</span> your config file:
</code></pre><p>con = psycopg2.connect(dbname= "db_name", host=config[hostname], port = config["port"],user=config["user_id"], password=config["password_key"])
cur = con.cursor()</p>
<pre><code>
You just created a database connection! When you imported the psycopg library, you translated the Python code you wrote above to speak to the PostgreSQL database (AWS Redshift). 

In it <span class="hljs-keyword">of</span> itself, AWS Redshift would not understand the above code. But because you imported the psycopg library, you now speak a language AWS Redshift can understand. 

The nice thing about Python is that it has libraries <span class="hljs-keyword">for</span> SQLite, MySQL, and PostgreSQL. You<span class="hljs-string">'ll be able to integrate the technologies with ease.

### How to Write a SQL Query

_Feel free to download the [European Soccer Data](https://www.kaggle.com/hugomathien/soccer) to your PostgreSQL database. I'</span>ll be using its data <span class="hljs-keyword">for</span> <span class="hljs-built_in">this</span> example._  

The database connection you created <span class="hljs-keyword">in</span> the last step lets you write SQL to then store the data <span class="hljs-keyword">in</span> a Python-friendly data structure. Now that you<span class="hljs-string">'ve established a database connection, you can write a SQL query to start pulling data:

```sql query
query = "SELECT *
         FROM League
         JOIN Country ON Country.id = League.country_id;"</span>
</code></pre><p>The work is not done yet, though. You need to write some additional Python code that executes the SQL query:</p>
<pre><code>#Runs your SQL query
execute1 = cur.execute(query)
result = cur.fetchall()
</code></pre><p>Then you need to store the returned data in a pandas data frame:</p>
<pre><code>#Create initial dataframe <span class="hljs-keyword">from</span> SQL data
raw_initial_df = pd.read_sql_query(query, con)
print(raw_initial_df)
</code></pre><p>You should get a pandas data frame (raw_initial_df) that looks something like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/image-108.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-theres-a-database-for-everybody">There's a Database for Everybody</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/03/nastya-dulhiier-0Oppqi4r394-unsplash.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>SQLite, MySQL, and PostgreSQL all have their pros and cons. The one you select should depend on your project or company's needs. You should also consider what you need now versus several years down the road. </p>
<p>The important thing to remember is that Python can integrate with each database type. </p>
<p>This article scratches the surface for what's possible with connecting Python to a SQL database. I love seeing the ways software intersect and combine to add incredible value. </p>
<p>If you want more of this type of content, you can find me at <a target="_blank" href="https://coursetohire.com/">Course to Hire</a>! I want to help more people learn how to code and land a job in tech. Please reach out for any questions or if you just want to say hi :)</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Learn How to Use SQLite Databases With Python ]]>
                </title>
                <description>
                    <![CDATA[ SQLite is a very easy to use database engine included with Python. SQLite is open source and is a great database for smaller projects, hobby projects, or testing and development. We've released a full video course to help you learn the basics of usin... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/using-sqlite-databases-with-python/</link>
                <guid isPermaLink="false">66b206f1c181ed99dbd2af46</guid>
                
                    <category>
                        <![CDATA[ SQLite ]]>
                    </category>
                
                    <category>
                        <![CDATA[ youtube ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Beau Carnes ]]>
                </dc:creator>
                <pubDate>Wed, 13 May 2020 18:41:54 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/05/sqlite.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>SQLite is a very easy to use database engine included with Python. SQLite is open source and is a great database for smaller projects, hobby projects, or testing and development.</p>
<p>We've released a full video course to help you learn the basics of using SQLite3 with Python. You’ll learn how to create databases and tables, add data, sort data, create reports, pull specific data, and more. The course is taught by John Elder from Codemy.com.</p>
<p>For this course you should already have a basic knowledge of Python programming, but you don’t need to know anything at all about databases or SQLite.</p>
<p>In this course, you will learn:</p>
<ul>
<li>what is a database</li>
<li>how to install Python</li>
<li>how to install git bash terminal</li>
<li>how to use sqlite in a Python program</li>
<li>how to connect to database in Python</li>
<li>how to create a database</li>
<li>how to create a table</li>
<li>how to insert one record into table</li>
<li>how to insert many records into table</li>
<li>understanding data types</li>
<li>how to select data from table</li>
<li>how to format your results</li>
<li>how to use the where clause</li>
<li>how to use the like clause and wildcards</li>
<li>how to use AND and OR</li>
<li>how to update records</li>
<li>how to limit and order results</li>
<li>how to delete records</li>
<li>how to delete (drop) a table and backups</li>
<li>and more!</li>
</ul>
<p>At the end of the course you will learn how to build a very basic app to help reinforce all the things from the course.</p>
<p>You can watch the video course below or <a target="_blank" href="https://www.youtube.com/watch?v=byHcYRpMgI4">on the freeCodeCamp.org YouTube channel</a> (1.5 hour watch).</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/byHcYRpMgI4" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to use Streams, BLoCs, and SQLite in Flutter ]]>
                </title>
                <description>
                    <![CDATA[ By Eric Grandt Recently, I’ve been working with streams and BLoCs in Flutter to retrieve and display data from an SQLite database. Admittedly, it took me a very long time to make sense of them. With that said, I’d like to go over all this in hopes yo... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/using-streams-blocs-and-sqlite-in-flutter-2e59e1f7cdce/</link>
                <guid isPermaLink="false">66d45e3f182810487e0ce147</guid>
                
                    <category>
                        <![CDATA[ Apps ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Flutter ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ SQLite ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 17 Apr 2019 19:58:12 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*ihvDZXwv6oGz760kKUgYTQ.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Eric Grandt</p>
<p>Recently, I’ve been working with streams and BLoCs in Flutter to retrieve and display data from an SQLite database. Admittedly, it took me a very long time to make sense of them. With that said, I’d like to go over all this in hopes you’ll walk away feeling confident in using them within your own apps. I’ll be going into as much depth as I possibly can and explaining everything as simply as possible.</p>
<p>In this post, we’ll be making a simple app from start to finish that makes use of streams, BLoCs, and an SQLite database. This app will allow us to create, modify, and delete notes. If you haven’t done so yet, create a new barebones Flutter app using <code>flutter create APPNAME</code>. It'll be a lot easier to understand all this if you start fresh. Then, later on, implement what you learned into your existing apps.</p>
<p>The first order of business is creating a class to handle the creation of our tables and to query the database. To do this properly, we need to add <code>sqflite</code> and <code>path_provider</code> as dependencies in our <code>pubspec.yaml</code> file.</p>


<p>In case it doesn’t run automatically, run <code>flutter packages get</code> to retrieve the packages. Once it finishes, create a <code>data</code> folder and a <code>database.dart</code> file within it. This class will create a singleton so we can access the database from other files, open the database, and run queries on that database. I've included comments to explain some of the code.</p>


<p>Create another folder, <code>models</code>, and add one file to it: <code>note_model.dart</code>. Here's a great tool to easily make models: <a target="_blank" href="https://app.quicktype.io/#l=dart">https://app.quicktype.io/#l=dart</a>.</p>
<p><strong>NOTE:</strong> Keep in mind that models do NOT have to copy the columns in the table. For example, if you have a user id stored in a table as a foreign key, the model probably shouldn’t contain that user id. Instead, the model should use that user id in order to retrieve an actual <code>User</code> object.</p>


<p>With our note model created, we can add the final functions to our database file that’ll handle all note related queries.</p>


<p>Let’s get started with streams and BLoCs now. If this is your first time working with these, it can be quite daunting. I promise you though that streams and BLoCs are exceptionally simple once you get past the learning phase.</p>
<p>The first thing we need is a <code>blocs</code> folder within the <code>data</code> folder. This folder will contain all our BLoCs, as the name suggests. Let's create the files for each BLoC: <code>bloc_provider.dart</code>, <code>notes_bloc.dart</code>, and <code>view_note_bloc.dart</code>. One BLoC per page and one to provide the BLoCs to those pages.</p>
<p>The <code>bloc_provider</code> is in charge of easily providing our pages with the necessary BLoC and then disposing of it when necessary. Every time we want to use a BLoC, we'll be using the <code>bloc_provider</code>.</p>


<p>Whenever we need a BLoC on one of our pages, we’ll utilize the <code>BlocProvider</code> like this:</p>


<p>Let’s create our notes BLoC which will handle retrieving all our notes and adding new notes to the database. Since our BLoCs are page specific, this BLoC will only be used on the notes page. I’ve commented the code to explain what’s going on.</p>


<p>With the notes BLoC created, we have everything we need to create our notes page. This page will display all our notes, and allow us to add new ones. We’ll put the code for our notes page into <code>main.dart</code>. Once again, I've commented on all the necessary pieces of code to explain what's going on.</p>


<p>Now we need a way to view, edit, save, and delete the notes. This is where the view note BLoC and the view note page come into play. We’ll start with <code>view_note_bloc.dart</code>.</p>


<p>Now we can build the actual page to allow us to interact with our notes. The code for this page is going in <code>view_note.dart</code>.</p>


<p><img src="https://cdn-media-1.freecodecamp.org/images/VM6e-BtScNO6RMweffYoZGr8kiqmcnstM2DE" alt="Image" width="200" height="422" loading="lazy">
<em>Final app using streams, BLoCs, and SQLite</em></p>
<p>That’s all it takes to work with streams, BLoCs, and SQLite. Using them, we’ve created a super simple app that allows us to create, view, edit, and delete notes. I hope this walkthrough has made you more confident in working with streams. You’ll now be able to implement them into your own apps with ease. If you have any questions, please leave a comment as I’d love to answer them. Thanks for reading.</p>
<p>View the full code here: <a target="_blank" href="https://github.com/Erigitic/flutter-streams">https://github.com/Erigitic/flutter-streams</a></p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
