<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<channel>
<title>Coder Legion - Recent posts tagged sqlite3</title>
<link>https://coderlegion.com/tag/sqlite3</link>
<description>Powered by Question2Answer</description>
<item>
<title>SQL - A Quick Intro</title>
<link>https://coderlegion.com/3192/sql-a-quick-intro</link>
<description>&lt;h2 id=&quot;sql---a-quick-intro&quot;&gt;SQL - A Quick Intro&lt;/h2&gt;
&lt;h3 id=&quot;overview&quot;&gt;Overview&lt;/h3&gt;
&lt;p&gt;In this article, we’ll walk through the essentials of SQL using the SQLite dialect. We’ll start by creating a couple of sample tables and populating them with data. These tables will serve as the foundation for our examples in later sections. By the end of this overview, you will have a simple schema to work with and understand how to set the scene for common SQL operations.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;-- Create a table for users
CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY,
    username TEXT NOT NULL,
    email TEXT NOT NULL,
    joined_date TEXT NOT NULL  -- stored as ISO-8601 strings in SQLite
);

-- Create a table for orders
CREATE TABLE IF NOT EXISTS orders (
    id INTEGER PRIMARY KEY,
    user_id INTEGER NOT NULL,
    product TEXT NOT NULL,
    quantity INTEGER NOT NULL,
    order_date TEXT NOT NULL,
    FOREIGN KEY (user_id) REFERENCES users(id)
);

-- Insert sample data into users
INSERT INTO users (username, email, joined_date) VALUES
    ('alice', '*Emails are not allowed*', '2023-01-15'),
    ('bob', '*Emails are not allowed*', '2023-02-10'),
    ('carol', '*Emails are not allowed*', '2023-03-05');

-- Insert sample data into orders
INSERT INTO orders (user_id, product, quantity, order_date) VALUES
    (1, 'Keyboard', 2, '2023-04-01'),
    (1, 'Mouse', 1, '2023-04-07'),
    (2, 'Monitor', 1, '2023-04-15'),
    (3, 'Desk Lamp', 3, '2023-05-02'),
    (2, 'USB Cable', 5, '2023-05-10');
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;These two tables - &lt;strong&gt;users&lt;/strong&gt; and &lt;strong&gt;orders&lt;/strong&gt; - will be the basis for our queries. Feel free to run these statements in an SQLite environment (e.g., the &lt;code&gt;sqlite3&lt;/code&gt; CLI or any GUI tool) to experiment with the examples that follow.&lt;/p&gt;
&lt;h3 id=&quot;common-syntax&quot;&gt;Common Syntax&lt;/h3&gt;
&lt;p&gt;In this section, we’ll introduce the four most common SQL statements:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;SELECT&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;UPDATE&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;DELETE&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;INSERT&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;We’ll focus on the typical usage patterns for each statement without covering every possible option or keyword. All SQL keywords are shown in uppercase by convention - this is a good practice. However, they are usually case-insensitive to the SQL engine.&lt;/p&gt;
&lt;h4 id=&quot;1-select&quot;&gt;1. SELECT&lt;/h4&gt;
&lt;p&gt;The &lt;code&gt;SELECT&lt;/code&gt; statement is used to retrieve data from one or more tables. At its simplest, you specify the columns you want and the table from which to retrieve them:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;SELECT id, username, email
FROM users;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you want all columns, use &lt;code&gt;*&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;SELECT *
FROM orders;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You can filter results using &lt;code&gt;WHERE&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;SELECT username, email
FROM users
WHERE joined_date &amp;gt;= '2023-02-01';
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To sort results, use &lt;code&gt;ORDER BY&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;SELECT id, product, quantity, order_date
FROM orders
WHERE quantity &amp;gt; 1
ORDER BY order_date DESC;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Limit the number of rows returned:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;SELECT *
FROM orders
LIMIT 3;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Combine clauses:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;SELECT username, email
FROM users
WHERE username LIKE 'a%'
ORDER BY joined_date;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;LIKE&lt;/code&gt; keyword here matches all names starting with an &lt;code&gt;a&lt;/code&gt;.&lt;/p&gt;
&lt;h4 id=&quot;2-update&quot;&gt;2. UPDATE&lt;/h4&gt;
&lt;p&gt;Use &lt;code&gt;UPDATE&lt;/code&gt; to modify existing rows. Always include a &lt;code&gt;WHERE&lt;/code&gt; clause to avoid updating every row unintentionally:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;-- Change Bob's email address
UPDATE users
SET email = '*Emails are not allowed*'
WHERE username = 'bob';
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You can update multiple columns at once:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;UPDATE users
SET email = '*Emails are not allowed*',
    joined_date = '2023-01-20'
