<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mr. S. Gupta on Medium]]></title>
        <description><![CDATA[Stories by Mr. S. Gupta on Medium]]></description>
        <link>https://medium.com/@surajsrggupta?source=rss-761b5c125020------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4dsQYBX8IlzXrF0bXAJySw.jpeg</url>
            <title>Stories by Mr. S. Gupta on Medium</title>
            <link>https://medium.com/@surajsrggupta?source=rss-761b5c125020------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 20:01:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@surajsrggupta/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[PostgreSQL Deep Dive: Tables, Relations, Primary Keys, Foreign Keys, Indexes, and Transactions]]></title>
            <link>https://surajsrggupta.medium.com/postgresql-deep-dive-tables-relations-primary-keys-foreign-keys-indexes-and-transactions-93760ee4c9a2?source=rss-761b5c125020------2</link>
            <guid isPermaLink="false">https://medium.com/p/93760ee4c9a2</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[keys]]></category>
            <category><![CDATA[table]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[dbms]]></category>
            <dc:creator><![CDATA[Mr. S. Gupta]]></dc:creator>
            <pubDate>Sun, 15 Nov 2026 12:45:12 GMT</pubDate>
            <atom:updated>2026-11-15T12:45:12.997Z</atom:updated>
            <content:encoded><![CDATA[<p>In backend development, a database is never just a place to dump data. It’s the actual foundation the rest of your application stands on. Get the design wrong, and the application slows down, data starts duplicating itself, bugs creep in, and future changes become genuinely painful. That’s exactly why understanding database fundamentals matters so much for anyone building backend systems.</p><p>This piece walks through PostgreSQL from the ground up, what a database actually is, what a table is, what rows and columns mean, what primary keys and foreign keys do, how relationships get built, how indexes actually speed things up, and how transactions keep your data safe.</p><h3>What PostgreSQL actually is</h3><p>PostgreSQL is a relational database management system, or RDBMS for short. In plain terms, it’s software that organizes, stores, and retrieves data for you. If you’re building a social media app, you need somewhere to keep users, posts, comments, and likes, and PostgreSQL stores all of that in a structured, predictable way.</p><p>A database itself is just an organized collection where all of an application’s data lives. A company’s database might hold users, products, orders, and payments, all sitting as separate tables inside one database.</p><h3>Tables, columns, and rows</h3><p>In SQL databases, data lives inside tables. Think of a users table.</p><pre>+----+---------+-------------------+<br>| id | name    | email             |<br>+----+---------+-------------------+<br>| 1  | Rahul   | rahul@test.com    |<br>| 2  | Aman    | aman@test.com     |<br>+----+---------+-------------------+</pre><p>You can think of a table pretty much like a spreadsheet. Each column represents one type of data, id, name, email, password, created_at, each with its own clear purpose. Each row, meanwhile, is one complete record, everything belonging to a single entry, like one specific user’s full set of details.</p><p>Creating a table looks like this.</p><pre>CREATE TABLE users(<br>  id SERIAL PRIMARY KEY,<br>  name TEXT NOT NULL,<br>  email TEXT UNIQUE NOT NULL<br>);</pre><p>That gives you three columns, id, name, and email. Adding data into it is just as direct.</p><pre>INSERT INTO users<br>(name, email)<br>VALUES<br>(&#39;Rahul&#39;, &#39;rahul@test.com&#39;);</pre><p>And pulling it back out is a simple select.</p><pre>SELECT *<br>FROM users;</pre><h3>Primary keys, the thing that makes every row unique</h3><p>A primary key is a column that uniquely identifies every single row in a table. Every user gets their own id, 1, 2, 3, and so on, and that id follows a few strict rules, it can never repeat, and it can never be null. It’s there purely to identify each record without any ambiguity.</p><p>Two rows sharing the same id, like two rows both marked id 1, would be a genuine problem. Two users can absolutely share the same name, plenty of people are named Rahul, but their ids will always be different, and that’s exactly the point. Names can collide, ids never should.</p><h3>Foreign keys, and how relationships actually form</h3><p>A foreign key is what creates a relationship between two tables. Say you have a users table and an orders table.</p><pre>users</pre><pre>id<br>name</pre><pre>orders</pre><pre>id<br>user_id<br>amount</pre><p>Here, orders.user_id references users.id, and that reference is the foreign key. So if Rahul has id = 1, and an order exists with user_id = 1, that combination is really just saying &quot;this order belongs to Rahul.&quot;</p><p>The most common relationship pattern by far is one-to-many, one user having multiple orders. A one-to-one relationship looks a bit different, think a user and their profile, where each user has exactly one profile record sitting in a separate table.</p><pre>users</pre><pre>id<br>name</pre><pre>profiles</pre><pre>id<br>user_id<br>bio</pre><p>And then there’s many-to-many, like students and courses, where one student can enroll in several courses, and one course can have many students enrolled. This kind of relationship typically needs an extra table in between, often called an enrollment or junction table, sitting right between students and courses to hold all those individual connections.</p><h3>Bringing multiple tables together with JOIN</h3><p>Once your data is spread across separate tables, the natural next question is, how do you actually pull related data back together? That’s exactly what SQL’s JOIN does, combining related data that lives across two or more tables.</p><p>Take a users table and an orders table.</p><pre>users</pre><pre>id | name<br>1  | Rahul<br>2  | Aman</pre><pre>orders</pre><pre>id | user_id | amount<br>101 | 1 | 500<br>102 | 1 | 900<br>103 | 2 | 300</pre><p>If you want to know which user placed which order, an INNER JOIN gets you there by returning only the rows where a match actually exists.</p><pre>SELECT<br>users.name,<br>orders.amount<br>FROM users<br>INNER JOIN orders<br>ON users.id = orders.user_id;</pre><p>That gives you Rahul matched with both his orders, and Aman matched with his one order, nothing more, nothing less, only where the relationship genuinely exists.</p><p>A LEFT JOIN behaves differently, it keeps every single row from the left table regardless of whether a match exists on the other side. Say a third user, Rohit, has never placed an order. A LEFT JOIN would still show Rohit in the results, just with a null amount next to his name, rather than dropping him entirely.</p><pre>SELECT<br>users.name,<br>orders.amount<br>FROM users<br>LEFT JOIN orders<br>ON users.id = orders.user_id;</pre><p>RIGHT JOIN is essentially the mirror image of that, keeping every row from the right table instead, though in practice LEFT JOIN shows up far more often. FULL JOIN goes further still, returning everything from both tables, matched or not.</p><p>A practical example, showing every product in a catalog and including order info wherever it exists, looks like this.</p><pre>SELECT<br>products.name,<br>orders.quantity<br>FROM products<br>LEFT JOIN orders<br>ON products.id = orders.product_id;</pre><p>JOINs matter because real applications genuinely spread their data across many tables, users, orders, products, payments, reviews, and so on, and stuffing all of that into one giant table would cause far more problems than it solves.</p><h3>Why data gets split apart in the first place: normalization</h3><p>Normalization is really just the practice of organizing your database properly so duplicate data doesn’t pile up. Picture a poorly designed orders table that tries to hold everything at once, order id, customer name, customer email, product name, product price, all crammed into one place. If Rahul places a hundred orders, his name and email get repeated a hundred times over, which is wasteful and genuinely fragile.</p><p>A properly normalized design splits that apart instead, a users table holding id, name, and email, a products table holding id, name, and price, and an orders table that simply references both through user_id and product_id. Now duplicate data is minimal.</p><p>Normalizing your schema this way cuts down on repeated data significantly, makes updates far simpler (changing a user’s email means updating one row in one table instead of a hundred scattered copies), and keeps a single, reliable source of truth for every piece of information.</p><p>That said, normalization isn’t a rule to follow blindly everywhere. Real systems balance it against performance needs, and sometimes data does get duplicated on purpose for speed, which is called denormalization. An orders table that stores a customer_name field directly, even though that’s technically duplicated from the users table, might genuinely help order history load faster. It’s a deliberate trade-off, not a mistake, when it’s used with intention.</p><p>When actually designing a database for something like a food delivery app, the process usually starts with identifying the core entities, users, restaurants, food items, orders, payments, deliveries, then figuring out how they relate to each other (a user places orders, an order pulls from a restaurant’s food items), and only then translating that into actual tables. A common beginner mistake is skipping straight to one giant table trying to hold everything, users, orders, products, and payments all mashed together, which causes duplicated data, painfully complex queries, and genuinely risky updates down the line.</p><h3>Indexes: why some queries are fast and others aren’t</h3><p>At some point, every backend developer runs into the same question. Why is this query slow, and how do you actually make it faster? A big part of the answer is indexes.</p><p>An index is essentially a shortcut that helps the database find data quickly, without needing to look through every single row. Think of a massive book. Looking for the word “Database” by checking page 1, then page 2, then page 3, all the way to page 500, would take forever. But if the book has an index at the back pointing straight to page 120, you skip right to it. Database indexes work exactly the same way.</p><p>Without an index, if you search a users table by email and there’s no index on that column, the database checks every single row one by one, something called a full table scan. That’s a non-issue on a table with a hundred rows, but on a table with ten million rows, it turns into a genuinely slow query, higher CPU usage, and a noticeably worse response time.</p><p>Adding an index changes that completely.</p><pre>CREATE INDEX email_index<br>ON users(email);</pre><p>Now the database can jump straight to matching rows instead of scanning everything.</p><p>Primary keys actually get an index automatically the moment you define them, precisely because they tend to get searched constantly.</p><pre>CREATE TABLE users(<br>  id SERIAL PRIMARY KEY<br>);</pre><p>A query like SELECT * FROM users WHERE id=10; needs to be fast, and that automatic index is exactly why it usually is.</p><p>Unique constraints work similarly. Marking a column like email as UNIQUE makes PostgreSQL build a unique index behind the scenes, which does double duty, speeding up searches and preventing duplicate values at the same time. And you can create ordinary indexes yourself wherever a column gets searched frequently, like an index on email for a users table that gets looked up by email a lot.</p><p>Sometimes a query depends on more than one column at once. Say you’re filtering orders by both user_id and status together.</p><pre>SELECT *<br>FROM orders<br>WHERE user_id=10<br>AND status=&#39;completed&#39;;</pre><p>For that, a composite index covering both columns together makes sense.</p><pre>CREATE INDEX order_search_idx<br>ON orders(user_id, status);</pre><p>The order of columns in a composite index actually matters here too. An index built as (user_id, status) helps a query filtering just on user_id, and helps even more when filtering on both user_id and status together, but it won&#39;t help nearly as much for a query that only filters on status alone.</p><p>It’s tempting to think, why not just index every column and make everything fast? The catch is that indexes cost storage space, and they slow down writes. Every time a new row gets inserted, the database has to update every relevant index alongside inserting the actual data, so indexes genuinely trade off read speed against write speed. They’re a clear win for search-heavy applications, but worth using carefully in systems doing heavy, constant data entry.</p><p>PostgreSQL also has something called a query planner running behind the scenes, whose whole job is figuring out the fastest way to actually execute a given query, whether that’s scanning the full table or using an available index, whichever turns out faster. Running EXPLAIN in front of a query shows you exactly what the planner decided, something like &quot;Index Scan using email_index,&quot; confirming the index is actually getting used.</p><p>A real-world example worth picturing, an Amazon-style product search across millions of products by name would be painfully slow without an index like this in place.</p><pre>CREATE INDEX product_name_idx<br>ON products(name);</pre><p>It’s worth keeping indexes and caching mentally separate too, since they’re solving related but distinct problems. An index lives inside the database itself, helping it find rows faster. A cache, something like Redis, typically sits outside the database entirely, storing frequently requested results so the application doesn’t even need to hit the database again for the same thing. Beyond indexing, a few other habits genuinely help production performance: selecting only the specific columns you actually need instead of always reaching for SELECT *, paginating large result sets with LIMIT and OFFSET instead of pulling everything at once, pooling database connections instead of creating new ones constantly, and caching data that gets requested repeatedly.</p><h3>Transactions: how data actually stays safe</h3><p>Real applications don’t just save data, they need to keep it safe, consistent, and correct even when things go wrong halfway through. That’s exactly the problem transactions solve.</p><p>A transaction is a group of database operations that executes as one single unit, either every operation in it completes, or none of them do.</p><p>A bank transfer is the textbook example here. Moving 500 rupees from Rahul’s account to Aman’s account genuinely involves two separate steps, deducting from Rahul’s balance, then adding to Aman’s. If the first step succeeds and the second one fails for whatever reason, Rahul’s money would just vanish without Aman ever receiving it, which is obviously unacceptable.</p><p>A transaction wraps both steps together so either both succeed and get committed, or if anything goes wrong, everything gets rolled back to exactly where it started.</p><pre>BEGIN;</pre><pre>UPDATE accounts<br>SET balance = balance - 500<br>WHERE id=1;</pre><pre>UPDATE accounts<br>SET balance = balance + 500<br>WHERE id=2;</pre><pre>COMMIT;</pre><p>And if something fails partway through, running ROLLBACK undoes everything cleanly, leaving the database exactly as it was before the transaction started.</p><p>Understanding transactions properly really comes down to ACID, four properties that define what a reliable transaction actually guarantees.</p><p>Atomicity means the transaction completes fully or fails entirely, there’s no such thing as a half-finished transaction sitting around, like Rahul losing money while Aman’s balance never actually updates.</p><p>Consistency means the database always stays in a genuinely valid state before and after any transaction, none of its underlying rules ever get violated in the process.</p><p>Isolation deals with multiple things happening at once, say two people trying to buy the last unit of a product in stock at the exact same moment. The database needs to handle that scenario correctly, and isolation is precisely what prevents one transaction from stepping on another mid-operation.</p><p>Durability means once a transaction actually commits successfully, that data is genuinely permanent. A payment going through should still be there even if the server crashes and restarts moments later.</p><p>It’s worth knowing you can technically try to handle something like this at the application level instead, running one operation, then another, in your own code. The problem is obvious once you think it through, if the second operation fails, how do you cleanly undo the first one yourself? That’s exactly the gap database-level transactions exist to close.</p><p>Modern ORMs make this pretty approachable too. In Prisma, wrapping operations in a transaction looks like this.</p><pre>await prisma.$transaction([<br>  prisma.account.update({<br>    where: { id: 1 },<br>    data: { balance: { decrement: 500 } }<br>  }),<br>  prisma.account.update({<br>    where: { id: 2 },<br>    data: { balance: { increment: 500 } }<br>  })<br>]);</pre><p>If either update fails, both roll back together. Drizzle follows the same underlying concept with slightly different syntax.</p><pre>await db.transaction(async (tx) =&gt; {<br>  await tx.update(accounts)<br>    .set({ balance: balance - 500 });</pre><pre>  await tx.update(accounts)<br>    .set({ balance: balance + 500 });<br>});</pre><p>Since multiple transactions can genuinely run at the same time, PostgreSQL also defines isolation levels that control exactly how much transactions are allowed to see of each other’s in-progress work. Read Uncommitted is the loosest level, technically allowing uncommitted data from other transactions to be read. Read Committed, PostgreSQL’s default, only ever shows data that’s actually been committed. Repeatable Read guarantees that the same query run twice inside one transaction returns the exact same result both times. And Serializable, the strictest level, makes concurrent transactions behave as though they ran one after another in strict sequence, never actually overlapping.</p><p>These levels exist specifically to prevent a handful of classic problems. A dirty read happens when one transaction reads data another transaction changed but hasn’t committed yet, and if that first transaction then rolls back, the second one ends up having read data that never actually existed. A non-repeatable read happens when the same query inside one transaction returns different results the second time around, say a balance reading 5000 initially and 4000 moments later, because some other transaction quietly changed it in between. And a phantom read happens when the same query suddenly starts returning entirely new rows that weren’t there before, again because of some other transaction’s changes landing in between reads.</p><p>A concrete e-commerce example ties this all together nicely. Someone clicks “Buy Now,” and the backend needs to create the order, reduce inventory, and save a payment record, all as one unit. If the payment step fails, inventory absolutely should not have been reduced. Wrapping the whole sequence, create order, reduce stock, save payment, inside a single transaction with a clean rollback on failure is exactly how that gets handled correctly.</p><p>Transactions genuinely matter whenever multiple operations depend on each other, banking transfers, e-commerce orders that touch payment and inventory together, ticket booking that reserves a seat and processes payment together, or wallet systems updating a balance alongside its transaction history. They’re not something every tiny query needs though, a plain SELECT * FROM users; has no real need to be wrapped in a transaction. And it&#39;s worth keeping transactions short and quick, since long-running transactions can hold database locks for extended periods, quietly hurting performance and blocking other users in the process.</p><h3>What separates production PostgreSQL from just knowing SQL</h3><p>Everything covered so far, tables, relations, joins, normalization, indexes, transactions, forms a genuinely solid foundation. But being a production-ready backend developer takes a bit more than just knowing how to write queries. It means actually knowing how to design, secure, and optimize a database properly.</p><p>Schema design is really where it all starts, figuring out your database’s actual structure. Building a SaaS product means identifying entities like users, organizations, teams, projects, tasks, and payments, then deciding what tables you need and how they relate. A user creating many projects, for instance, becomes a straightforward one-to-many relationship between a users table and a projects table referencing it through user_id.</p><p>Choosing the right data types matters more than it might seem at first. PostgreSQL gives you integers for numbers, text for strings, booleans for true or false flags, timestamps for dates and times, and importantly, JSON support through the JSONB type, letting you store genuinely flexible structured data like user settings directly inside a column. That last one’s worth remembering, PostgreSQL isn’t limited to rigid traditional tables alone, it happily blends in flexible JSON data where it makes sense.</p><p>Constraints are the rules that stop bad data from ever getting saved in the first place. NOT NULL makes a field mandatory, so an email column can&#39;t end up empty. UNIQUE prevents duplicates, ensuring two users can&#39;t share the same email. CHECK lets you enforce custom rules, like requiring age to be at least 18. And foreign key constraints protect relationships directly, refusing to save a user_id that doesn&#39;t actually correspond to a real user.</p><p>Security deserves real attention too. Passwords should never sit in a database as plain text, ever, since a leak would expose every single one instantly. They should be hashed instead, using something like bcrypt or argon2, so what actually gets stored is unreadable without the original password. SQL injection is another real risk worth guarding against, string-concatenating user input directly into a query is dangerous, and parameterized queries are the safer way to go. Most modern ORMs like Prisma and Drizzle handle this protection for you automatically, which is one more reason they’re so widely used.</p><p>Migrations matter because production schemas genuinely change over time, adding a phone column to an existing users table, for instance. Manually editing a live production database directly is risky, which is exactly why migrations exist, tracked, versioned changes like ALTER TABLE users ADD COLUMN phone TEXT; that keep a clear history of every structural change made along the way.</p><p>Backups are non-negotiable too, protecting against server crashes, accidental deletions, or data corruption, whether through full backups of the entire database or incremental backups capturing just what’s changed.</p><p>Connection pooling avoids the real cost of spinning up a brand new database connection for every single request, reusing a small set of existing connections instead. And larger applications sometimes split reads and writes entirely, sending writes to a main database and reads to a replica, spreading load and improving overall performance.</p><p>Monitoring rounds all of this out, keeping an eye on query time, CPU usage, memory usage, active connections, and slow queries, since production issues tend to show up as patterns in these metrics long before they become outright failures.</p><p>A typical real backend request, someone signing up, ties all of this together, the request gets validated, the password gets hashed, the user gets inserted, and a response goes back, with an ORM sitting between your backend code and PostgreSQL the whole way through.</p><h3>Where all of this leaves you</h3><p>If you’re actually learning PostgreSQL properly, a reasonable order looks something like this. Start with the basics, tables, rows, columns, and the core CRUD operations, select, insert, update, delete. Move into relationships next, primary keys, foreign keys, and the one-to-one, one-to-many, and many-to-many patterns. From there, get comfortable with more advanced SQL, joins, group by, having, subqueries, views, and functions. Then focus on performance, indexes, the query planner, EXPLAIN, and general optimization. And finally, round it out with production concerns, transactions, migrations, backups, security, and replication.</p><p>A common modern stack pairs all of this with TypeScript, Node.js, Express or Fastify, and an ORM like Prisma or Drizzle sitting on top of PostgreSQL, with a request flowing from the API through a controller, into a service, through Prisma, and finally down into PostgreSQL itself.</p><p>PostgreSQL, at the end of the day, isn’t just a database. It’s a genuinely complete data management system. A strong backend developer understands how to actually design data properly, how to build relationships that make sense, how to optimize queries when they need it, and how to keep data safe under real conditions. Choosing which database to use matters, sure, but designing it well matters even more. Once these fundamentals are genuinely solid, picking up PostgreSQL, MySQL, MongoDB, or whatever comes next becomes far less intimidating, because a database is really just a tool. The actual skill worth building is understanding a problem deeply enough to design the right data structure for it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93760ee4c9a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PostgreSQL vs MongoDB: The Real Difference Between SQL and NoSQL]]></title>
            <link>https://surajsrggupta.medium.com/postgresql-vs-mongodb-the-real-difference-between-sql-and-nosql-79caafd5028f?source=rss-761b5c125020------2</link>
            <guid isPermaLink="false">https://medium.com/p/79caafd5028f</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Mr. S. Gupta]]></dc:creator>
            <pubDate>Fri, 04 Sep 2026 10:02:52 GMT</pubDate>
            <atom:updated>2026-09-04T10:02:52.308Z</atom:updated>
            <content:encoded><![CDATA[<p>Choosing a database is one of the bigger decisions in backend development, and this exact confusion tends to show up the moment a new project starts. Should I go with PostgreSQL, or should I go with MongoDB?</p><p>Some people will tell you SQL is old and NoSQL is the modern way to go. Others will insist MongoDB scales better and PostgreSQL just can’t keep up. Both of these takes are incomplete, and honestly a bit misleading.</p><p>The truth is that SQL and NoSQL are two different philosophies, each built to solve a different kind of problem. There’s no universally “best” database out there. Once you actually understand what each of these really is, deciding between them stops being a guessing game.</p><h3>What a database is actually for</h3><p>A database’s job is genuinely simple, it stores your application’s data. If you’re building an e-commerce app, you need somewhere to keep users, products, orders, payments, and reviews. All of that data ends up in a database one way or another, the only real question is how it gets organized once it’s there.</p><h3>What a SQL database actually is</h3><p>SQL stands for Structured Query Language, and SQL databases are also called relational databases. PostgreSQL, MySQL, Oracle Database, and Microsoft SQL Server are all common examples. In all of them, data lives inside tables.</p><p>Take a simple users table.</p><pre>Users Table</pre><pre>+----+---------+-------------------+<br>| id | name    | email             |<br>+----+---------+-------------------+<br>| 1  | Rahul   | rahul@test.com    |<br>| 2  | Aman    | aman@test.com     |<br>+----+---------+-------------------+</pre><p>And an orders table.</p><pre>Orders Table</pre><pre>+----+---------+--------+<br>| id | user_id | amount |<br>+----+---------+--------+<br>| 1  | 1       | 500    |<br>| 2  | 1       | 900    |<br>| 3  | 2       | 300    |<br>+----+---------+--------+</pre><p>There’s a relationship here, one user can have many orders, and that’s exactly why these are called relational databases.</p><p>PostgreSQL is simply a relational SQL database. Data lives in tables, relationships are explicit, you write actual SQL to interact with it, and you get strong consistency guarantees.</p><pre>SELECT *<br>FROM users<br>WHERE id = 1;</pre><p>This is why PostgreSQL shows up so often in SaaS applications, banking systems, enterprise software, and e-commerce platforms.</p><h3>What MongoDB actually is</h3><p>MongoDB is a NoSQL database, and NoSQL originally just meant “not only SQL.” It doesn’t mean NoSQL databases are somehow better than SQL ones, it just means they organize data differently than tables. MongoDB specifically is a document based database.</p><p>Where SQL structures things as tables full of rows and columns, MongoDB structures things as collections full of documents, and those documents look a lot like JSON.</p><pre>{<br> &quot;_id&quot;: 1,<br> &quot;name&quot;: &quot;Rahul&quot;,<br> &quot;email&quot;: &quot;rahul@test.com&quot;,<br> &quot;orders&quot;: [<br>   {<br>    &quot;product&quot;: &quot;Laptop&quot;,<br>    &quot;price&quot;: 50000<br>   }<br> ]<br>}</pre><p>It looks like JSON, but technically it isn’t. MongoDB internally stores things as BSON, which is basically binary JSON.</p><p>One thing worth clearing up here, MongoDB doesn’t just store raw JSON files. The documents look JSON-like, but under the hood the database engine still handles indexing, query processing, and storage optimization properly. It’s a full database engine, not just a glorified file store.</p><h3>The two philosophies think about data differently</h3><p>SQL’s whole approach is, keep your data separated across different tables and connect them through relationships. This is called normalization. In an e-commerce app, that means users, orders, and products all sit in their own tables, linked together through relations.</p><p>MongoDB flips that idea around, whatever data you tend to access together, store it together. You could call this denormalization.</p><p>Think of an Instagram style profile page as a real example. A user needs their name, bio, profile picture, and recent posts. In MongoDB, all of that can live in one single document.</p><pre>{<br>&quot;name&quot;: &quot;Rahul&quot;,<br>&quot;bio&quot;: &quot;Developer&quot;,<br>&quot;posts&quot;: [<br>  {<br>   &quot;title&quot;: &quot;My first post&quot;<br>  }<br>]<br>}</pre><p>In PostgreSQL, that same data would be split, a users table and a separate posts table, joined together to fetch the full picture.</p><pre>SELECT *<br>FROM users<br>JOIN posts<br>ON users.id = posts.user_id;</pre><p>A common myth is that MongoDB doesn’t support relationships at all. It does, MongoDB’s design just doesn’t center around joins the way relational databases do. You can absolutely store something like a userId field to represent a relationship yourself, the database just won&#39;t manage that relationship as efficiently or natively as SQL does.</p><p>Firestore falls into this same document database category, collections holding documents, documents holding fields. The structure looks a lot like MongoDB’s, but they aren’t the same product. Both are NoSQL, both are document based, both store JSON-like data, but MongoDB is a general purpose database built for complex querying and works fine self hosted or on managed cloud, while Firestore lives inside Google’s Firebase ecosystem, leans heavily into real-time applications, and follows a serverless approach.</p><h3>The biggest real difference: joins vs embedding</h3><p>This is really the core conceptual split between SQL and NoSQL, they organize data in fundamentally different ways.</p><p>Say you’re building an e-commerce app with users, orders, and products. In PostgreSQL, the structure looks like this.</p><pre>Users</pre><pre>id<br>name<br>email</pre><pre>Products</pre><pre>id<br>name<br>price</pre><pre>Orders</pre><pre>id<br>user_id<br>product_id<br>quantity</pre><p>Every entity gets its own table, because each one genuinely serves a different purpose. Pulling Rahul’s orders means writing something like this.</p><pre>SELECT<br>users.name,<br>products.name,<br>orders.quantity<br>FROM users<br>JOIN orders<br>ON users.id = orders.user_id<br>JOIN products<br>ON products.id = orders.product_id<br>WHERE users.id = 1;</pre><p>The tables are connected here, and that connecting operation is what a join actually is.</p><p>In MongoDB, that same data can live inside one document.</p><pre>{<br> &quot;_id&quot;: 1,<br> &quot;name&quot;: &quot;Rahul&quot;,<br> &quot;orders&quot;: [<br>  {<br>   &quot;product&quot;: &quot;Laptop&quot;,<br>   &quot;quantity&quot;: 1<br>  },<br>  {<br>   &quot;product&quot;: &quot;Mouse&quot;,<br>   &quot;quantity&quot;: 2<br>  }<br> ]<br>}</pre><p>All of Rahul’s orders are already sitting right there, no joins needed at all.</p><p>Which one’s better really just depends on the situation. A banking system deals with accounts, transactions, and balances, data where a mistake is genuinely expensive, and it needs strong consistency, real transactions, and clean relationships, which makes PostgreSQL a strong pick there. On the other hand, something like an Instagram feed, where likes, comments, images, and metadata are all accessed together constantly, tends to feel a lot more natural as a document model.</p><p>Both approaches come with their own trade-offs too. In PostgreSQL, if joins start getting genuinely complex, users, orders, payments, products, and reviews all tangled together, queries can get messy fast. In MongoDB, if the same piece of data ends up duplicated across many documents, say a laptop’s price repeated in several different orders, and that price ever changes, you could end up needing to update multiple documents just to keep things consistent, which turns into a real maintenance headache.</p><p>A chat app like WhatsApp is a good example of where documents feel natural, messages within a conversation group together on their own.</p><pre>{<br>&quot;conversationId&quot;: 100,<br>&quot;messages&quot;: [<br> {<br>  &quot;from&quot;: &quot;Rahul&quot;,<br>  &quot;text&quot;: &quot;Hello&quot;<br> },<br> {<br>  &quot;from&quot;: &quot;Aman&quot;,<br>  &quot;text&quot;: &quot;Hi&quot;<br> }<br>]<br>}</pre><h3>Transactions, where SQL genuinely shines</h3><p>A transaction means bundling multiple database operations into one single unit, either everything happens, or nothing does.</p><p>A bank transfer is the classic way to think about this. Deducting 1000 rupees from Rahul’s account and adding 1000 to Aman’s account both need to happen together. If the first step succeeds and the second one fails, that’s a genuinely serious problem.</p><pre>BEGIN;</pre><pre>UPDATE accounts<br>SET balance = balance - 1000<br>WHERE id = 1;</pre><pre>UPDATE accounts<br>SET balance = balance + 1000<br>WHERE id = 2;</pre><pre>COMMIT;</pre><p>If something goes wrong partway through, running ROLLBACK reverts the database back to where it was before anything happened.</p><p>Relational databases lean heavily on a concept called ACID here. Atomicity means either the whole operation completes or none of it does. Consistency means the database always stays in a valid state. Isolation means multiple transactions running at once won’t incorrectly interfere with each other. And durability means once data is saved, it isn’t going anywhere.</p><p>MongoDB does support transactions too, which is worth clearing up because a lot of people assume it doesn’t. It does, it’s just that in relational databases, transactions and relationships are baked into the core design, whereas in MongoDB, document based operations are the more natural, common way of working.</p><h3>The truth about scaling</h3><p>One line that gets thrown around a lot is “MongoDB scales better.” That statement is incomplete on its own. Scaling actually comes in two flavors, vertical scaling, which just means making a server more powerful (say, going from 8GB of RAM to 64GB), and horizontal scaling, which means adding more servers instead of a bigger one.</p><p>MongoDB’s design is genuinely friendly toward distributed systems, supporting things like sharding and distributed storage well for large datasets. But PostgreSQL scales too, through read replicas, partitioning, caching, and query optimization, and today it’s genuinely used in plenty of large scale applications without issue.</p><p>Performance comparisons follow a similar pattern. Fetching a simple user profile can be equally fast in either database. Complex relational queries, like pulling total purchases, last order date, and average order value per customer, tend to be naturally strong in SQL. And flexible, changing data, like a user’s settings object, tends to feel more natural in MongoDB.</p><p>The schema approach also differs quite a bit. SQL defines its schema upfront, and the structure stays fixed.</p><pre>CREATE TABLE users(<br> id INT,<br> name TEXT,<br> email TEXT<br>);</pre><p>MongoDB documents are flexible by nature, one user might just have a name field, another might have name, age, and city, and both are perfectly valid.</p><p>That flexibility isn’t automatically a good thing though. If a hundred developers are all saving data with slightly different shapes, some using name, others using username, things get genuinely hard to maintain over time. This is exactly where SQL&#39;s fixed schema becomes an advantage, the database itself enforces rules, like making an email field NOT NULL so incomplete or invalid data can never sneak in.</p><h3>What this actually looks like in a real project</h3><p>Picture a full e-commerce application with users, products, cart, orders, payments, and inventory.</p><p>In PostgreSQL, every entity gets its own table, users, products, orders, order items, and payments, all connected through relationships.</p><p>In MongoDB, that same data might live inside a single document like this.</p><pre>{<br> &quot;_id&quot;: 101,<br> &quot;customer&quot;: &quot;Rahul&quot;,<br> &quot;orders&quot;: [<br>  {<br>   &quot;orderId&quot;: 500,<br>   &quot;items&quot;: [<br>    {<br>     &quot;product&quot;: &quot;Laptop&quot;,<br>     &quot;price&quot;: 50000<br>    }<br>   ],<br>   &quot;payment&quot;: {<br>    &quot;status&quot;: &quot;paid&quot;<br>   }<br>  }<br> ]<br>}</pre><p>Both approaches genuinely work in real projects, it just comes down to which trade-offs you’re more willing to live with.</p><p>Firestore and MongoDB also structure things a little differently. Firestore goes collections holding documents holding fields, while MongoDB adds one more layer, a database holding collections, holding documents, holding fields. Firestore’s whole focus is real-time updates, mobile apps, and serverless development, think a chat app where a message sent by one user instantly shows up for another. MongoDB is more of a general purpose tool, better suited for backend APIs, large applications, and flexible data models overall.</p><p>Querying differs too. Firestore’s queries are intentionally limited, which works great for simple filtering, while MongoDB supports much more complex querying, range filters, aggregations, and a lot more besides.</p><h3>Can MongoDB actually replace PostgreSQL</h3><p>This question comes up constantly, and the honest answer is, sometimes, but definitely not everywhere.</p><p>MongoDB tends to make more sense when your data’s structure keeps changing, like a CMS where today you only need a title and description, and tomorrow you’re adding video and metadata fields too. It also makes sense when a document naturally represents one complete, self contained unit, like a product catalog entry with its own specifications baked in.</p><p>PostgreSQL tends to make more sense when relationships between your data are genuinely strong, like the chain from customer to orders to payments to invoices. It’s also the better call when accuracy is truly critical, think finance, healthcare, or enterprise systems, or when you need serious reporting capability, like last quarter’s revenue broken down by customer segment, something SQL handles naturally well.</p><p>If you’re building a fairly standard SaaS product, authentication, a dashboard, payments, users, teams, PostgreSQL is a safe default, mainly because most SaaS data is fundamentally relational underneath. But if you’re building a chat app, a real-time feed, or a flexible content platform, MongoDB can genuinely be the better fit.</p><p>It’s also worth knowing that modern applications often go hybrid anyway. Main application data sitting in PostgreSQL, analytics data in MongoDB, and a cache layer in Redis, using a different tool for a different problem is completely normal in practice.</p><h3>So how do you actually decide</h3><p>The wrong question to ask when picking a database is which one’s more popular, or which one’s newer technology. The right question is, what does my application’s data actually look like, and how will it actually be used?</p><p>If there are strong relationships in your data, like the chain from customer to orders to payments in e-commerce, or account to transactions in banking, or employee to department in an HR system, SQL databases are the strong choice, and PostgreSQL fits naturally.</p><p>If your application’s structure keeps shifting, like a content platform where new fields get added constantly, document databases like MongoDB become genuinely convenient.</p><p>If you need complex queries, like total revenue, average order value, and purchase frequency for premium customers over the last six months, relational databases are naturally the stronger tool.</p><pre>SELECT<br>customer_id,<br>SUM(amount),<br>AVG(amount)<br>FROM orders<br>GROUP BY customer_id;</pre><p>And if real-time updates genuinely matter, chat, live location tracking, multiplayer experiences, collaboration tools, something like Firebase Firestore becomes useful, where one user’s edit shows up instantly for everyone else watching.</p><p>Put side by side, PostgreSQL is best suited for SaaS applications, banking systems, e-commerce, ERP, and enterprise software, with real strengths in relationships, transactions, complex queries, and data integrity, though schema changes need to be managed carefully. MongoDB is best suited for flexible data, content systems, large document heavy data, and rapid development, with strengths in flexible schemas, the document model, and easy horizontal scaling, though complex relationships need extra planning upfront. Firestore is best suited for mobile apps, real-time applications, and anything living in the Firebase ecosystem, with strengths in real-time updates, easy setup, and a genuinely serverless experience, though complex querying has real limitations and cost planning matters more here than people expect.</p><p>Feature PostgreSQL MongoDB Firestore Type SQL NoSQL Document NoSQL Document Data Model Tables Documents Documents Relations Excellent Limited / not natural Limited Transactions Excellent Supported Supported Flexible Schema Medium Excellent Excellent Complex Queries Excellent Good Limited Real-time Extra setup Possible Excellent Learning Value Very High High Medium</p><p>A misconception worth putting to rest, SQL isn’t outdated just because it’s old. Being old and being outdated are two different things entirely, HTTP is old too, and it’s still the backbone of the entire internet. PostgreSQL today comes with genuinely modern capabilities, JSON support, full text search, and a long list of extensions. And the idea that NoSQL is “the future” while SQL fades out doesn’t really hold up either, both are going to matter for a long time, and most real world systems actually use them together. A food delivery app is a good example, users and orders sitting in PostgreSQL, live driver location in Redis or some other NoSQL store, and analytics living in a separate data warehouse entirely.</p><p>If you’re learning backend development, a reasonable order to follow looks like this. Start with PostgreSQL and SQL first, since the fundamentals, tables, relationships, constraints, transactions, all become genuinely clear there. Then pick up MongoDB’s basics, documents, collections, embedding, and referencing. After that, learn an ORM like Prisma or Drizzle, so you understand what problem an ORM is actually solving and how it makes database access easier day to day.</p><p>A genuinely strong backend developer doesn’t say “I only use MongoDB” or “I only use PostgreSQL.” They say, “I know which database fits which problem.”</p><p>Choosing a database was never really about chasing whatever’s trending. It’s about actually understanding what your application needs. If you need strong relationships, accurate transactions, and serious reporting, PostgreSQL is a strong choice. If you need flexible documents, rapid changes, and document based data, MongoDB is genuinely useful. And if you need a real-time mobile experience, Firebase’s ecosystem, and fast development, Firestore is a solid option. An experienced developer never treats a database like a religion, they look at the actual problem first, and only then pick the tool that fits it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79caafd5028f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Express Actually Talks to a Database: From HTTP Request to SQL Query]]></title>
            <link>https://surajsrggupta.medium.com/how-express-actually-talks-to-a-database-from-http-request-to-sql-query-67a55a26787b?source=rss-761b5c125020------2</link>
            <guid isPermaLink="false">https://medium.com/p/67a55a26787b</guid>
            <category><![CDATA[dbms]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[mern-stack]]></category>
            <category><![CDATA[prisma]]></category>
            <dc:creator><![CDATA[Mr. S. Gupta]]></dc:creator>
            <pubDate>Sun, 30 Aug 2026 14:02:02 GMT</pubDate>
            <atom:updated>2026-08-30T14:02:02.495Z</atom:updated>
            <content:encoded><![CDATA[<p>When beginners start learning backend development, they usually pick up things one at a time and separately, Express routes here, controllers there, middleware somewhere else, then databases, then Prisma, then authentication. Each piece makes sense on its own.</p><p>But one question tends to linger even after all that. When a user clicks something on a website, what’s actually happening behind the scenes, step by step?</p><p>Say someone opens an e-commerce site and clicks “Show my orders.” What happens right after that click? Does Express talk to the database directly? Does Prisma just handle everything on its own? Where exactly does authentication slot in, and where does the actual SQL query get executed? Once this full flow actually clicks, backend development stops feeling like a pile of disconnected pieces.</p><h3>The big picture</h3><p>A modern backend app generally looks something like this.</p><pre>Frontend Application<br>        |<br>        v<br>HTTP Request<br>        |<br>        v<br>Express Server<br>        |<br>        v<br>Routes<br>        |<br>        v<br>Controllers<br>        |<br>        v<br>Services<br>        |<br>        v<br>Database Layer<br>        |<br>        v<br>PostgreSQL Database</pre><p>Each layer here has its own job, so let’s walk through them one at a time.</p><p><strong>The user sends a request.</strong> Say someone clicks “View Profile.” The frontend fires off an HTTP request, something like GET /api/profile, carrying a method, a URL, maybe an authorization header, and sometimes a body. The browser genuinely has no idea your database even exists, it only ever talks to your backend API.</p><p><strong>The request reaches the Express server</strong>, which is just sitting there running somewhere, waiting.</p><pre>import express from &quot;express&quot;;</pre><pre>const app = express();</pre><pre>app.listen(3000, () =&gt; {<br>  console.log(&quot;Server running&quot;);<br>});</pre><p>The moment that GET /api/profile request arrives, Express picks it up.</p><p><strong>The router figures out where it goes.</strong> A real app has dozens of endpoints, /api/users, /api/products, /api/orders, /api/payments, and the router&#39;s whole job is deciding which piece of code handles which one.</p><pre>router.get(&quot;/profile&quot;, getProfile);</pre><p>In plain terms, if someone hits GET /profile, run the getProfile function.</p><p><strong>Middleware runs before the controller ever sees the request.</strong> Think of it as a checkpoint the request has to pass through first.</p><pre>Request<br>   ↓<br>Authentication Middleware<br>   ↓<br>Validation Middleware<br>   ↓<br>Controller</pre><p>Say a request comes in with Authorization: Bearer token123. The middleware&#39;s job is simply asking, is this token actually valid?</p><pre>function authMiddleware(req, res, next) {<br>  const token = req.headers.authorization;</pre><pre>  if (!token) {<br>    return res.status(401).json({<br>      message: &quot;Unauthorized&quot;<br>    });<br>  }</pre><pre>  next();<br>}</pre><p>If everything checks out, next() runs and the request keeps moving forward.</p><p><strong>The controller takes over.</strong></p><pre>async function getProfile(req, res) {<br>  const userId = req.user.id;</pre><pre>  const profile = await userService.getProfile(userId);</pre><pre>  res.json(profile);<br>}</pre><p>A controller’s real job is just taking the request, pulling out what it needs, calling whatever service handles the actual work, and sending back a response. It really shouldn’t be carrying heavy database logic itself.</p><p><strong>The service layer handles the actual business logic.</strong></p><pre>async function getProfile(userId) {<br>  const user = await prisma.user.findUnique({<br>    where: { id: userId }<br>  });</pre><pre>  return user;<br>}</pre><p>This is where the real database call happens.</p><p><strong>Prisma steps in here.</strong> When your code calls prisma.user.findUnique(), Prisma quietly builds the actual SQL behind it, something like SELECT * FROM users WHERE id = 1;, and PostgreSQL runs it.</p><pre>Service<br>   ↓<br>Prisma<br>   ↓<br>SQL Query<br>   ↓<br>PostgreSQL<br>   ↓<br>Result</pre><p><strong>The database sends data back</strong>, something like { &quot;id&quot;: 1, &quot;name&quot;: &quot;Rahul&quot;, &quot;email&quot;: &quot;rahul@test.com&quot; }, and it travels all the way back up through Prisma, the service, the controller, the Express response, and finally lands back at the frontend.</p><p>Put the whole thing together and you get this complete picture, from the click all the way to the UI updating.</p><pre>User Clicks Button<br>        |<br>Frontend Sends HTTP Request<br>        |<br>Express Server<br>        |<br>Router<br>        |<br>Middleware<br>        |<br>Controller<br>        |<br>Service<br>        |<br>Prisma / Drizzle / SQL<br>        |<br>PostgreSQL<br>        |<br>Response Returns<br>        |<br>Frontend Updates UI</pre><p>A question that comes up a lot at this point is, why not just call the database straight from the controller? Technically, you absolutely can.</p><pre>app.get(&quot;/users&quot;, async (req, res) =&gt; {<br>  const users = await prisma.user.findMany();<br>  res.json(users);<br>});</pre><p>That’ll work fine for a small project. The trouble shows up once the app grows, controllers stacked directly on the database without any layers in between tend to balloon in size, logic gets duplicated all over the place, testing becomes a pain, and maintaining any of it gets genuinely difficult over time. With proper layering, routes to controllers to services to a dedicated database layer, code stays organized, testing gets easier, teams can actually work in parallel without stepping on each other, and future changes stay contained instead of rippling everywhere.</p><h3>Where does all this code actually live</h3><p>Knowing the flow is one thing, but figuring out where this code should actually sit inside a real project is the next question worth answering.</p><p>Beginners typically start with something dead simple.</p><pre>src<br>├── index.ts<br>├── routes.ts<br>└── database.ts</pre><p>That’s genuinely fine for a small project. But as users pile up, products get added, payments show up, authentication gets bolted on, keeping everything crammed into a couple of files stops being manageable.</p><p>A more production style layout tends to look like this.</p><pre>src<br>├── index.ts<br>├── app.ts<br>├── config<br>│   └── env.ts<br>├── routes<br>│   ├── user.routes.ts<br>│   └── product.routes.ts<br>├── controllers<br>│   ├── user.controller.ts<br>│   └── product.controller.ts<br>├── services<br>│   ├── user.service.ts<br>│   └── product.service.ts<br>├── repositories<br>│   ├── user.repository.ts<br>│   └── product.repository.ts<br>├── db<br>│   └── prisma.ts<br>├── middleware<br>│   ├── auth.ts<br>│   └── error.ts<br>├── validators<br>└── utils</pre><p>Every folder here is pulling its own weight. index.ts is really just the entry point, its only job is starting the server, nothing more.</p><pre>import app from &quot;./app&quot;;</pre><pre>app.listen(3000, () =&gt; {<br>  console.log(&quot;Server running&quot;);<br>});</pre><p>app.ts is where the Express app actually gets configured, middleware loaded, routes wired up.</p><pre>import express from &quot;express&quot;;<br>import userRoutes from &quot;./routes/user.routes&quot;;</pre><pre>const app = express();</pre><pre>app.use(express.json());</pre><pre>app.use(&quot;/api/users&quot;, userRoutes);</pre><pre>export default app;</pre><p>The routes layer’s whole job is deciding which URL goes to which controller, nothing about the database belongs here.</p><pre>router.get(&quot;/profile&quot;, getProfile);</pre><p>The controller layer handles request and response, pulling data out and handing it off.</p><pre>export async function getProfile(req, res) {<br>  const user = await userService.getProfile(req.user.id);<br>  res.json(user);<br>}</pre><p>The service layer is where the actual business logic lives, deciding what needs to happen, in what order, and under what rules.</p><pre>export async function getProfile(userId: number) {<br>  const user = await userRepository.findById(userId);<br>  return user;<br>}</pre><p>The repository layer is what talks directly to the database.</p><pre>export async function findById(id: number) {<br>  return prisma.user.findUnique({<br>    where: { id }<br>  });<br>}</pre><p>Here’s the real payoff of splitting things this way. If Prisma ever got swapped out for Drizzle down the line, only the repository layer would need to change, the service code sitting above it wouldn’t need to know or care. That’s really the whole point of the repository pattern.</p><p>And the database layer itself is usually just one shared client instance.</p><pre>import { PrismaClient } from &quot;@prisma/client&quot;;</pre><pre>export const prisma = new PrismaClient();</pre><p>It’s worth flagging why this matters, because beginners sometimes create a fresh Prisma client inside every single request.</p><pre>app.get(&quot;/users&quot;, async (req, res) =&gt; {<br>  const prisma = new PrismaClient();<br>});</pre><p>That’s a genuinely bad habit, since it can spin up way too many database connections and hurt performance badly. Sticking to a single shared instance, sitting on top of a proper connection pool, is the better approach.</p><pre>Application<br>   ↓<br>Single Prisma Client<br>   ↓<br>Database Connection Pool<br>   ↓<br>PostgreSQL</pre><p>A login flow is a good example of how all these layers cooperate. A POST /login request moves through the route, into the controller, into an auth service, which hits the database, checks the password, generates a JWT, and finally sends back a response.</p><pre>const user = await userService.findByEmail(email);</pre><pre>const valid = await bcrypt.compare(password, user.password);</pre><pre>const token = jwt.sign({ id: user.id });</pre><p>User input should never head straight to the database untouched either. Something like { &quot;name&quot;: &quot;&quot;, &quot;email&quot;: &quot;wrong-email&quot; } needs to pass through a validation layer first, usually something like Zod, Joi, or Yup.</p><pre>const schema = z.object({<br>  email: z.string().email(),<br>});</pre><p>Errors deserve real handling too, not just a stray console.log(error) buried in a try-catch. A cleaner approach routes errors through dedicated middleware instead.</p><pre>app.use((error, req, res, next) =&gt; {<br>  res.status(500).json({<br>    message: &quot;Something went wrong&quot;<br>  });<br>});</pre><p>Put together, the full architecture looks like this.</p><pre>Client<br>   ↓<br>Routes<br>   ↓<br>Controllers<br>   ↓<br>Services<br>   ↓<br>Repositories<br>   ↓<br>Prisma / Drizzle<br>   ↓<br>PostgreSQL</pre><p>None of this is mandatory for every project though. A small app can genuinely get by with just routes, controllers, a db folder, and an entry file. Services and repositories are things you layer in as the project actually grows into needing them, not something you’re required to bolt on from day one. The real goal here was never piling on more folders for their own sake, it’s making sure every piece has a clear, single responsibility. If the database ever needs to change, the whole app shouldn’t need rewriting. If auth logic changes, only auth related code should need touching. That’s really what a maintainable backend comes down to.</p><h3>What’s actually happening between Express, the ORM, and the database</h3><p>There’s still one layer worth pulling apart properly, what’s actually going on inside that database layer. When you write await prisma.user.findMany() or await db.select().from(users), what actually reaches the database? Does Prisma talk to PostgreSQL directly? How does a connection even get established? And what happens when a hundred people hit your API at the same exact moment?</p><p>The flow isn’t quite as direct as beginners often assume. It’s not just Express straight to database, it’s really more like this.</p><pre>Express Application<br>   ↓<br>Database Client / ORM<br>   ↓<br>Database Driver<br>   ↓<br>Database Server</pre><p>Or more concretely.</p><pre>Express<br>   ↓<br>Prisma Client<br>   ↓<br>PostgreSQL Driver<br>   ↓<br>PostgreSQL</pre><p>A database driver is really just the software layer handling the actual back and forth between your app and the database. Connecting Node.js to PostgreSQL usually starts with installing the pg package.</p><pre>import { Pool } from &quot;pg&quot;;</pre><pre>const pool = new Pool({<br>  connectionString: process.env.DATABASE_URL<br>});</pre><p>That driver’s job is opening connections, sending queries, and handing results back. Prisma doesn’t reinvent PostgreSQL’s wire protocol itself, it sits on top of a driver underneath it.</p><pre>Your Code<br>   ↓<br>Prisma<br>   ↓<br>Database Driver<br>   ↓<br>PostgreSQL</pre><p>So await prisma.user.findMany() becomes SELECT * FROM users; under the hood, and the driver is what actually carries that query over to the database.</p><p>When your app first starts up, the database client gets initialized, though the actual connection usually isn’t opened right away, it tends to get established only when it’s actually needed, sometimes called a lazy connection.</p><pre>Server Start<br>   ↓<br>Database Client Initialize<br>   ↓<br>Connection Available<br>   ↓<br>Requests Accept</pre><p>This is where connection pooling becomes a genuinely important concept. Picture a hundred users hitting your API at once. If every single request tried spinning up a brand new database connection from scratch, the database would get overwhelmed pretty fast. That’s exactly what connection pools exist to prevent, a small set of ready-to-go connections sitting in a pool.</p><pre>Application<br>   ↓<br>Connection Pool<br>[Connection 1] [Connection 2] [Connection 3]<br>   ↓<br>PostgreSQL</pre><p>A request comes in, grabs whatever connection’s free, does its work, and hands that connection back to the pool once it’s done. Say your pool caps out at 10 connections and 100 users show up at once, the first 10 requests grab connections right away, and everyone else just waits their turn until one frees up.</p><p>Development and production databases also tend to look pretty different day to day. Locally you’re often just running something like PostgreSQL in a Docker container.</p><pre>docker run postgres</pre><p>In production, you’re usually looking at a managed PostgreSQL service instead, something like AWS RDS, Neon, Supabase’s PostgreSQL offering, or Railway.</p><p>And database credentials should never be hardcoded directly into your code.</p><pre>// don&#39;t do this<br>const db = &quot;postgres://user:password@localhost&quot;;</pre><p>That’s both a security risk and a deployment headache waiting to happen. Environment variables are the better home for this.</p><pre>DATABASE_URL=postgresql://user:password@host/database</pre><pre>const url = process.env.DATABASE_URL;</pre><p>Tracing a real request end to end makes all of this click. Say a GET /api/users/10 request comes in. Express routes it through router.get(&quot;/users/:id&quot;, getUser). The controller pulls the id out of the params and calls the service. The service calls the repository. The repository calls prisma.user.findUnique({ where: { id } }), which Prisma turns into SELECT * FROM users WHERE id=10;. PostgreSQL runs that, finds the row, and hands it back. From there it travels back up through Prisma, the repository, the service, the controller, and out through Express to the browser as something like { &quot;id&quot;: 10, &quot;name&quot;: &quot;Rahul&quot;, &quot;email&quot;: &quot;rahul@test.com&quot; }.</p><p>Validation and authentication both slot in before the database ever gets touched. Registration data gets checked by something like Zod before it’s allowed anywhere near the database. Protected routes run through JWT middleware first, and if that token’s invalid, the database query simply never executes at all.</p><p>None of this is just academic trivia either. If you only ever memorize Prisma syntax or Express routing without understanding this flow, you can absolutely build things that work. But the moment something actually breaks, a slow query, a failing database connection, memory creeping up, a sluggish API response, that’s exactly when understanding this architecture actually pays off. Backend development was never really about memorizing syntax. It’s about understanding the journey a request takes from start to finish.</p><h3>Pulling it all together</h3><p>Putting the entire journey in one place looks like this.</p><pre>User Request<br>   ↓<br>Express Server<br>   ↓<br>Route<br>   ↓<br>Middleware<br>   ↓<br>Controller<br>   ↓<br>Service<br>   ↓<br>Repository<br>   ↓<br>ORM / Database Driver<br>   ↓<br>Database<br>   ↓<br>Response</pre><p>Or laid out as a full production style diagram.</p><pre>Client<br>                       |<br>                       v<br>                HTTP Request<br>                       |<br>                       v<br>                Express Server<br>                       |<br>                       v<br>                   Router<br>                       |<br>                       v<br>                Middleware Layer<br>          (Auth, Validation, Logging)<br>                       |<br>                       v<br>                  Controller<br>                       |<br>                       v<br>                   Service<br>              (Business Logic)<br>                       |<br>                       v<br>                 Repository<br>              (Database Logic)<br>                       |<br>                       v<br>            Prisma / Drizzle / SQL<br>                       |<br>                       v<br>                PostgreSQL</pre><p>A lot of beginners end up wondering whether the API itself is basically the database. It’s not, an API is really just a communication layer. The frontend asks for something, GET /api/products say, and the backend decides whether that user&#39;s allowed to see it, what data actually needs fetching, what query the database needs, and how the response should be shaped. The API&#39;s really just acting as the messenger in between.</p><p>And there’s a good reason the frontend never talks to the database directly, even though some databases technically allow it. Exposing credentials directly to the frontend is a straightforward security risk, since anyone poking around the client code could grab them. Business rules also need somewhere to live, checking stock availability, verifying payment completion, making sure a user isn’t banned, and none of that belongs sitting in the frontend. And directly exposing a production database to the open internet is just asking for trouble. The safer shape is always frontend to backend API to database, never frontend straight to database.</p><h3>Mistakes that tend to show up along the way</h3><p>Cramming everything into the controller is a really common one early on, validating users, checking products, calculating prices, updating the database, sending emails, building the response, all crammed into one route handler. It works at first, but that controller balloons into a thousand line mess pretty quickly on a bigger project. Splitting things into controller, service, and repository keeps that from happening.</p><p>Scattering database queries across multiple controllers is another one, prisma.user.findMany() showing up in one controller file and again somewhere else entirely. That spreads database logic all over the codebase instead of keeping it contained inside a proper repository layer.</p><p>Treating the ORM like it’s pure magic is a subtler trap. prisma.user.findMany() looks effortless on the surface, but underneath it&#39;s still just running SELECT * FROM users;. If the underlying SQL never actually makes sense to you, diagnosing real performance issues later becomes genuinely hard.</p><p>Ignoring proper error handling is another common gap, and in production, things will go wrong eventually, a database going down, bad input, network hiccups, unauthorized access attempts, all of it needs a proper path through central error handling middleware rather than getting quietly swallowed.</p><p>And hardcoding secrets directly into code, things like const password = &quot;123456&quot;, is a habit worth killing early. Environment variables exist specifically so things like DATABASE_URL, JWT_SECRET, and API_KEY never end up sitting in plain code.</p><p>Applications also change shape over time, a users table might start with just id, name, and email, then later pick up a phone number and a created_at timestamp. Migrations exist to track exactly these kinds of structural changes over time, tools like Prisma Migrate, Drizzle Kit, Flyway, or Liquibase are all essentially version control for your database’s shape.</p><p>Good backends also tend to test layer by layer, controller tests checking whether the response looks right, service tests checking whether the business rules actually hold, repository tests checking whether the database queries themselves behave correctly. And logging matters a lot more once something’s actually live, tools like Pino or Winston help capture things like request paths, status codes, and response times so debugging in production isn’t a total guessing game. On top of that, keeping an eye on API response times, database performance, error rates, and general server health is just part of running something in production responsibly.</p><h3>What a solid backend developer actually needs to understand</h3><p>Realistically, it comes down to a handful of layers stacking on top of each other. HTTP basics, requests, responses, headers, status codes. Express itself, routes, middleware, controllers. The database, SQL, relationships, indexes, transactions. The ORM sitting on top of that, Prisma, Drizzle, migrations. The overall architecture tying it together, services, repositories, proper error handling. And finally, production concerns, deployment, logging, security.</p><p>A reasonable learning order tends to look like this: get comfortable with JavaScript or TypeScript fundamentals like async/await, promises, modules, and types. Then pick up HTTP basics, REST conventions, methods, status codes, headers. From there, build actual things with Express, simple APIs, middleware, basic auth. Then move into PostgreSQL properly, tables, relationships, joins, indexes. After that, bring in an ORM, Prisma first, then Drizzle. And finally, round it out with production concerns, Docker, deployment, logging, security.</p><p>Honestly, the easiest way to hold all of this in your head is to think of a backend like a restaurant. The frontend user is the customer. The API is the waiter. The business logic is the chef. The database is the kitchen. And the application’s rules are basically the recipe everyone’s following. A customer never walks straight into the kitchen themselves, there’s a whole system standing between them and the food, and a backend works exactly the same way, frontend to API to business logic to database.</p><p>At the end of the day, the real skill in backend development was never memorizing one specific framework. Express, Prisma, Drizzle, PostgreSQL, these are all just tools. What actually matters is understanding how a request travels, how data gets stored, where business rules actually belong, how database queries get executed under the hood, and how to keep an architecture maintainable as it grows. Once those ideas are genuinely clear, picking up whatever new backend tool shows up next stops being intimidating, because at that point you’re not just learning a tool, you’re recognizing a system you already understand.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67a55a26787b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prisma vs Drizzle vs Raw SQL: What Every Backend Developer Should Understand Before Choosing an ORM]]></title>
            <link>https://surajsrggupta.medium.com/prisma-vs-drizzle-vs-raw-sql-what-every-backend-developer-should-understand-before-choosing-an-orm-a9690013470a?source=rss-761b5c125020------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9690013470a</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[orm]]></category>
            <category><![CDATA[prisma]]></category>
            <category><![CDATA[drizzle]]></category>
            <dc:creator><![CDATA[Mr. S. Gupta]]></dc:creator>
            <pubDate>Fri, 28 Aug 2026 11:00:08 GMT</pubDate>
            <atom:updated>2026-08-28T11:00:08.237Z</atom:updated>
            <content:encoded><![CDATA[<p>When most developers start building backend applications, they’re usually focused on one thing, getting an API working. Express routes, controllers, some auth, a bit of middleware, that’s usually the whole mental model in the beginning.</p><p>But sooner or later, a bigger question shows up. How exactly should your application be talking to the database?</p><p>And that’s when a bunch of unfamiliar words start floating around. Raw SQL, database drivers, ORMs, Prisma, Drizzle, query builders. Some people will tell you to never touch an ORM and just write SQL yourself. Others will swear Prisma made their life ten times easier. And then there’s a smaller crowd that prefers Drizzle specifically because it stays close to SQL instead of hiding it.</p><p>So what’s actually going on here? Why do all these tools even exist, and how do you know which one to reach for? Let’s build this up from the ground.</p><h3>First, understand how data actually moves</h3><p>Before Prisma or Drizzle mean anything to you, it helps to see the full picture of how a request travels through a backend app.</p><p>Say a user opens your site and clicks something like “show my profile.” That click travels roughly like this.</p><pre>Browser</pre><pre>   |<br>   v</pre><pre>Express API</pre><pre>   |<br>   v</pre><pre>Database Layer</pre><pre>   |<br>   v</pre><pre>PostgreSQL Database</pre><pre>   |<br>   v</pre><pre>Response back to the user</pre><p>That “database layer” bit in the middle is where all the confusion tends to live. Your app needs some way to actually talk to PostgreSQL, and there are basically three common ways to do that: writing raw SQL yourself, using an ORM like Prisma, or using a query builder like Drizzle.</p><h3>Writing raw SQL directly</h3><p>This is the oldest, most direct route there is, you just write the SQL yourself.</p><p>Say you’ve got a users table.</p><pre>users</pre><pre>id<br>name<br>email<br>password</pre><p>Finding a user is as simple as this.</p><pre>SELECT *<br>FROM users<br>WHERE id = 1;</pre><p>The database speaks SQL natively, so there’s no translation happening anywhere.</p><p>In Node.js, if you’re on PostgreSQL, the pg package is the usual way to send queries like that directly.</p><pre>import { Pool } from &quot;pg&quot;;</pre><pre>const pool = new Pool({<br>  connectionString: process.env.DATABASE_URL<br>});</pre><pre>const result = await pool.query(<br>  &quot;SELECT * FROM users WHERE id = $1&quot;,<br>  [1]<br>);</pre><pre>console.log(result.rows);</pre><p>Your code sends SQL, PostgreSQL runs it, and the data comes straight back. Nothing hidden, nothing abstracted away.</p><p>Writing SQL yourself gives you complete control, obviously. You can write things like this without fighting any abstraction.</p><pre>SELECT<br>users.name,<br>COUNT(orders.id)<br>FROM users<br>JOIN orders<br>ON users.id = orders.user_id<br>GROUP BY users.name;</pre><p>For gnarly reports like that, SQL is genuinely hard to beat. Writing it yourself also forces you to actually understand joins, indexes, execution plans, and performance in general, which is knowledge that pays off no matter what tool you end up using later. And there’s no extra layer sitting between your code and the database either.</p><p>But raw SQL has real downsides once a project grows past a handful of queries. Imagine a codebase with hundreds of them scattered around.</p><pre>const result = await pool.query(<br>`<br>SELECT *<br>FROM users<br>WHERE email=$1<br>`,<br>[email]<br>);</pre><p>Now imagine someone renames a column somewhere down the line, say email becomes email_address. Every query touching that column is now quietly broken, and the database knows about the change immediately. Your TypeScript code has no idea until something crashes at runtime.</p><p>There’s a sneakier version of this problem too.</p><pre>const user = result.rows[0];</pre><pre>console.log(user.emial);</pre><p>Spot the typo, emial instead of email. JavaScript won&#39;t say a word about it. You only find out once that line actually executes and blows up. This exact pain point is basically why ORMs exist in the first place.</p><h3>So what is an ORM, really</h3><p>ORM stands for Object Relational Mapping, which sounds fancier than it actually is. All it really means is that there’s a bridge sitting between your programming language and your database.</p><p>Instead of writing this.</p><pre>SELECT *<br>FROM users<br>WHERE id=1;</pre><p>You end up writing something closer to this.</p><pre>user.findUnique({<br> id: 1<br>})</pre><p>The ORM takes what you wrote and turns it into actual SQL behind the scenes.</p><pre>Your TypeScript code</pre><pre>        |<br>        v</pre><pre>ORM</pre><pre>        |<br>        v</pre><pre>SQL query</pre><pre>        |<br>        v</pre><pre>Database</pre><p>Developers reach for ORMs because modern apps need more than just sending queries around. They need type safety, proper migrations, schema management that doesn’t require memorizing every table by hand, and honestly, just less repetitive boilerplate. That’s the gap ORMs are trying to close.</p><p>In the TypeScript world today, the names that come up most are Prisma, Drizzle, TypeORM, and Sequelize. This piece focuses mainly on raw SQL, Prisma, and Drizzle, since those three are what most modern TypeScript backend projects are actually choosing between right now.</p><h3>Getting into Prisma</h3><p>Prisma is easily one of the most talked about ORMs in the TypeScript world, and it’s usually one of the first names that comes up in any conversation about modern Node.js backends. So what problem is it actually solving?</p><p>At its core, Prisma lets your TypeScript app talk to a database using regular TypeScript code instead of SQL scattered everywhere. It supports PostgreSQL, MySQL, SQLite, SQL Server, and MongoDB.</p><pre>TypeScript code</pre><pre>        |<br>        v</pre><pre>Prisma Client</pre><pre>        |<br>        v</pre><pre>SQL queries</pre><pre>        |<br>        v</pre><pre>Database</pre><p>You write TypeScript, Prisma turns it into the actual queries.</p><p>A typical Express plus Prisma plus PostgreSQL setup ends up looking roughly like this.</p><pre>Client</pre><pre>  |<br>  v</pre><pre>Express API</pre><pre>  |<br>  v</pre><pre>Service Layer</pre><pre>  |<br>  v</pre><pre>Prisma Client</pre><pre>  |<br>  v</pre><pre>PostgreSQL Database</pre><p>Prisma Client is really the piece doing all the work here, it’s the actual bridge between your backend code and the database sitting behind it.</p><p>Everything starts with a file called schema.prisma, which defines your entire database structure in one place.</p><pre>model User {<br>  id       Int    @id @default(autoincrement())<br>  name     String<br>  email    String @unique<br>  password String<br>}</pre><p>That’s basically saying, create a User table with these four columns, and Prisma understands exactly what that means.</p><p>Where raw SQL would need something like this to create the table.</p><pre>CREATE TABLE users (<br> id SERIAL PRIMARY KEY,<br> name TEXT,<br> email TEXT UNIQUE,<br> password TEXT<br>);</pre><p>Prisma just needs the schema block shown above, and it handles turning that into actual database changes through something called a migration.</p><p>A migration is really just a recorded history of database changes over time. Say your User table starts out simple.</p><pre>User</pre><pre>id<br>name<br>email</pre><p>Months later you decide to add a phone number field. Instead of manually altering the table yourself, you run something like this.</p><pre>npx prisma migrate dev --name add_phone_number</pre><p>Prisma generates a migration file to track that change, something like a folder with 001_initial_setup followed by 002_add_phone_number, so your entire database history stays saved and versioned instead of living only in someone&#39;s memory.</p><p>Once your schema’s defined, Prisma generates a client you actually use in your code.</p><pre>const user = await prisma.user.findUnique({<br>  where:{<br>    id:1<br>  }<br>});</pre><p>Behind the scenes, that quietly becomes this.</p><pre>SELECT *<br>FROM users<br>WHERE id=1;</pre><p>You never had to type that SQL yourself.</p><p>The common operations map over pretty intuitively too. Creating a record that would normally be an INSERT INTO users (name, email) VALUES (...) becomes prisma.user.create({ data: { name, email } }). Fetching all users, which would be a plain SELECT * FROM users, becomes prisma.user.findMany(). Updating a record swaps UPDATE users SET name=&#39;Aman&#39; WHERE id=1 for prisma.user.update({ where: { id: 1 }, data: { name: &quot;Aman&quot; } }). And deleting swaps DELETE FROM users WHERE id=1 for prisma.user.delete({ where: { id: 1 } }).</p><p>Where Prisma really earns its popularity is type safety. If your schema defines a User with id, name, and email, then writing something like this actually gives you working autocomplete on every field.</p><pre>const user = await prisma.user.findMany();</pre><pre>user[0].email;</pre><p>And if you accidentally typo it as user[0].emali, Prisma paired with TypeScript will flag that before your app even runs, which saves a genuinely surprising amount of debugging time down the line.</p><p>Real applications almost never have just one table either. Say a user has many posts.</p><pre>User</pre><pre>id<br>name</pre><pre>Post</pre><pre>id<br>title<br>userId</pre><p>Prisma represents that relationship directly in the schema.</p><pre>model User {<br> id Int @id @default(autoincrement())</pre><pre> name String</pre><pre> posts Post[]<br>}</pre><pre>model Post {</pre><pre> id Int @id @default(autoincrement())</pre><pre> title String</pre><pre> userId Int</pre><pre> user User @relation(<br> fields:[userId],<br> references:[id]<br> )</pre><pre>}</pre><p>And fetching a user along with their posts becomes a single readable call.</p><pre>const user = await prisma.user.findUnique({<br> where:{<br>  id:1<br> },<br> include:{<br>  posts:true<br> }<br>});</pre><p>Which gives you back something like a user object with a nested posts array, exactly the shape you’d want to work with in your app.</p><p>Prisma’s biggest strengths really come down to how natural the developer experience feels, how strong the type safety is especially in TypeScript projects, how organized migrations become, how solid the documentation is, and how easily a whole team can look at the schema and immediately understand the database structure.</p><p>It’s not without trade-offs though. Genuinely complex reporting queries can start feeling awkward compared to just writing raw SQL. Because Prisma hides SQL so effectively, developers who only ever learn Prisma can end up struggling later when they actually need to optimize something at the database level. And there’s technically an extra layer sitting in the request flow, application to Prisma to SQL to database, instead of the more direct application to SQL to database path. For most apps that extra layer is a complete non issue, but it’s worth knowing it’s there.</p><p>Prisma tends to make the most sense when you’re building APIs in TypeScript, want fast development, mostly need standard CRUD operations, and care a lot about developer experience. A lot of startups and SaaS products lean on it for exactly these reasons.</p><h3>Where Drizzle fits into the picture</h3><p>Drizzle is the other ORM that’s picked up serious momentum in the TypeScript world, but understanding it really comes down to understanding one thing first, Prisma and Drizzle are built on genuinely different philosophies.</p><p>Prisma’s whole approach is keeping developers away from database complexity as much as possible. Drizzle takes the opposite stance, keep developers close to SQL, just give them TypeScript’s safety on top of it. Both are chasing the same end goal, a better development experience around your database, they just take very different roads to get there.</p><p>Drizzle is a lightweight TypeScript ORM that works with PostgreSQL, MySQL, and SQLite, and its whole focus is type safety, performance, staying close to SQL, and keeping the architecture lightweight.</p><pre>TypeScript code</pre><pre>        |<br>        v</pre><pre>Drizzle ORM</pre><pre>        |<br>        v</pre><pre>SQL query</pre><pre>        |<br>        v</pre><pre>Database</pre><p>The philosophy difference is easiest to see side by side. Fetching all users in Prisma looks like this, and you never really need to think about what SQL it’s generating underneath.</p><pre>const user = await prisma.user.findMany();</pre><p>Drizzle asks you to write something noticeably closer to actual SQL.</p><pre>const users = await db<br>.select()<br>.from(usersTable);</pre><p>You can basically read what’s happening at the database level just by looking at the code.</p><p>Schemas work differently too. Where Prisma defines things in its own schema.prisma file, Drizzle defines the schema directly in TypeScript.</p><pre>import {<br> pgTable,<br> serial,<br> varchar<br>} from &quot;drizzle-orm/pg-core&quot;;</pre><pre>export const users = pgTable(&quot;users&quot;, {</pre><pre> id: serial(&quot;id&quot;).primaryKey(),</pre><pre> name: varchar(&quot;name&quot;),</pre><pre> email: varchar(&quot;email&quot;)</pre><pre>});</pre><p>So your database structure literally lives inside your TypeScript codebase, no separate schema language to learn.</p><p>The common operations feel like a TypeScript flavored version of SQL itself. Inserting a row that would be INSERT INTO users (name, email) VALUES (...) in SQL becomes db.insert(users).values({ name, email }) in Drizzle. Fetching everything, which is SELECT * FROM users, becomes db.select().from(users). And filtering, which would be SELECT * FROM users WHERE id=1, becomes db.select().from(users).where(eq(users.id, 1)).</p><p>People gravitate toward Drizzle for a handful of reasons. It’s genuinely lightweight with very little unnecessary abstraction sitting in the way. Because it stays close to SQL, your actual SQL knowledge stays sharp and keeps growing rather than getting hidden behind an abstraction. The queries it generates tend to be predictable since there’s less machinery translating your intent. And it was built with modern runtimes in mind too, things like edge environments and serverless setups.</p><p>That said, if you’ve never really learned SQL, Drizzle can feel a lot more confusing upfront than Prisma does, since Prisma is generally the easier on-ramp for total beginners. Using Drizzle well also genuinely requires understanding joins, relations, indexes, and how queries actually work, there’s no hiding from that. And its ecosystem, documentation, and community, while solid, are still smaller than Prisma’s more mature setup.</p><p>The simplest way to frame the difference is this. With Prisma you treat the database like a bunch of objects, prisma.user.findMany(), and the whole focus is developer experience. With Drizzle you treat the database more like SQL itself, db.select().from(users), and the focus shifts toward performance and control.</p><h3>Looking at all three side by side</h3><p>At this point we’ve covered three real approaches, raw SQL, Prisma, and Drizzle, and architecturally they stack up like this.</p><pre>Raw SQL:      Application → SQL Query → Database<br>Prisma:       Application → Prisma Client → SQL → Database<br>Drizzle:      Application → Drizzle → SQL → Database</pre><p>Take one simple operation, finding a user by email, given a basic users table with id, name, and email. Here&#39;s how each approach handles the exact same task.</p><p>Raw SQL:</p><pre>const result = await pool.query(<br>`<br>SELECT *<br>FROM users<br>WHERE email=$1<br>`,<br>[&quot;rahul@test.com&quot;]<br>);</pre><p>Prisma:</p><pre>const user =<br>await prisma.user.findUnique({</pre><pre>where:{<br> &lt;email:&quot;rahul@test.com&gt;&quot;<br>}</pre><pre>});</pre><p>Drizzle:</p><pre>const user =<br>await db<br>.select()<br>.from(users)<br>.where(<br> eq(<br> users.email,<br> &quot;rahul@test.com&quot;<br> )<br>);</pre><p>All three get you the exact same data back at the end of the day. What actually differs is how much control you want, how much abstraction you’re comfortable with, and how much SQL you already know going in.</p><p>A mistake a lot of beginners make here is fixating on “which one’s the fastest,” when in real projects that’s rarely the question that actually matters. The better questions are usually things like what the team’s already comfortable with, how complex the project genuinely is, how strong everyone’s database knowledge actually is, and how complicated the queries are likely to get. A simple SaaS app can usually get by just fine on Prisma alone. A database heavy application is where Drizzle, or even raw SQL in places, starts earning its keep.</p><p>Feature Raw SQL Prisma Drizzle Learning curve Harder Easier Medium SQL Control Highest Lowest High Type Safety Low Excellent Excellent Performance Excellent Good Excellent Developer Experience Medium Excellent Good Complex Queries Excellent Medium Excellent Beginner Friendly Low High Medium</p><h3>So what should you actually choose</h3><p>Should you always default to using an ORM? No, honestly. An ORM is a tool like any other, and no single tool is the right call for every project out there. Some apps genuinely move faster with one, others are better off without.</p><p>Raw SQL earns its place when you need maximum control over the database, when the app is genuinely database heavy, when queries get complex, or when performance really can’t take a hit. Think analytics platforms, reporting systems, financial applications, or anything doing heavy data processing. Say you need a report answering something like “how much has each customer purchased over the last five years, and what’s their average order value.” That kind of query is just naturally easier to express directly in SQL.</p><pre>SELECT<br>customers.name,<br>COUNT(orders.id),<br>AVG(orders.amount)</pre><pre>FROM customers</pre><pre>JOIN orders</pre><pre>ON customers.id = orders.customer_id</pre><pre>GROUP BY customers.name;</pre><p>There’s really no substitute for SQL’s raw power in cases like that. The catch is that leaning entirely on raw SQL across a large codebase gets unwieldy fast, hundreds of scattered query files, and you’re left manually managing type safety yourself on top of it all.</p><p>Prisma tends to be the better call when you’re building a TypeScript backend, doing mostly standard CRUD work, care about development speed, and have multiple developers working across the same codebase. Think SaaS products, admin dashboards, e-commerce APIs, or content management systems, basically anywhere operations like creating a user, updating a profile, creating an order, or pulling dashboard data are the daily bread and butter. Prisma genuinely boosts productivity here, turning something like a raw SELECT * FROM users WHERE id=1 into a clean, readable prisma.user.findUnique({ where: { id: 1 } }) that any teammate can understand at a glance.</p><p>Drizzle earns its spot when you’re working in TypeScript, already know SQL reasonably well, care a lot about performance and control, and want something lightweight rather than heavy handed. It tends to appeal to developers who want the safety net of an ORM without feeling like they’ve been pulled too far away from the actual database.</p><p>In practice, plenty of real projects don’t stick to just one approach. A startup might reasonably begin like this.</p><pre>Express → Prisma → PostgreSQL</pre><p>Which is a genuinely practical starting point. As the app grows and analytics or complex reporting needs pile up, it’s common to start layering raw SQL into specific parts of the app rather than ripping out Prisma entirely.</p><pre>Application<br>├── Prisma<br>└── Raw SQL Queries<br>        ↓<br>   PostgreSQL</pre><p>Using one approach everywhere isn’t some rule you’re required to follow, and most real world codebases end up mixing them anyway. Startups often lean toward TypeScript plus Prisma plus PostgreSQL purely for development speed. Newer, more modern TypeScript projects increasingly reach for Drizzle instead, valuing that lightweight, SQL friendly approach. And larger scale systems often end up combining an ORM with raw SQL and dedicated database optimization work, simply because different parts of a large system run into genuinely different problems.</p><h3>Mistakes worth avoiding</h3><p>A few things trip people up consistently here. The first is treating the ORM itself as the database. Prisma isn’t a database, Drizzle isn’t a database, they’re just tools for accessing one, whether that’s PostgreSQL, MySQL, or MongoDB sitting underneath.</p><p>The second is skipping SQL entirely and jumping straight to Prisma. It feels productive early on, but it tends to backfire later when slow queries stop making sense, joins feel needlessly confusing, and database optimization becomes genuinely hard because there’s no real foundation underneath the abstraction. An ORM was never meant to replace SQL, it’s a layer sitting on top of it.</p><p>The third is chasing raw performance numbers above everything else. Developer productivity matters just as much in the real world. Shaving five milliseconds off a query while making development three months slower isn’t automatically the smarter trade to make.</p><h3>A learning path worth following</h3><p>If starting from zero today, this is roughly the order worth going in. Start with SQL fundamentals, tables, primary keys, foreign keys, joins, indexes, transactions, all using something like PostgreSQL. Then spend some real time connecting directly with something like Node’s pg package, so you actually understand how an application talks to a database without anything hidden in between. From there, move into Prisma, get comfortable with schemas, migrations, relations, and the type safety it brings. And finally, give Drizzle a proper try, so you understand what an SQL-first approach with a query builder actually feels like, along with the performance trade-offs that come with it.</p><h3>Where that leaves you</h3><p>The point of an ORM was never to replace SQL. It’s there to make the developer experience better, nothing more grand than that.</p><p>A genuinely strong backend developer isn’t someone who just happens to know Prisma or Drizzle well. It’s someone who understands how a database actually works, how to write SQL when it’s needed, what an ORM is actually simplifying for them, and just as importantly, when reaching for an ORM makes sense and when writing raw SQL directly is the smarter call.</p><p>Once that clarity sets in, choosing between these tools stops feeling like a guessing game. You start making the call based on what the project actually needs, not on whatever’s trending that particular month.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9690013470a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is Supabase Actually a Database?]]></title>
            <link>https://surajsrggupta.medium.com/is-supabase-actually-a-database-2d504b2e42c6?source=rss-761b5c125020------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d504b2e42c6</guid>
            <category><![CDATA[neon]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[supabase]]></category>
            <category><![CDATA[appwrite]]></category>
            <dc:creator><![CDATA[Mr. S. Gupta]]></dc:creator>
            <pubDate>Thu, 20 Aug 2026 14:41:04 GMT</pubDate>
            <atom:updated>2026-08-20T14:41:04.398Z</atom:updated>
            <content:encoded><![CDATA[<h3>Is Supabase Actually a Database? Sorting Out Supabase, Firebase, Appwrite, PocketBase, and Neon</h3><p>For a good chunk of my early days learning backend stuff, I genuinely believed Supabase, Firebase, and Appwrite were databases. Just straight up databases, no different from PostgreSQL or MongoDB in my head.</p><p>And honestly, the way tutorials talk about them didn’t help at all. One video would tell you to just use Supabase and move on. The next would swear by Firebase instead. Then someone else would come along and say skip all of that, just learn PostgreSQL properly.</p><p>At some point I genuinely lost track of what I was even picking between. Was I choosing a database? A backend? Some kind of hosting service? Honestly I couldn’t tell you at the time.</p><p>If that confusion sounds familiar, this should clear most of it up.</p><h3>The one thing you need to get straight first</h3><p>A database and a backend platform are not the same thing, and mixing them up is where basically all the confusion starts.</p><p>Think about building a house for a second. You need bricks, sure, but you also need wiring, plumbing, security systems, furniture, all of it. The bricks are just one piece of a much bigger picture.</p><p>A database works the same way inside your backend. It’s just one piece of the whole thing. Modern platforms tend to bundle a bunch of backend services together under one roof, and that’s exactly why people end up mistaking the whole platform for just the database part.</p><h3>So what does a database actually do</h3><p>A database really only has one job, and it’s not glamorous. It stores your data. That’s the entire job description.</p><p>Take PostgreSQL for example. It stores things in tables.</p><p><strong>Users</strong></p><p>id name email 1 Rahul <a href="/service/mailto:rahul@example.com">rahul@example.com</a> 2 Aman <a href="/service/mailto:aman@example.com">aman@example.com</a></p><p>It genuinely doesn’t care what you’re building on top of it, whether that’s an online store, a social app, or some banking system. Its only concern is storing and pulling back data when asked.</p><h3>Okay, so what is Supabase then</h3><p>Here’s the thing people keep getting wrong. Supabase is not a database.</p><p>Supabase is a backend platform, and one of the things it happens to include is a PostgreSQL database.</p><p>Picture it more like this.</p><pre>Supabase</pre><pre>├── PostgreSQL Database<br>├── Authentication<br>├── File Storage<br>├── Realtime Engine<br>├── Edge Functions<br>├── Dashboard<br>└── APIs</pre><p>See how the database is just one item in that list, not the whole thing. Supabase basically hands you a bunch of backend pieces that are already wired together, so instead of setting up each one separately, you get a working backend pretty much out of the box.</p><h3>What if you skip Supabase entirely</h3><p>Nothing’s actually stopping you from building this exact same setup yourself, piece by piece.</p><pre>Express</pre><pre>├── PostgreSQL<br>├── JWT Authentication<br>├── AWS S3 Storage<br>├── Socket.IO<br>├── REST API<br>└── Docker Deployment</pre><p>You get total control doing it this way, no argument there. But you’re also signing up for a lot more setup work, and honestly a lot more things that can go wrong along the way.</p><h3>And Firebase</h3><p>Firebase is also a backend platform, but it’s built around a different core. Instead of PostgreSQL, its main database is Firestore, which is a document database, meaning your data lives as documents rather than rows in a table.</p><p>Firebase brings along its own bundle of services too.</p><pre>Firebase</pre><pre>├── Firestore<br>├── Authentication<br>├── Cloud Functions<br>├── Cloud Storage<br>├── Analytics<br>├── Hosting<br>└── Push Notifications</pre><p>If you’ve ever built an Android app, you’ve probably had Firebase suggested to you constantly, and that’s mostly because Google has baked it so deeply into its mobile ecosystem.</p><h3>So is Firebase actually better than Supabase</h3><p>There’s no clean answer here, and honestly anyone who gives you one confidently is probably oversimplifying. They’re just solving different problems.</p><p>Supabase makes a lot of sense if you’re comfortable with PostgreSQL and SQL in general. Firebase makes more sense if your app genuinely benefits from Firestore’s structure or from being deep in Google’s ecosystem. Which one wins really comes down to what you’re building, not which platform is objectively superior.</p><h3>Where does Appwrite fit in</h3><p>Appwrite is chasing a pretty similar goal to Supabase. It gives you authentication, a database, file storage, functions, messaging, the usual suite.</p><p>What sets it apart is that it’s really built with self hosting in mind from the start. If the idea of running your own backend infrastructure instead of leaning on someone else’s managed cloud appeals to you, Appwrite is worth a proper look.</p><h3>And PocketBase</h3><p>PocketBase is a much smaller, lighter animal compared to Supabase or Firebase. Under the hood it’s running on SQLite, which is itself a relational SQL database, and it pairs that with the handy stuff like auth and file storage.</p><p>Its whole setup is refreshingly simple.</p><pre>PocketBase</pre><pre>├── SQLite<br>├── Authentication<br>├── File Storage<br>└── Dashboard</pre><p>Because it’s so lightweight, PocketBase has become a favorite for quick prototypes, demos, and smaller side projects. It’s just not usually what people reach for when they’re building something that needs to scale up seriously.</p><h3>Then what exactly is Neon</h3><p>Compared to everything above, Neon is honestly refreshingly simple to explain. Neon is basically managed PostgreSQL. That’s genuinely it, nothing more hidden underneath.</p><p>So if someone tells you they’re using Neon, all that really means is their PostgreSQL database is being hosted and managed by Neon. There’s no built in auth system, no storage service, no bundled backend platform sitting alongside it. Just the database.</p><pre>Application</pre><pre>↓</pre><pre>Neon</pre><pre>↓</pre><pre>PostgreSQL</pre><p>That’s exactly why a lot of developers pair Neon with something else on top, like Prisma, Drizzle, Clerk, Better Auth, or their own setup on AWS.</p><h3>Laying them all out side by side</h3><p>Platform Database Type Extra Backend Services Supabase PostgreSQL SQL Yes Firebase Firestore NoSQL Yes Appwrite SQL based database support SQL Yes PocketBase SQLite SQL Yes Neon PostgreSQL SQL No</p><p>Look closely and the pattern is obvious. Neon is the only one that’s really just about hosting the database itself. Everyone else on that list gives you a whole backend ecosystem wrapped around one.</p><h3>So which one should a beginner actually go with</h3><p>Don’t pick based on whatever’s trending on YouTube this month, that’s honestly how a lot of people end up confused in the first place. Pick based on what you’re actually trying to learn.</p><p>If you want to genuinely understand relational databases, plain PostgreSQL is a solid starting point. If you want authentication, storage, and a dashboard without burning days configuring everything yourself, Supabase is a great pick. If you’re building mobile apps and want tight integration with Google’s ecosystem, Firebase is the logical choice. If you’re just messing around with side projects or prototypes, PocketBase is genuinely convenient. And if owning your own infrastructure matters to you, Appwrite is worth exploring properly.</p><h3>The mistake almost everyone makes early on</h3><p>A lot of people end up comparing PostgreSQL directly with Supabase, and honestly that comparison just doesn’t hold up. It’s a bit like comparing an engine to an entire car.</p><p>The comparisons that actually make sense look more like this. PostgreSQL against Firestore. Or Supabase against Firebase. One of those is a database versus database comparison, the other is a platform versus platform comparison. Once that distinction clicks, a huge chunk of the confusion just disappears on its own.</p><h3>Wrapping up</h3><p>Whenever some new backend tool crosses your radar, there’s really just one question worth asking before anything else. Is this actually a database, or is it a platform built around one?</p><p>That single question quietly untangles most backend architecture confusion. Once you know exactly what each piece of the puzzle is actually responsible for, choosing between tools stops feeling like a random guessing game and starts feeling a lot more deliberate.</p><p>Next time, I want to go one level up from the database itself and tackle another question beginners run into constantly, what exactly is an ORM, and why do people reach for tools like Prisma or Drizzle instead of just writing raw SQL themselves?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d504b2e42c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL vs NoSQL, Explained the Way I Wish Someone Had Explained It to Me]]></title>
            <link>https://surajsrggupta.medium.com/sql-vs-nosql-explained-the-way-i-wish-someone-had-explained-it-to-me-68b5513c8ca0?source=rss-761b5c125020------2</link>
            <guid isPermaLink="false">https://medium.com/p/68b5513c8ca0</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[supabase]]></category>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Mr. S. Gupta]]></dc:creator>
            <pubDate>Sun, 16 Aug 2026 09:29:53 GMT</pubDate>
            <atom:updated>2026-08-16T09:29:53.551Z</atom:updated>
            <content:encoded><![CDATA[<p>When I was starting out with backend development, there was one question that kept messing with my head more than anything else.</p><p>Should I be learning SQL or NoSQL?</p><p>And every single tutorial seemed to have its own opinion on this. One guy swore PostgreSQL was the only sane option. Another one was pushing MongoDB purely because, in his words, “JSON is just easier.” Then someone else came along and said forget databases entirely, use Firebase, you don’t even need a real backend.</p><p>And just when I thought I had a decent grip on things, names like Supabase, Prisma, and Drizzle started showing up everywhere, and I genuinely couldn’t tell anymore which of these were actual databases and which were just tools sitting on top of one.</p><p>If any of that sounds familiar, this is basically the article I wish existed back then.</p><p>By the time you’re done reading this, you should have a clear picture of what a database actually is, what SQL and NoSQL even mean, why PostgreSQL, MySQL, Oracle, MongoDB, and Firestore aren’t all the same thing despite sounding similar, and how to actually pick between SQL and NoSQL instead of just guessing.</p><p>Let’s start from zero.</p><h3>What a database actually is</h3><p>Say you’re building an online store. Your app needs somewhere to keep track of users, products, orders, payments, reviews, all of it.</p><p>Now, if you just shove all of that into regular JavaScript variables, the moment your server restarts, everything’s gone. Poof.</p><p>A database exists to solve exactly that problem. It’s just a system that holds onto your data permanently, so your app can read it back or update it whenever it needs to, restart or no restart.</p><p>Honestly, the simplest way to think about it is as a warehouse where your application’s data actually lives.</p><h3>Everything mostly falls into two buckets</h3><p>Almost every app you’ll build ends up leaning on one of two approaches, SQL or NoSQL.</p><p>And it’s worth being clear here, these are categories, not products. Kind of like how Android and iOS are categories of operating systems, not the actual phone you’re holding. SQL and NoSQL work the same way.</p><h3>What a SQL database actually looks like</h3><p>A SQL database keeps everything in tables. If you’ve ever messed around in Excel, this is going to feel oddly familiar.</p><p><strong>Users</strong></p><p>ID Name Age 1 Rahul 21 2 Aman 24 3 Priya 20</p><p>Each row is one record, each column is one property, and the structure never really changes. If your table has id, name, and age as columns, then every single row follows that same shape, no exceptions.</p><p>That rigid consistency, honestly, is one of SQL’s biggest selling points, even though it sounds boring on paper.</p><h3>Where SQL really shines, relationships</h3><p>Say your app also needs an Orders table.</p><p><strong>Orders</strong></p><p>Order ID User ID Product 101 1 Laptop 102 2 Keyboard</p><p>Here’s the interesting part. Instead of writing the user’s actual name into the Orders table over and over, it just stores the User ID. That ID is what links the two tables together.</p><p>That link is what people mean when they say relationship. SQL databases are built specifically to handle these kinds of connections well, which is exactly why banks, hospitals, schools, ERP systems, basically anything with serious business logic, tend to run on relational databases.</p><p>Some of the more common SQL databases you’ll run into are PostgreSQL, MySQL, Oracle Database, Microsoft SQL Server, and SQLite. They’re all built differently under the hood and each has its own quirks, but they all follow that same table based, relational way of organizing data.</p><h3>So what’s NoSQL then</h3><p>The name trips a lot of people up. NoSQL doesn’t actually mean “no SQL.” It originally stood for “not only SQL,” which honestly makes a lot more sense once you think about it.</p><p>Instead of forcing everything into tables, NoSQL databases give you other ways to organize your data. The one you’ll bump into most often is the document database, and that’s the category MongoDB and Firestore both fall under.</p><h3>Documents instead of rows and columns</h3><p>Rather than rows and columns, a document database stores, well, documents, and these usually look a lot like JSON.</p><pre>{<br>  &quot;name&quot;: &quot;Rahul&quot;,<br>  &quot;age&quot;: 21,<br>  &quot;skills&quot;: [&quot;Node.js&quot;, &quot;React&quot;],<br>  &quot;address&quot;: {<br>    &quot;city&quot;: &quot;Patna&quot;,<br>    &quot;country&quot;: &quot;India&quot;<br>  }<br>}</pre><p>The thing is, every document is allowed to look different. One user might have an address field, another might not bother with one at all. One user might list ten skills, another just one. Nothing forces every document into the exact same shape.</p><p>That flexibility right there is basically the main reason a lot of developers reach for document databases in the first place.</p><h3>MongoDB</h3><p>MongoDB is probably the name most people think of first when document databases come up. Its structure goes database, then collections, then documents inside those collections.</p><pre>users</pre><pre>{<br>  &quot;name&quot;: &quot;Rahul&quot;,<br>  &quot;age&quot;: 21<br>}</pre><pre>{<br>  &quot;name&quot;: &quot;Aman&quot;,<br>  &quot;age&quot;: 24,<br>  &quot;city&quot;: &quot;Delhi&quot;<br>}</pre><p>Notice the second document has an extra city field that the first one doesn’t. MongoDB is completely fine with that kind of mismatch, no complaints.</p><h3>Firestore</h3><p>Firestore, which lives under the Firebase umbrella, is also a document database. At a glance it looks a lot like MongoDB since both deal in JSON-ish documents, but there are real differences once you dig in.</p><p>Its structure goes database, then collections, then documents, and then something MongoDB doesn’t really have, subcollections.</p><pre>users<br>   |<br>Rahul<br>   |<br>orders<br>   |<br>order1<br>order2</pre><p>So a single user document can literally have another collection nested inside it. Firestore also comes with real time sync built right in, which is a big part of why it’s such a common pick for chat apps and mobile apps that need things updating live.</p><h3>Wait, so are Firestore and MongoDB basically the same thing</h3><p>Nope, and this trips people up a lot. They’re in the same category, sure, but they’re different products entirely.</p><p>Think of it like PostgreSQL and Oracle. Both are SQL databases, both use tables, but nobody’s out there claiming PostgreSQL and Oracle are interchangeable. It’s the exact same logic with MongoDB and Firestore. Both document databases, but different architecture, different APIs, different pricing, different capabilities under the hood.</p><h3>Putting SQL and NoSQL side by side</h3><p><strong>SQL</strong> stores data in tables. Think PostgreSQL, MySQL, Oracle, SQL Server. It tends to be the go-to for banking, e-commerce, inventory systems, ERP software, and anything financial. Its strengths are solid relationships, real transactions, a structure that stays consistent, and genuinely powerful querying. Where it struggles a bit is when your data’s shape keeps changing constantly.</p><p><strong>NoSQL</strong>, at least the document flavor, stores data as, well, documents. Think MongoDB and Firestore. It tends to work well for chat apps, social platforms, content management, mobile apps, and anything where the data shape shifts often. Its strengths are a flexible schema, easy handling of nested data, and generally faster initial development. Where it tends to struggle is once your relationships between data start getting genuinely complex.</p><h3>So which one should a beginner actually learn first</h3><p>If your end goal is backend development, learning SQL first is usually the smarter move, and here’s the actual reason why. SQL forces you to actually understand things every developer eventually needs anyway, tables, primary keys, foreign keys, relationships, joins, transactions, indexes, all of it.</p><p>Once those concepts click, picking up MongoDB or Firestore later becomes almost easy. Going the other way around tends to be rougher, because document databases quietly hide a lot of the relational thinking you’d otherwise be forced to learn.</p><h3>A misconception worth clearing up</h3><p>A lot of beginners assume SQL is some outdated technology and NoSQL is the shiny modern replacement. That’s just not accurate.</p><p>Companies like Stripe, GitHub, and Shopify, along with plenty of massive SaaS businesses, lean heavily on PostgreSQL even today. At the same time, plenty of successful products run just fine on MongoDB or Firestore. Neither one is objectively better across the board, they’re just built to solve different kinds of problems, and the right pick really just comes down to what your application actually needs.</p><h3>Wrapping it up</h3><p>If I had to boil the whole thing down to one sentence each, it’d be this. SQL databases organize your data into related tables. NoSQL document databases organize your data as flexible, self contained documents.</p><p>Once that one distinction actually sinks in, a surprising number of other confusing topics start making sense on their own. Things like Supabase, Prisma, Drizzle, Firebase, and ORMs in general become a lot easier to reason about, because now you actually understand what’s sitting underneath them.</p><p>Next up, I want to tackle another question that trips a lot of beginners up, is Supabase actually a database itself, or is it something else entirely wearing a database’s clothes?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68b5513c8ca0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Is shadcn/ui, and When Should You Actually Use It in React or Next.js]]></title>
            <link>https://surajsrggupta.medium.com/what-is-shadcn-ui-and-when-should-you-actually-use-it-in-react-or-next-js-54e21c0727cf?source=rss-761b5c125020------2</link>
            <guid isPermaLink="false">https://medium.com/p/54e21c0727cf</guid>
            <category><![CDATA[mern-stack]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[shadcn-ui]]></category>
            <category><![CDATA[shadcn]]></category>
            <dc:creator><![CDATA[Mr. S. Gupta]]></dc:creator>
            <pubDate>Fri, 17 Jul 2026 14:07:50 GMT</pubDate>
            <atom:updated>2026-07-17T14:07:50.066Z</atom:updated>
            <content:encoded><![CDATA[<p>Every time I start a new React or Next.js project, the same question shows up pretty early. How am I going to handle the UI this time?</p><p>Do I build every component myself from scratch? Do I just grab a component library and move on? And if I go with a library, which one, because the options never seem to end. Material UI, Ant Design, Chakra UI, Bootstrap, and now shadcn/ui seems to be everywhere.</p><p>I ran into this exact confusion when I started digging into more modern Next.js setups. Everyone kept talking about shadcn/ui, and I genuinely couldn’t tell if it was actually better than the usual libraries or if it was just having a moment.</p><p>So I spent some time actually working with it and reading through how it’s built, and this article is basically everything I picked up along the way. What shadcn/ui really is, why people are switching to it, how it’s different from a normal UI library, what else is out there, and how you can figure out if it’s the right pick for whatever you’re building.</p><h3>So what actually is shadcn/ui</h3><p>Here’s the first thing that threw me off. shadcn/ui isn’t really a component library in the traditional sense.</p><p>With something like Material UI, you install a package and pull components out of it.</p><pre>import Button from &quot;@mui/material/Button&quot;;</pre><p>That component’s code sits inside the package itself. You use it, you tweak it through whatever props and theme options are exposed, but the actual source never becomes part of your codebase.</p><p>shadcn/ui does the opposite. When you add a component, it literally copies the code into your project.</p><pre>src/<br> └── components/<br>      └── ui/<br>           └── button.tsx</pre><p>Once that file exists, it’s yours. Open it, rewrite the styling, change how it behaves, strip parts out, whatever you need. Nobody’s stopping you because there’s no package boundary in the way anymore.</p><h3>The philosophy behind it</h3><p>If I had to sum up shadcn/ui in one line, it’d be something like this: use solid, well built components, but never give up ownership of the code.</p><p>It leans on three things to make that work.</p><p><strong>Tailwind CSS</strong> handles the styling. Instead of maintaining separate stylesheets, you write utility classes directly on the elements.</p><pre>&lt;button className=&quot;bg-black text-white px-4 py-2&quot;&gt;<br>  Login<br>&lt;/button&gt;</pre><p><strong>Radix UI</strong> takes care of the harder, easy to mess up interaction logic, things like dialogs, dropdowns, checkboxes, and popovers. Radix handles the accessibility groundwork, keyboard behavior, focus trapping, all of that, so you can spend your energy on how it looks instead of reinventing that wheel.</p><p><strong>TypeScript</strong> ties it together nicely too. You get proper autocomplete, fewer silent bugs, and it’s noticeably easier to keep a larger codebase sane over time.</p><h3>Why did it blow up the way it did</h3><p>Given that there were already a dozen solid UI libraries floating around, it’s fair to ask why developers suddenly started gravitating toward shadcn/ui. A few reasons kept coming up as I looked into it.</p><p>The first is control. With a typical library, customization usually happens through props, theme configs, or override classes, and that works fine until it doesn’t. At some point you hit a wall where the design you want just isn’t achievable without hacking around the library’s internals. With shadcn/ui, that wall doesn’t exist because components/ui/button.tsx is just a regular file sitting in your repo.</p><p>The second is that you’re not really locked into anyone’s design system. The component code lives inside your app, so if your product’s design direction shifts down the line, you go in and change it directly instead of fighting a framework.</p><p>The third reason is just how well it lines up with where a lot of teams have already landed stack wise.</p><pre>Next.js<br>+<br>TypeScript<br>+<br>Tailwind CSS<br>+<br>shadcn/ui</pre><p>Since this combination had already become the default for a lot of new Next.js projects, shadcn/ui basically slotted right in.</p><h3>Is it the best UI library out there</h3><p>Not really, and that’s an important thing to get straight early on. There isn’t a single UI library that’s the right call for every project, no matter how much hype it’s getting. It depends entirely on what you’re trying to build.</p><h3>The alternatives worth knowing about</h3><p><strong>Material UI (MUI)</strong> is probably still the most widely used React component library out there. It shows up a lot in enterprise apps, admin dashboards, and internal tooling. The upside is a huge catalogue of ready components, strong documentation, and genuinely fast development. The downside is that unless you put in real effort, your app tends to end up looking like, well, Material Design.</p><p><strong>Ant Design</strong> leans more into business and enterprise territory, things like CRM tools, ERP systems, and dashboards that are drowning in data. Its tables, forms, and data components are noticeably more powerful than what you’d get elsewhere, which makes it a solid pick if you’re building something enterprise heavy.</p><p><strong>Chakra UI</strong> is the simpler, friendlier option of the bunch. Clean APIs, decent accessibility defaults out of the box, and components that don’t fight you. Good choice if you just want something readable and easy to reason about without a steep learning curve.</p><p><strong>Bootstrap</strong> is the old guard here, and it still gets the job done for simple sites, landing pages, and smaller projects. But for custom SaaS style products these days, most developers I’ve seen tend to reach for Tailwind based setups instead.</p><h3>shadcn/ui vs MUI vs Ant Design at a glance</h3><p>Feature shadcn/ui MUI Ant Design Customization Very High Medium Medium Ready Components Medium Very High Very High Developer Control Very High Medium Medium Next.js Support Excellent Good Good Enterprise Apps Good Excellent Excellent Unique Designs Excellent Medium Medium</p><h3>How to actually decide</h3><p>Before picking a UI approach, it helps to just ask yourself a few honest questions.</p><p>Do you need a genuinely custom design, something that doesn’t look like every other app built with the same library? If yes, shadcn/ui makes a lot of sense, since owning the component code means nothing is off limits.</p><p>Do you need a ton of ready made, complex components out of the box, like advanced tables, enterprise grade forms, or heavy data components? Then MUI or Ant Design will probably save you more time.</p><p>Are you building a SaaS product, something like an AI tool, a dashboard, a startup MVP, or a developer facing platform? shadcn/ui tends to fit that kind of project really well.</p><p>Are you just building something simple, like a portfolio site or a landing page? Honestly, plain Tailwind CSS might be all you need. You don’t have to reach for a full UI system every time.</p><h3>Setting it up in a Next.js project</h3><p>Getting started is pretty straightforward. Initialize it first.</p><pre>pnpm dlx shadcn@latest init</pre><p>Then add whatever component you need, say a button.</p><pre>pnpm dlx shadcn@latest add button</pre><p>That drops the file straight into your project.</p><pre>components/<br> └── ui/<br>      └── button.tsx</pre><p>From there, it’s just a regular file in your codebase, use it and edit it however your project needs.</p><h3>Questions people usually have</h3><p><strong>Is shadcn/ui a component library?</strong> Not in the technical sense. It’s more of a system that hands you reusable components while making sure the actual source code lives inside your own project instead of some package you install.</p><p><strong>Should every project use it?</strong> No, not really. Different projects have genuinely different needs, and sometimes a full featured library like MUI or Ant Design is just the more practical route.</p><p><strong>Is it only useful with Next.js?</strong> Not at all. It works fine in any React project, it’s just that the Next.js community adopted it especially fast, which is why the two get mentioned together so often.</p><h3>Final thoughts</h3><p>The real strength of shadcn/ui comes down to ownership. You’re not just installing a package and working within whatever boundaries it sets. You’re pulling components into your own codebase and keeping full control over them going forward.</p><p>That said, none of this means shadcn/ui is automatically the right call for every project. If you’re after a highly customized design with a modern React workflow, it’s an excellent option. If what you actually need is a massive library of ready made enterprise components, Material UI or Ant Design will likely serve you better.</p><p>At the end of the day, the best tool isn’t whatever’s trending the hardest. It’s whichever one actually fits what you’re building.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54e21c0727cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why I Stopped Using One Single SSH Key for GitHub (And You Probably Should Too)]]></title>
            <link>https://surajsrggupta.medium.com/why-i-stopped-using-one-single-ssh-key-for-github-and-you-probably-should-too-a006f101ffa2?source=rss-761b5c125020------2</link>
            <guid isPermaLink="false">https://medium.com/p/a006f101ffa2</guid>
            <category><![CDATA[ssh-keygen]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[ssh-keys]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Mr. S. Gupta]]></dc:creator>
            <pubDate>Thu, 16 Jul 2026 14:03:01 GMT</pubDate>
            <atom:updated>2026-07-16T14:03:01.080Z</atom:updated>
            <content:encoded><![CDATA[<h3>For the longest time I was doing what most people do when they start out with Git and GitHub. One SSH key, doing everything. Pushing code, pulling repos, signing commits, all from the same pair of files sitting quietly in my .ssh folder. It worked fine. Never gave me trouble. So I never really questioned it.</h3><p>Then one day I was reading through GitHub’s docs for something completely unrelated, and I noticed they actually let you register two different <em>types</em> of SSH keys. One for authentication, and one purely for signing commits. That small detail stuck with me, and honestly it took me a weekend project to actually sit down and understand why this separation even exists in the first place.</p><p>So here’s what I learned, and how I set it up on my own machine. If you’re someone who has multiple GitHub accounts, contributes to open source, or just wants your commit history to look a bit more trustworthy with that green “Verified” tag, this is worth doing.</p><h3>First, the confusion: authentication and signing are not the same thing</h3><p>I used to think SSH keys on GitHub had one job, prove it’s you. Turns out that’s only half true.</p><p><strong>Authentication</strong> is about access. When you clone, pull or push a repo, GitHub needs to confirm that the machine talking to it actually belongs to you. That’s what your regular SSH key handles.</p><p><strong>Signing</strong> is about trust in your commits, not your access. Anyone who has your repo cloned locally can technically create a commit and put your name and email on it in the author field. That doesn’t mean <em>you</em> wrote it. Signing solves that. When a commit is signed with your private key, GitHub can verify the signature and show that little “Verified” badge next to it, which basically tells other developers this commit genuinely came from you and not from someone spoofing your identity.</p><p>Two very different jobs. So I figured, why should one single key be responsible for both?</p><h3>The setup I ended up going with</h3><p>After going back and forth, here’s the folder structure I landed on inside ~/.ssh/:</p><pre>~/.ssh/</pre><pre>id_ed25519_personal<br>id_ed25519_personal.pub</pre><pre>id_ed25519_personal_signing<br>id_ed25519_personal_signing.pub</pre><pre>config</pre><p>Two separate key pairs. One purely handles GitHub access, the other purely handles commit signatures. Nothing overlaps.</p><h3>Step 1: Creating the authentication key</h3><p>I went with Ed25519 since it’s what’s generally recommended these days over the older RSA keys, it’s faster and just as secure with a much shorter key length.</p><pre>ssh-keygen -t ed25519 -C &quot;contact@devnotes.example&quot; -f ~/.ssh/id_ed25519_personal</pre><p>It’ll ask you to set a passphrase during creation. Don’t skip this part out of laziness like I almost did. A passphrase means that even if somehow your private key file ends up in the wrong hands, it’s still useless without that phrase. Small extra step, real difference in security.</p><p>Once done, you’ll have two files:</p><pre>id_ed25519_personal<br>id_ed25519_personal.pub</pre><p>The .pub file is your public key, the one you&#39;re allowed to share anywhere. The other file, without the .pub extension, is your private key. That one never leaves your machine, never gets pasted anywhere, never gets emailed to anyone, no exceptions.</p><h3>Step 2: Adding it to GitHub</h3><p>Copy the public key to your clipboard:</p><pre>cat ~/.ssh/id_ed25519_personal.pub</pre><p>Head over to GitHub, go to <strong>Settings → SSH and GPG keys → New SSH key</strong>, paste it in, and this is the part people usually miss, make sure you select:</p><pre>Key type: Authentication Key</pre><p>Once it’s added, test the connection:</p><pre>ssh -T git@github-personal</pre><p>If everything’s set up correctly you’ll see something like:</p><pre>Hi yourusername! You&#39;ve successfully authenticated, but GitHub does not provide shell access.</pre><p>That message is basically GitHub telling you “yep, I know who you are now.”</p><h3>Step 3: Setting up the SSH config file</h3><p>This part is what actually ties everything together, especially useful if you’re juggling more than one GitHub identity (say a personal account and a work account). Open or create:</p><pre>~/.ssh/config</pre><p>And add this block:</p><pre>Host github-personal<br>    HostName github.com<br>    User git<br>    IdentityFile ~/.ssh/id_ed25519_personal<br>    IdentitiesOnly yes</pre><p>That IdentitiesOnly yes line looks tiny but it matters a lot. Without it, SSH tends to just try every single key it finds in your .ssh folder one by one until something sticks, which gets messy fast once you have multiple keys lying around. With this line, SSH is told explicitly, &quot;only use the key I&#39;m pointing you to, don&#39;t go guessing.&quot;</p><h3>Step 4: Creating a separate key just for signing</h3><p>Now for the second key, the one that has nothing to do with logging into GitHub and everything to do with proving your commits are genuinely yours.</p><pre>ssh-keygen -t ed25519 -C &quot;contact@devnotes.example&quot; -f ~/.ssh/id_ed25519_personal_signing</pre><p>This gives you another pair:</p><pre>id_ed25519_personal_signing<br>id_ed25519_personal_signing.pub</pre><p>Take the public half back to GitHub’s SSH key settings, add it again, but this time choose:</p><pre>Key type: Signing Key</pre><p>Yes, you’re allowed to add multiple keys under the same account as long as you pick the right type for each one.</p><h3>Step 5: Telling Git to actually use it for signing</h3><p>By default Git assumes you’re using GPG for signing, so we need to switch that over to SSH format:</p><pre>git config --global gpg.format ssh</pre><p>Then point Git to your new signing key:</p><pre>git config --global user.signingkey ~/.ssh/id_ed25519_personal_signing.pub</pre><p>From here you can sign commits manually one at a time:</p><pre>git commit -S -m &quot;First signed commit, finally&quot;</pre><p>Or, if like me you’d rather not remember to add -S every single time, just make it automatic for every commit going forward:</p><pre>git config --global commit.gpgsign true</pre><p>Now every commit you make carries your digital signature without you having to think about it.</p><h3>Making sure it actually worked</h3><p>Locally, you can double check with:</p><pre>git log --show-signature</pre><p>And once you push it up, GitHub will show a <strong>Verified</strong> badge right next to the commit in the repo history. That badge is basically GitHub’s way of confirming to anyone browsing the repo that this commit is authentically yours and hasn’t been tampered with or spoofed.</p><h3>Was this actually worth the extra setup?</h3><p>Honestly, for a lot of casual personal projects, no one’s going to notice or care whether your commits are signed. But once you’re contributing to open source, working with a team, or just care about your GitHub profile looking legitimate and professional, this small separation between “who can access my repos” and “who can prove a commit came from me” starts to matter a lot more.</p><p>Here’s roughly how the two pieces fit together once it’s all set up:</p><pre>SSH Authentication Key<br>        |<br>        v<br>GitHub Access (clone / pull / push)<br></pre><pre>SSH Signing Key<br>        |<br>        v<br>Commit Verification (Verified badge)</pre><p>Two keys, two jobs, no overlap. It took me maybe twenty minutes total to set this up properly, and now I don’t really have to think about it again. If you’ve been putting off doing this on your own setup, honestly it’s a pretty painless afternoon task and one of those things that quietly makes your whole workflow feel a bit more solid.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a006f101ffa2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>