DEV Community

Cover image for Learn SQL with PostgreSQL: Building a Budget Tracking Application
kihuni
kihuni

Posted on

Learn SQL with PostgreSQL: Building a Budget Tracking Application

Whether you're taking your first steps in database management and eager to grasp the fundamentals or an aspiring developer hungry for practical experience, you've landed on the ideal resource. In this guide, we'll delve into the world of SQL and PostgreSQL, creating a budget-tracking application from the ground up.

This guide is tailored for:

  • Beginners looking to grasp the essentials of SQL and database management.

  • Developers eager to hone their skills with PostgreSQL and application development.

Throughout this blog post, we'll cover:

  • Understanding SQL and PostgreSQL: We'll introduce SQL and PostgreSQL, explaining their significance in database management and application development.

  • Designing the Database Schema: We'll outline the database schema for our budget tracking application, detailing the tables and relationships involved.

  • Setting Up PostgreSQL: We'll guide you through installing and configuring PostgreSQL on your system.

  • Creating and Populating Tables: We'll demonstrate how to create the necessary tables for our application and populate them with sample data.

  • Querying Data: Finally, we'll explore how to retrieve and analyze data from our database using SQL queries.

What is SQL?

SQL, or Structured Query Language, is a specialized programming language designed to interact with relational databases. You can think of it as a means to ask specific questions about your data and receive relevant answers. SQL can be used to create and manage databases and insert, update, and delete data within them.

What is PostgreSQL?

PostgreSQL is a powerful and open-source database management system that allows the use of SQL. It is widely known for being reliable, performing well, and offering a wide range of features. While SQL is the main language used to interact with PostgreSQL, the system also includes extra functionality that goes beyond standard SQL. This includes features like user authentication, data integrity checks, and advanced data types.

Understanding the Budget Tracking System
Budget tracking applications help individuals monitor their expenses, manage their finances, and achieve their financial goals more effectively. By recording income and expenditures, categorizing transactions, and generating reports, users gain insights into their spending habits and can make informed decisions about budgeting and saving.

PostgreSQL is an ideal database management system for building budget-tracking applications due to its robust features, including support for complex queries, transactions, and data integrity constraints. Its reliability, scalability, and open-source nature make it a popular choice among developers for a wide range of applications, including financial management tools.

Designing the Database Schema:

The budget tracking application's database schema consists of several tables to store user information, accounts, spending categories, and transactions. Here's an overview of the database schema:

User Table:

UserID (Primary Key)
Username
Password
Email

Accounts Table:

AccountID (Primary Key)
UserID (Foreign Key referencing User table)
AccountName
Balance

Categories Table:

CategoryID (Primary Key)
UserID (Foreign Key referencing User table)
CategoryName

Transactions Table:

TransactionID (Primary Key)
UserID (Foreign Key referencing User table)
AccountID (Foreign Key referencing Accounts table)
CategoryID (Foreign Key referencing Categories table)
Amount
TransactionDate
Description
Type (Income or Expense)
Enter fullscreen mode Exit fullscreen mode

Relationships between Tables:

  • The user table is the central table with other tables referencing it using UserID(Foreign Keys).

  • One User can have many Accounts and Transactions (one-to-many).

  • One User can have many Transactions (one-to-many).

  • One Account can have many Transactions (one-to-many).

  • One Category can have many transactions (one-to-many).

Setting Up PostgreSQL:

To set up PostgreSQL on your system, follow these steps:

  • First, you should check if already pre-installed on your system.

  • Use Postgresql documentation for installation; Here is the general installation guide.

  • During installation, set a password for the default PostgreSQL user (postgres).

  • Start the PostgreSQL service.

  • Access the PostgreSQL command-line interface (psql) or use a graphical tool like pgAdmin to manage databases.

Creating a Database:

We will be using our terminal as a client application to perform database operations.

To create a database we use createdb command followed by the name of the database, for our example we will call it budgetTracking

Creating database

Accessing a database