WHERE username = 'alice';
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It’s good practice to run a &lt;code&gt;SELECT&lt;/code&gt; with the same &lt;code&gt;WHERE&lt;/code&gt; first:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;SELECT * FROM users WHERE username = 'alice';
-- Review the row, then:
UPDATE users
SET email = '*Emails are not allowed*'
WHERE username = 'alice';
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;3-delete&quot;&gt;3. DELETE&lt;/h4&gt;
&lt;p&gt;The &lt;code&gt;DELETE&lt;/code&gt; statement removes rows from a table. Again, a &lt;code&gt;WHERE&lt;/code&gt; clause is essential:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;-- Delete Carol's record
DELETE FROM users
WHERE username = 'carol';
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To delete all rows in a table (but keep the table structure):&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;DELETE FROM orders;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;SQLite supports &lt;code&gt;DELETE FROM table_name;&lt;/code&gt; without &lt;code&gt;WHERE&lt;/code&gt; to remove every row. If you only want to remove specific rows:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;DELETE FROM orders
WHERE order_date &amp;lt; '2023-04-01';
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;4-insert&quot;&gt;4. INSERT&lt;/h4&gt;
&lt;p&gt;&lt;code&gt;INSERT&lt;/code&gt; adds new rows into a table. We already used this in the overview to populate &lt;code&gt;users&lt;/code&gt; and &lt;code&gt;orders&lt;/code&gt;. The basic syntax specifies columns and values:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;INSERT INTO users (username, email, joined_date)
VALUES ('dave', '*Emails are not allowed*', '2023-06-01');
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You can omit the column list if you supply values for every column in the exact order:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;INSERT INTO orders VALUES (NULL, 4, 'Webcam', 2, '2023-06-02');
-- NULL for id since it's an AUTOINCREMENT primary key
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you want to insert from another table (a simple form of &lt;code&gt;SELECT&lt;/code&gt; inside &lt;code&gt;INSERT&lt;/code&gt;):&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;INSERT INTO orders (user_id, product, quantity, order_date)
SELECT id, 'Headphones', 1, '2023-06-05'
FROM users
WHERE username = 'bob';
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;techniques&quot;&gt;Techniques&lt;/h3&gt;
&lt;p&gt;The examples above covered basic CRUD operations. In this section, we’ll focus on more advanced - but frequently used - &lt;code&gt;SELECT&lt;/code&gt; patterns in SQLite, including implicit joins, explicit joins, Common Table Expressions (&lt;code&gt;WITH&lt;/code&gt;), and subqueries. These techniques are particularly helpful when you need to combine data from multiple tables or derive aggregated results.&lt;/p&gt;
&lt;h4 id=&quot;1-implicit-join-using-multiple-tables-in-from&quot;&gt;1. Implicit Join Using Multiple Tables in FROM&lt;/h4&gt;
&lt;p&gt;An implicit join (sometimes called a “comma join”) lists multiple tables in the &lt;code&gt;FROM&lt;/code&gt; clause and specifies the join condition in &lt;code&gt;WHERE&lt;/code&gt;. This style is concise but can be less clear for complex queries:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;-- List every order along with the username of the user who placed it
SELECT u.username, o.product, o.quantity, o.order_date
FROM users u, orders o
WHERE u.id = o.user_id;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here, &lt;code&gt;u&lt;/code&gt; is an alias for &lt;code&gt;users&lt;/code&gt; and &lt;code&gt;o&lt;/code&gt; is an alias for &lt;code&gt;orders&lt;/code&gt;. The join condition &lt;code&gt;u.id = o.user_id&lt;/code&gt; ties rows in &lt;code&gt;users&lt;/code&gt; to matching rows in &lt;code&gt;orders&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;You can add filters:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;-- Only orders with quantity &amp;gt; 1
SELECT u.username, o.product, o.quantity
FROM users u, orders o
WHERE u.id = o.user_id
  AND o.quantity &amp;gt; 1
ORDER BY o.order_date;
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;2-explicit-join-syntax-inner-join-left-join-&quot;&gt;2. Explicit Join Syntax (INNER JOIN, LEFT JOIN)&lt;/h4&gt;
&lt;p&gt;SQLite supports the standard explicit &lt;code&gt;JOIN&lt;/code&gt; syntax, which is recommended for clarity:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;-- INNER JOIN retrieves only matching rows
SELECT u.username, o.product, o.order_date
FROM users u
INNER JOIN orders o
    ON u.id = o.user_id;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;For a left (or left outer) join, which returns all rows from the left table and matching rows (if any) from the right table:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;-- List all users, including those who have not placed orders
SELECT u.username, o.product, o.order_date
FROM users u
LEFT JOIN orders o
    ON u.id = o.user_id;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If a user has no matching &lt;code&gt;orders&lt;/code&gt;, the &lt;code&gt;product&lt;/code&gt; and &lt;code&gt;order_date&lt;/code&gt; columns will be &lt;code&gt;NULL&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Multiple Joins&lt;/strong&gt;&lt;br&gt;
When you have more than two tables, chain the joins together:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;-- Suppose we add a table for payment info
CREATE TABLE IF NOT EXISTS payments (
    id INTEGER PRIMARY KEY,
    order_id INTEGER NOT NULL,
    amount REAL NOT NULL,
    payment_date TEXT NOT NULL,
    FOREIGN KEY (order_id) REFERENCES orders(id)
);

-- Sample data
INSERT INTO payments (order_id, amount, payment_date) VALUES
    (1, 49.98, '2023-04-02'),
    (2, 19.99, '2023-04-08'),
    (3, 149.99, '2023-04-16');

-- Query: find username, product, and payment amount for each paid order
SELECT u.username,
       o.product,
       p.amount,
       p.payment_date
FROM users u
INNER JOIN orders o
    ON u.id = o.user_id
INNER JOIN payments p
    ON o.id = p.order_id
ORDER BY p.payment_date;
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;3-with-clause-common-table-expressions-&quot;&gt;3. WITH Clause (Common Table Expressions)&lt;/h4&gt;
&lt;p&gt;A Common Table Expression (CTE) defined by &lt;code&gt;WITH&lt;/code&gt; allows you to create a temporary, named result set that you can reference in a subsequent query. This is useful for breaking complex queries into more readable pieces.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;-- Example: Find users who have spent more than $50 in total
WITH user_totals AS (
    SELECT u.id AS user_id,
           u.username,
           SUM(p.amount) AS total_spent
    FROM users u
    INNER JOIN orders o
        ON u.id = o.user_id
    INNER JOIN payments p
        ON o.id = p.order_id
    GROUP BY u.id, u.username
)
SELECT username, total_spent
FROM user_totals
WHERE total_spent &amp;gt; 50;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In this example:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;The CTE named &lt;code&gt;user_totals&lt;/code&gt; aggregates total spending per user.&lt;/li&gt;
&lt;li&gt;The outer &lt;code&gt;SELECT&lt;/code&gt; filters users based on their aggregated spending.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;CTEs can be &lt;strong&gt;recursive&lt;/strong&gt; as well, but for a quick intro, focus on non-recursive CTEs.&lt;/p&gt;
&lt;h4 id=&quot;4-subqueries&quot;&gt;4. Subqueries&lt;/h4&gt;
&lt;p&gt;Subqueries (also called inner queries or nested queries) are queries embedded inside other SQL statements. They can appear in the &lt;code&gt;SELECT&lt;/code&gt; list, &lt;code&gt;FROM&lt;/code&gt; clause, or &lt;code&gt;WHERE&lt;/code&gt; clause.&lt;/p&gt;
&lt;h5 id=&quot;4-1-subquery-in-select-list&quot;&gt;4.1 Subquery in SELECT List&lt;/h5&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;-- Add a column showing the number of orders each user has placed
SELECT u.username,
       u.email,
       (
           SELECT COUNT(*)
           FROM orders o
           WHERE o.user_id = u.id
       ) AS order_count
FROM users u;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The subquery &lt;code&gt;(SELECT COUNT(*) FROM orders o WHERE o.user_id = u.id)&lt;/code&gt; executes for each row in &lt;code&gt;users&lt;/code&gt;.&lt;/p&gt;
&lt;h5 id=&quot;4-2-subquery-in-where-clause&quot;&gt;4.2 Subquery in WHERE Clause&lt;/h5&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;-- Find users who have never placed an order
SELECT username, email
FROM users
WHERE id NOT IN (
    SELECT DISTINCT user_id
    FROM orders
);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Alternatively, using &lt;code&gt;NOT EXISTS&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;SELECT username, email
FROM users u
WHERE NOT EXISTS (
    SELECT 1
    FROM orders o
    WHERE o.user_id = u.id
);
&lt;/code&gt;&lt;/pre&gt;
&lt;h5 id=&quot;4-3-subquery-in-from-clause&quot;&gt;4.3 Subquery in FROM Clause&lt;/h5&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;-- Join users to a derived table that calculates order counts
SELECT t.username, t.order_count
FROM (
    SELECT u.id AS user_id,
           u.username,
           COUNT(o.id) AS order_count
    FROM users u
    LEFT JOIN orders o
        ON u.id = o.user_id
    GROUP BY u.id, u.username
) AS t
WHERE t.order_count &amp;gt;= 2;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here, the subquery in the &lt;code&gt;FROM&lt;/code&gt; clause (aliased as &lt;code&gt;t&lt;/code&gt;) computes the number of orders per user. The outer query then filters on &lt;code&gt;order_count&lt;/code&gt;.&lt;/p&gt;
&lt;h4 id=&quot;5-aggregation-and-group-by&quot;&gt;5. Aggregation and GROUP BY&lt;/h4&gt;
&lt;p&gt;While technically a part of &lt;code&gt;SELECT&lt;/code&gt; patterns, aggregation is so common that it merits a dedicated mention:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;-- Total quantity ordered per product
SELECT product,
       SUM(quantity) AS total_quantity