Once you create a database you can access it by using psql command followed by the name of your database budgetTracking

Accessing database

Creating Tables

You can create tables by specifying the table name along with all column names and their types.

Let's create our tables:

Users table:

CREATE TABLE "User" (
    UserID SERIAL PRIMARY KEY,
    Username VARCHAR(50) NOT NULL,
    Email VARCHAR(100)
);

Accounts tables:

CREATE TABLE Accounts (
    AccountID SERIAL PRIMARY KEY,
    UserID INT REFERENCES Users(UserID),
    AccountName VARCHAR(50) NOT NULL,
    Balance DECIMAL(10, 2)
);

Categories table:

CREATE TABLE Categories (
    CategoryID SERIAL PRIMARY KEY,
    UserID INT REFERENCES Users(UserID),
    CategoryName VARCHAR(50) NOT NULL
);

Transaction table:

CREATE TABLE Transactions (
    TransactionID SERIAL PRIMARY KEY,
    UserID INT REFERENCES Users(UserID),
    AccountID INT REFERENCES Accounts(AccountID),
    CategoryID INT REFERENCES Categories(CategoryID),
    Amount DECIMAL(10, 2) NOT NULL,
    TransactionDate DATE NOT NULL,
    Description VARCHAR(255),
    Type VARCHAR(10) CHECK (Type IN ('Income', 'Expense'))
);
Enter fullscreen mode Exit fullscreen mode

Populating the Database with sample data

To populate the table with rows we use the INSERT statement.

INSERT INTO User (Username, Email) VALUES ('user1', 'user1@example.com');

INSERT INTO Accounts (UserID, AccountName, Balance) VALUES (1, 'Savings Account', 5000.00);

INSERT INTO Categories (UserID, CategoryName) VALUES (1, 'Groceries'), (1, 'Utilities');

INSERT INTO Transactions (UserID, AccountID, CategoryID, Amount, TransactionDate, Description, Type) 
VALUES 
(1, 1, 1, 50.00, '2024-03-26', 'Grocery shopping', 'Expense'),
(1, 1, 2, 100.00, '2024-03-25', 'Electricity bill', 'Expense');

Enter fullscreen mode Exit fullscreen mode

Querying Data:

We use the' SELECT' statement to retrieve or query data from a table.

-- Retrieving all users, accounts, transactions, and categories individually.
Query data

-- Calculating total expenses for a specific category

SELECT Categories.CategoryName, SUM(Transactions.Amount) AS TotalExpenses 
FROM Transactions 
JOIN Categories ON Transactions.CategoryID = Categories.CategoryID 
WHERE Transactions.UserID = 1 AND Transactions.Type = 'Expense' 
GROUP BY Categories.CategoryName;

Enter fullscreen mode Exit fullscreen mode

-- Retrieve account balances for all accounts

SELECT AccountName, Balance FROM Accounts;

Summary

Congratulations on completing your journey into the world of SQL, PostgreSQL, and budget-tracking application development! In this guide, we've explored the fundamentals of SQL and PostgreSQL and applied our newfound knowledge to design and build a simple budget-tracking system. Along the way, we've covered everything from understanding database schema design to querying data. You've gained invaluable skills that will serve you well as a developer.

Resources for Further Learning

To further enhance your skills in SQL and PostgreSQL, consider exploring additional resources and courses available online. Here are some recommended resources:

Documentation and Tutorials:

PostgreSQL Documentation: The official documentation for PostgreSQL is an invaluable resource for learning about its features, functions, and best practices.

SQL Tutorial by w3schools: W3schools offers a comprehensive tutorial on SQL, covering everything from basic queries to advanced topics like joins and subqueries.

By leveraging these resources and continuing to engage with the SQL and PostgreSQL community, you'll deepen your understanding, refine your skills, and stay updated on the latest developments in database management and application development. Keep learning, exploring, and building, and you'll undoubtedly achieve great things in your journey with SQL and PostgreSQL.

Top comments (0)