FROM orders
GROUP BY product
ORDER BY total_quantity DESC;
&lt;/code&gt;&lt;/pre&gt;
&lt;h5 id=&quot;having&quot;&gt;HAVING&lt;/h5&gt;
&lt;p&gt;To filter on aggregated values, use &lt;code&gt;HAVING&lt;/code&gt; rather than &lt;code&gt;WHERE&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;-- Only products with total quantity &amp;gt; 2
SELECT product,
       SUM(quantity) AS total_quantity
FROM orders
GROUP BY product
HAVING total_quantity &amp;gt; 2;
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;6-putting-it-all-together&quot;&gt;6. Putting It All Together&lt;/h4&gt;
&lt;p&gt;Let’s combine a few of these techniques into a more comprehensive example:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;We want to list each user, their total number of orders, total quantity ordered, and their most recent order date.&lt;/li&gt;
&lt;li&gt;Only include users who have placed at least one order.&lt;/li&gt;
&lt;li&gt;Sort by total quantity descending.&lt;/li&gt;
&lt;/ol&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;WITH user_orders AS (
    SELECT u.id    AS user_id,
           u.username,
           COUNT(o.id)           AS order_count,
           SUM(o.quantity)       AS total_quantity,
           MAX(o.order_date)     AS last_order_date
    FROM users u
    INNER JOIN orders o
        ON u.id = o.user_id
    GROUP BY u.id, u.username
)
SELECT username,
       order_count,
       total_quantity,
       last_order_date
FROM user_orders
WHERE order_count &amp;gt;= 1
ORDER BY total_quantity DESC;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Explanation:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The CTE &lt;code&gt;user_orders&lt;/code&gt; aggregates order-related metrics per user.&lt;/li&gt;
&lt;li&gt;The outer query filters out users with zero orders and sorts the results.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;putting-it-into-practice&quot;&gt;Putting It into Practice&lt;/h3&gt;
&lt;p&gt;Here are a few additional examples and variations you might find useful in everyday data analysis with SQLite:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Top 3 Users by Total Spending&lt;/strong&gt;&lt;br&gt;
Combine payments and orders to rank users.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;WITH spending AS (
    SELECT u.id         AS user_id,
           u.username,
           SUM(p.amount) AS total_spent
    FROM users u
    INNER JOIN orders o
        ON u.id = o.user_id
    INNER JOIN payments p
        ON o.id = p.order_id
    GROUP BY u.id, u.username
)
SELECT username, total_spent
FROM spending
ORDER BY total_spent DESC
LIMIT 3;
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Find Orders with No Payment Records&lt;/strong&gt;&lt;br&gt;
Use a left join and look for &lt;code&gt;NULL&lt;/code&gt; in the payment side.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;SELECT o.id AS order_id,
       u.username,
       o.product,
       o.order_date
FROM orders o
LEFT JOIN payments p
    ON o.id = p.order_id
INNER JOIN users u
    ON o.user_id = u.id
WHERE p.id IS NULL;
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Update via Subquery&lt;/strong&gt;&lt;br&gt;
Suppose we want to mark users who joined before a certain date as “legacy” in a new column. First, add a column:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;ALTER TABLE users ADD COLUMN status TEXT DEFAULT 'active';

UPDATE users
SET status = 'legacy'
WHERE joined_date &amp;lt; '2023-02-01';
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Delete Based on a Joined Condition&lt;/strong&gt;&lt;br&gt;
If you needed to delete payments for orders that were canceled (imagine a hypothetical &lt;code&gt;orders.status = 'canceled'&lt;/code&gt; column), you could write:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;DELETE FROM payments
WHERE order_id IN (
    SELECT id
    FROM orders
    WHERE status = 'canceled'
);
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Nested CTEs&lt;/strong&gt;&lt;br&gt;
Chain multiple CTEs to break down a complex problem:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;WITH recent_orders AS (
    SELECT *
    FROM orders
    WHERE order_date &amp;gt;= '2023-04-01'
),
recent_payments AS (
    SELECT o.id     AS order_id,
           o.user_id,
           p.amount,
           p.payment_date
    FROM recent_orders o
    INNER JOIN payments p
        ON o.id = p.order_id
)
SELECT u.username,
       SUM(rp.amount) AS recent_spending
FROM users u
INNER JOIN recent_payments rp
    ON u.id = rp.user_id
GROUP BY u.username
ORDER BY recent_spending DESC;
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h3&gt;
&lt;p&gt;This article has introduced the basics of SQL using the SQLite dialect, focusing on the most common statements - &lt;strong&gt;SELECT&lt;/strong&gt;, &lt;strong&gt;UPDATE&lt;/strong&gt;, &lt;strong&gt;DELETE&lt;/strong&gt;, and &lt;strong&gt;INSERT&lt;/strong&gt; - as well as several useful &lt;code&gt;SELECT&lt;/code&gt; techniques. You now have a schema with &lt;code&gt;users&lt;/code&gt;, &lt;code&gt;orders&lt;/code&gt;, and &lt;code&gt;payments&lt;/code&gt; to experiment with, and you’ve seen how to:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Create tables and insert data.&lt;/li&gt;
&lt;li&gt;Perform simple CRUD operations.&lt;/li&gt;
&lt;li&gt;Join tables both implicitly and explicitly.&lt;/li&gt;
&lt;li&gt;Use Common Table Expressions (&lt;code&gt;WITH&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;Write subqueries in various parts of a statement.&lt;/li&gt;
&lt;li&gt;Aggregate data and filter with &lt;code&gt;HAVING&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;These examples should provide a solid foundation for everyday data analysis tasks. As you become more comfortable, you can explore advanced topics like window functions, triggers, and indexing strategies in SQLite.&lt;/p&gt;
</description>
<category>Data Science</category>
<guid isPermaLink="true">https://coderlegion.com/3192/sql-a-quick-intro</guid>
<pubDate>Mon, 02 Jun 2025 23:03:06 +0000</pubDate>
</item>
<item>
<title>Database Interaction: Connecting to Databases</title>
<link>https://coderlegion.com/390/database-interaction-connecting-to-databases</link>
<description>&lt;p&gt;In this article, we will address the key issue of database connections in software development. Large volumes of data are effectively stored and managed via databases, which form the foundation of many applications. Building scalable and reliable apps requires developers to have a solid understanding of database connections.&lt;br&gt;In software development, database connectivity is essential for maintaining &lt;strong&gt;data integrity&lt;/strong&gt;, &lt;strong&gt;scalability&lt;/strong&gt;, and &lt;strong&gt;system performance&lt;/strong&gt;. Relational databases like MySQL and PostgreSQL offer structured storage and sophisticated querying, whereas NoSQL databases like MongoDB and Redis offer flexibility for unstructured data. Comprehending these distinctions is essential for developers to make well-informed decisions.&lt;/p&gt;
&lt;section&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Selecting the Right Database&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;This tutorial offers information on different kinds of databases and things to think about.&lt;br&gt;Different Types of Databases:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Relational Databases:&lt;/strong&gt; These databases arrange information into structured tables that have pre-established connections between them. PostgreSQL, SQL Server, and MySQL are a few examples.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;NoSQL database&lt;/strong&gt;: Large amounts of unstructured or semi-structured data are easily handled by NoSQL databases because they provide a more flexible data format. Redis, Cassandra, and MongoDB are a few examples.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Factors to Consider When Choosing a Database:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Data Structure and Requirements&lt;/strong&gt;: NoSQL databases are better for unstructured or schema-less data, while relational databases are better for highly structured data that requires complex querying.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Scalability&lt;/strong&gt;: Relational databases scale vertically by adding resources to a single server; NoSQL databases scale horizontally by sharing data across servers.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Performance&lt;/strong&gt;: Relational databases perform better in ACID transactions, however NoSQL databases place a higher priority on low latency and high throughput.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Requirements for Consistency and Integrity&lt;/strong&gt;: Strict consistency and transactional integrity are guaranteed for accurate data by relational databases. NoSQL databases may provide models for eventual consistency, putting high availability ahead of instant consistency.&lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;from pymongo import MongoClient&lt;br&gt;
client = MongoClient('mongodb://localhost:27017/')&lt;br&gt;
db = client['my_database']&lt;br&gt;
collection = db['my_collection']&lt;br&gt;
collection.insert_one({'name': 'XYZ', 'age': 30, 'email': '*Emails are not allowed*'})&lt;br&gt;
# Query documents&lt;br&gt;
result = collection.find_one({'name': 'XYZ'})&lt;br&gt;
print(result)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;div class=&quot;div-green&quot;&gt;&lt;span class=&quot;alert-header&quot;&gt;Tip:&lt;/span&gt; Prototype with different databases to assess performance, scalability, and suitability for your project before making a final decision.&lt;/div&gt;
&lt;/section&gt;
&lt;section&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Python's Common Database Connection Methods&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;There are numerous ways to connect to databases in Python, including:&lt;/p&gt;
&lt;h3&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;1. Using built-in libraries&lt;/strong&gt;:&lt;/span&gt;&lt;/h3&gt;
&lt;/section&gt;
&lt;section&gt;Direct database connections without the need for additional dependencies are made possible by Python's built-in modules, such as sqlite3 for SQLite.&lt;br&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import sqlite3&lt;br&gt;
conn = sqlite3.connect('example.db')&lt;br&gt;
cursor = conn.cursor()&lt;br&gt;
cursor.execute('SELECT * FROM table_name')&lt;br&gt;
results = cursor.fetchall()&lt;br&gt;
for x in results:&lt;br&gt;
  print(x)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;2. Third-party libraries:&lt;/strong&gt;&lt;/span&gt;&lt;/h3&gt;
&lt;p&gt;External libraries provide additional functionality and optimizations for particular database systems, such as psycopg2 for PostgreSQL and mysql-connector-python for MySQL. These packages offer simple-to-use APIs for establishing database connections and running queries.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import mysql.connector&lt;br&gt;
mydb= mysql.connector.connect(&lt;br&gt;
    host='hostname',&lt;br&gt;
    user='username',&lt;br&gt;
    database='database_name'&lt;br&gt;
)&lt;br&gt;
mycursor = mydb.cursor()&lt;br&gt;
mycursor.execute('SELECT * FROM table_name')&lt;br&gt;
myresult = mycursor.fetchall()&lt;br&gt;
for x in myresult:&lt;br&gt;
  print(x)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=11770887932542901517&quot; alt=&quot;&quot; width=&quot;750&quot; height=&quot;450&quot;&gt;
&lt;h3&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;3. ORM (Object-Relational Mapping) frameworks:&lt;/strong&gt;&lt;/span&gt;&lt;/h3&gt;
&lt;p&gt;By abstracting database interactions, ORM frameworks such as SQLAlchemy save developers from writing raw SQL queries and enable them to work with Python objects. These frameworks offer strong capabilities for manipulating and managing databases.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;from sqlalchemy import create_engine, MetaData, Table&lt;br&gt;
engine = create_engine('postgresql://username:password@localhost/database_name')&lt;br&gt;
metadata = MetaData()&lt;br&gt;
table = Table('table_name', metadata, autoload=True, autoload_with=engine)&lt;br&gt;
results = engine.execute(table.select()).fetchall()&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;/section&gt;
&lt;section&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Connecting to Relational Database&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;There are multiple processes involved in setting up connections to widely used relational databases such as SQLite, MySQL, and PostgreSQL. Here's a thorough explanation with examples to help clarify:&lt;/p&gt;
&lt;h3&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;1. Setting up connections with each database:&lt;/strong&gt;&lt;/span&gt;&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;A. SQLite:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Data is stored in a single file with the lightweight serverless database engine SQLite. With Python's built-in sqlite3 package, connecting to SQLite is simple.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import sqlite3&lt;br&gt;
conn = sqlite3.connect('example.db')&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=14587128245889891539&quot; alt=&quot;&quot; width=&quot;750&quot; height=&quot;350&quot;&gt;
&lt;p&gt;&lt;strong&gt;B. MySQL:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The mysql-connector-python library can be used to create a connection for MySQL. Make sure pip install mysql-connector-python is installed on your computer.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import mysql.connector&lt;br&gt;
conn = mysql.connector.connect(&lt;br&gt;
    host='localhost',&lt;br&gt;
    user='username',&lt;br&gt;
    database='database_name'&lt;br&gt;
)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;C. PostgreSQL:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;You can use the psycopg2 library to establish a connection to PostgreSQL. Install it (pip install psycopg2), please.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import psycopg2&lt;br&gt;
conn = psycopg2.connect(&lt;br&gt;
    host='localhost',&lt;br&gt;
    user='username',&lt;br&gt;
    password='password',&lt;br&gt;
    database='database_name'&lt;br&gt;
)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;2. Handling connection errors and exceptions:&lt;/strong&gt;&lt;/span&gt;&lt;/h3&gt;
&lt;p&gt;For your application to be robust, it is imperative that you handle exceptions and connection problems in a polite manner. Try-except blocks are a useful tool for handling and catching exceptions.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;try:&lt;br&gt;
    conn = psycopg2.connect(&lt;br&gt;
        host='localhost',&lt;br&gt;
        user='username',&lt;br&gt;
        database='database_name'&lt;br&gt;
    )&lt;br&gt;
except psycopg2.Error as e:&lt;br&gt;
    print(f&quot;Error connecting to PostgreSQL: {e}&quot;)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;3. Executing SQL queries and retrieving results:&lt;/strong&gt;&lt;/span&gt;&lt;/h3&gt;
&lt;p&gt;Once connected, you may use cursor objects to run SQL queries and get the appropriate responses.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;cursor = conn.cursor()&lt;br&gt;
cursor.execute('SELECT * FROM table_name')&lt;br&gt;
results = cursor.fetchall()&lt;br&gt;
for row in results:&lt;br&gt;
    print(row)&lt;br&gt;
cursor.close()&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;/section&gt;
&lt;section&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Connecting to NoSQL Databases&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;In Python, connecting to well-known NoSQL databases such as MongoDB and Redis requires simple steps for database operations, error handling, and setup:&lt;/p&gt;
&lt;h3&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;1. Setting up connections with each database:&lt;/strong&gt;&lt;/span&gt;&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;A. MongoDB:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;To create a connection for MongoDB, use the pymongo package.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;from pymongo import MongoClient&lt;br&gt;
client = MongoClient('mongodb://localhost:27017/')&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;B. Redis:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://pymongo.readthedocs.io/en/stable/&quot;&gt;Redis&lt;/a&gt; can be accessed by using the redis library.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import redis&lt;br&gt;
r = redis.Redis(host='localhost', port=6379, db=0)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;2. Handling connection errors and exceptions:&lt;/strong&gt;&lt;/span&gt;&lt;/h3&gt;
&lt;p&gt;Make sure to use try-except blocks to properly handle connection problems.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;try:&lt;br&gt;
    client = MongoClient('mongodb://localhost:27017/')&lt;br&gt;
except Exception as e:&lt;br&gt;
  print(f&quot;Error connecting to MongoDB: {e}&quot;)&lt;br&gt;
// Redis&lt;br&gt;
try:&lt;br&gt;
    r = redis.Redis(host='localhost', port=6379, db=0)&lt;br&gt;
except Exception as e:&lt;br&gt;
    print(f&quot;Error connecting to Redis: {e}&quot;)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;3. Executing database Operations:&lt;/strong&gt;&lt;/span&gt;&lt;/h3&gt;
&lt;p&gt;Execute database operations like delete, update, and insert.&lt;/p&gt;
&lt;p&gt;MongoDB:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;db = client['my_database']&lt;br&gt;
collection = db['my_collection']&lt;br&gt;
collection.insert_one({'name': 'John', 'age': 30})&lt;br&gt;
collection.update_one({'name': 'John'}, {'$set': {'age': 31}})&lt;br&gt;
collection.delete_one({'name': 'John'})&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Redis:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;r.set('key', 'value')&lt;br&gt;
value = r.get('key')&lt;br&gt;
r.delete('key')&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;/section&gt;
&lt;section&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Error Handling&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;Error handling in database connections is crucial for program reliability and robustness, preventing crashes and enhancing user experience by addressing unforeseen database errors and connection issues.&lt;/p&gt;
&lt;strong&gt;Using try-except blocks:&lt;/strong&gt; Try-except blocks can be used to catch and manage exceptions that are raised during database operations. This guarantees that your program can continue running even after encountering failures.&lt;br&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import psycopg2&lt;br&gt;
try:&lt;br&gt;
    conn = psycopg2.connect(&lt;br&gt;
        host='localhost',&lt;br&gt;
        user='username',&lt;br&gt;
        database='database_name'&lt;br&gt;
    )&lt;br&gt;
except psycopg2.Error as e:&lt;br&gt;
    print(f&quot;Error connecting to PostgreSQL: {e}&quot;)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;strong&gt;Handling specific error types&lt;/strong&gt;: To improve error management precision, classify errors such as query problems or connection failures and provide customised error messages and actions.&lt;br&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import psycopg2&lt;br&gt;
try:&lt;br&gt;
    conn = psycopg2.connect(&lt;br&gt;
        host='localhost',&lt;br&gt;
        user='username',&lt;br&gt;
        password='password',&lt;br&gt;
        database='database_name'&lt;br&gt;
    )&lt;br&gt;
except psycopg2.OperationalError as e:&lt;br&gt;
    print(f&quot;Operational error connecting to PostgreSQL: {e}&quot;)&lt;br&gt;
except psycopg2.DatabaseError as e:&lt;br&gt;
    print(f&quot;Database error connecting to PostgreSQL: {e}&quot;)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;strong&gt;Implementing retry mechanisms&lt;/strong&gt;: Retry techniques automatically retry database operations during temporary errors or network issues, enhancing application robustness, especially in unstable contexts.
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;import psycopg2&lt;br&gt;
import time&lt;br&gt;
max_retries = 3&lt;br&gt;
retry_delay = 1  # seconds&lt;br&gt;
for retry_count in range(max_retries):&lt;br&gt;
    try:&lt;br&gt;
        conn = psycopg2.connect(&lt;br&gt;
            host='localhost',&lt;br&gt;
            user='username',&lt;br&gt;
            database='database_name'&lt;br&gt;
        )&lt;br&gt;
        break&lt;br&gt;
    except psycopg2.Error as e:&lt;br&gt;
        print(f&quot;Error connecting to PostgreSQL: {e}&quot;)&lt;br&gt;
        if retry_count &amp;lt; max_retries - 1:&lt;br&gt;
            print(f&quot;Retrying in {retry_delay} seconds...&quot;)&lt;br&gt;
            time.sleep(retry_delay)&lt;br&gt;
        else:&lt;br&gt;
            print(&quot;Max retries exceeded, unable to connect.&quot;)&lt;br&gt;
          break&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;/section&gt;
&lt;section&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Best Practices and Tips&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;By adhering to these best practices, Python programs may guarantee stable database connections:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;To effectively manage database connections, make use of connection pooling.&lt;/li&gt;
&lt;li&gt;In order to reduce overhead and boost efficiency, reuse connections.&lt;/li&gt;
&lt;li&gt;To liberate resources, always properly close connections.&lt;/li&gt;
&lt;li&gt;Handle connection credentials securely to avoid unwanted access.&lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;&lt;code&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;span class=&quot;hljs-function&quot;&gt;&lt;span class=&quot;hljs-built_in&quot;&gt;from sqlalchemy import create_engine, Pool&lt;br&gt;
# Create an engine with connection pooling&lt;br&gt;
engine = create_engine('database://user:password@host:port/db_name', pool_size=5, max_overflow=10)&lt;br&gt;
# Use the engine to connect to the database&lt;br&gt;
connection = engine.connect()&lt;br&gt;
# Perform database operations...&lt;br&gt;
# Close the connection&lt;br&gt;
connection.close()&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;/section&gt;
&lt;div class=&quot;div-faq&quot;&gt;&lt;span class=&quot;faq-header&quot;&gt;FAQ&lt;/span&gt; &lt;span class=&quot;faq-body&quot;&gt;&lt;br&gt;Q: Why is connection pooling important in database applications?&lt;br&gt;A: Connection pooling helps manage and reuse database connections, reducing the overhead of establishing new connections for each database operation. This improves performance and scalability, especially in applications with high traffic.&lt;/span&gt;&lt;/div&gt;
&lt;section&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;To sum up, this article highlights how important database connections are to software development. Comprehending the subtle differences between &lt;strong&gt;relational &lt;/strong&gt;and &lt;strong&gt;NoSQL database&lt;/strong&gt; types is essential for achieving the best possible project performance. Python provides &lt;strong&gt;flexible &lt;/strong&gt;ways to provide error handling and make database connections. Through careful consideration of database selection and adherence to industry best practices, developers can construct &lt;strong&gt;resilient systems&lt;/strong&gt; that effectively handle data and satisfy the requirements of contemporary software development.&lt;/p&gt;
&lt;/section&gt;
&lt;section&gt;
&lt;h2&gt;&lt;span style=&quot;font-family: arial,helvetica,sans-serif;&quot;&gt;&lt;strong&gt;Reference&lt;/strong&gt;&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;For more reference:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;PyMongo &lt;br&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://pymongo.readthedocs.io/en/stable/&quot;&gt;PyMongo - MongoDB Python driver&lt;/a&gt;&lt;/p&gt;
&lt;/section&gt;
</description>
<category>Data Structures</category>
<guid isPermaLink="true">https://coderlegion.com/390/database-interaction-connecting-to-databases</guid>
<pubDate>Fri, 26 Jul 2024 10:22:07 +0000</pubDate>
</item>
</channel>
</rss>