r/SQL • • 4h ago

PostgreSQL Connection pooling & read/write isolation with Lakebase

5 Upvotes

folks working with Postgres across Lakebase and-or Neon db, how do u handle connection pooling, read/ write routings, & query isolation when analytics and app queries hit the same data ?
Any tips or best practices?


r/SQL • • 3h ago

Discussion LAST_VALUE kept giving me the current row instead of the last one. the default window frame was the reason

3 Upvotes

wanted the latest order amount next to every order for each customer, so i wrote this:

SELECT customer_id, order_date, amount,
LAST_VALUE(amount) OVER (
PARTITION BY customer_id ORDER BY order_date
) AS last_amt
FROM orders;

and got this:

customer_id | order_date | amount | last_amt
1 | 2025-01-05 | 40 | 40
1 | 2025-02-11 | 25 | 25
1 | 2025-03-02 | 60 | 60
2 | 2025-01-20 | 90 | 90
2 | 2025-02-28 | 15 | 15

last_amt is just amount again. FIRST_VALUE on the same window worked fine, which made it more confusing

the reason: once you put ORDER BY inside OVER, the default frame is `RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW`. so the "last" row of the frame is always the current row (or its last tie). FIRST_VALUE doesnt care because the start of the frame is still the first row

fix is to spell out the frame:

LAST_VALUE(amount) OVER (
PARTITION BY customer_id ORDER BY order_date
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) AS last_amt

now customer 1 gets 60 on every row and customer 2 gets 15

or skip LAST_VALUE and flip the sort: `FIRST_VALUE(amount) OVER (PARTITION BY customer_id ORDER BY order_date DESC)` gives the same result

same default frame in postgres, sql server, mysql 8 and sqlite (tested on sqlite). also the reason a running SUM can act weird when two rows have the same date, since RANGE treats ties as one group

anyone actually use LAST_VALUE with the full frame or do you all just do the FIRST_VALUE DESC trick?


r/SQL • • 17m ago

MySQL MySQL InnoDB – Index Gap Deadlock with Concurrent INSERT … SELECT

Thumbnail reddit.com
1 Upvotes

r/SQL • • 15h ago

PostgreSQL Moving into a data analyst role next year and figuring out how much SQL to learn past joins and GROUP BY

13 Upvotes

I'm an inventory planner and I've been writing my own queries against our Postgres reporting replica for about a year, mostly joins, GROUP BY and the odd subquery. I'm moving onto the analytics team in March and work is covering a course before then. The analysts there use window functions and CTEs everywhere, and I can read them but couldn't write one cold. Which SQL topics come up day to day in analyst work, and which can wait?


r/SQL • • 2h ago

SQL Server SSMS 22 extension skill

Thumbnail
github.com
1 Upvotes

Reposting to this group in case others are interested, thanks


r/SQL • • 13h ago

Discussion How I changed my boring commute time to sql upskilling

3 Upvotes

My daily commute was just watching reels on phone and I realized how much time I was wasting while commuting. Lately I have been trying to turn that dead time into a sql practice session on phone instead of doomscrolling or just looking out of window.

I started using an offline android SQL practice app which has no ads.

Runs a local SQLite sandbox with zero network needed, plus custom/preloaded schemas to mess around with queries freely, has company tagged interview inspired questions, daily scenario challenges, and quick output MCQs with explanation breakdowns

It uses a phone friendly editor with a symbol toolbar so writing queries on a screen doesn't feel like a chore.

If anyone else also follows a quick routine to brush up sql skills, then I would love to know it


r/SQL • • 1d ago

Discussion diagnosing wrong SQL by testing one edit mutations on the data (and the fan out case that shrinks the result)

4 Upvotes

i'm working on an automated SQL grader on DuckDB for a game. pass/fail grading is the straightforward part. explaining why a wrong query is wrong is getting difficult, because "93 rows, expected 13" doesn't really tell a player much.

guessing the mistake from the SQL text didn't work for me, there are too many ways to write the same thing. so the checker only uses the query to list candidate edits (each join, each aggregate). the data decides:

  • unmatched rows: flip one INNER JOIN to LEFT, or move the outer table's WHERE conditions into its ON. if that single edit makes the result match the expected rows exactly, that join is the mistake.
  • NULLs: swap COUNT(*) and COUNT(col), or AVG(x) and AVG(COALESCE(x, 0)). same exact-match test.
  • fan-out: change the data instead of the query. keep one row per join key in the repeated table, then run the learner's query and the reference on that. if they now agree, and the original result was inflated, the duplicates were it. then it shows the source rows that got repeated.

the screenshot: "users with a completed deposit and zero withdrawals, each user once". the join to deposits repeats a user once per deposit, so one user shows up 11 times. the panel names the key and the repeated rows.

the one i was stuck on until this week: fan-out that shrinks the result. one audit problem compares SUM(fills.quantity) > SUM(orders.quantity) after the join, so the order side gets inflated and the query returns fewer rows than it should. my inflation check never fired, because nothing was inflated in the output.

what ended up working: first a cheap probe per joined table, count(t.rowid) - count(distinct t.rowid), to see if that table's rows repeat at all after the join. if one does, rewrite each aggregate over it so every source row counts once (in duckdb: list_sum(map_values(map_from_entries(list(distinct row(t.rowid, x)))))), rerun, and require an exact match like the other edits. it hasn't misfired on the problems i've run it on, but that's my own test set, so take it with salt.

two things i'd like input on:

  1. is there a cleaner way to make an aggregate count each source row once after a join? SUM(DISTINCT x) is wrong when two different rows hold the same value, which is why i went through rowid. curious if other engines have something tidier.
  2. if you review SQL regularly, what common bug would completely fool a single-edit checker like this (besides compound mistakes, which already break it)?

r/SQL • • 9h ago

Discussion Does this table meet the normalization requirements (1NF, 2NF, and 3NF)?

Post image
0 Upvotes

I’m working on a database project for a metro system, and I’m not sure if my Train table satisfies 3NF.
I think Capacity depends on TrainModel rather than TrainID. If I enter different capacity values for trains of the same model, would that solve the problem, or would it still violate 3NF?
Should I remove Capacity from the table?


r/SQL • • 22h ago

Discussion Keeping a Redis cache in sync when jobs and manual SQL also write to the same tables

1 Upvotes

I've got Postgres with a Redis cache in front. The app deletes the cache key after it updates a row, and that part works. What I'm unsure about is everything else that writes to those tables:

  1. background jobs doing bulk `UPDATE`s
  2. someone fixing data in psql
  3. migrations and backfills
  4. another service sharing the same database

None of those go through the app's update, then delete the key path, so as far as I can tell, the cache just stays stale until the TTL runs out.

How are you handling this? Do your jobs and scripts clear the cache too, do you rely on the TTL, or did you move to something based on logical replication or Debezium? Has one of these other writers ever bitten you?


r/SQL • • 1d ago

Oracle How to understand the changes in pl sql, how to integrate AI into your work

2 Upvotes

I need help. I worked as a part-time pl sql developer supporting the l2/l3 line system, I was on maternity leave for 2 years, and during that time a lot has changed in the company and in technology, AI has spread a lot. I want to sort everything out in my head, but I don't understand where to get the information from, it won't do to ask the manager, I'm interested in developing in this area and catching up, but I don't understand where to start. I'm waiting for advice, maybe there is a map, etc. Or a brief overview of how things have changed. I hope my request is clear.


r/SQL • • 2d ago

MySQL need good sql resources

2 Upvotes

i wanted to practice sql and to be able to answer qns , i have noticed that i am struggling a bit when there is two tables give and the qn has to do something with joins and all , in theory i understand how the joins work but i am unable to implement it .I need resources which can help me in advancing my sql like CTE and window function . Is there any youtube channel or anything which will help


r/SQL • • 2d ago

Oracle UniQL now lists an open-source schema layer + a Flash model at 64.93% on its Oracle text-to-SQL column (best single-model baseline: 49.61%)

Post image
2 Upvotes

r/SQL • • 2d ago

SQLite A 60-second SQL test with three traps. Most AIs I've graded fall for at least one

0 Upvotes

I grade AI models on data questions for a living experiment, and the same three mistakes keep showing up. Here's a pocket version: paste it into whatever AI you use and see how it does. The database is SQLite.
sales (sale_id, amount):
1: 412.75 · 2: 268.40 · 3: 529.99 · 4: 145.20 · 5: 876.10 · 6: 233.65
7: 694.30 · 8: 358.55 · 9: 921.00 · 10: 187.45 · 11: 543.80 · 12: 476.25
returns (sale_id, one row per return event, 25 rows):
2, 5, 9, 2, 7, 3, 2, 11, 5, 12, 9, 4, 2, 7, 10, 5, 1, 9, 12, 4, 11, 8, 10, 13, 13
Task: write SQLite SQL returning exactly two columns: returned_sales (how many sales came back) and total_returned_sales (their total value, each sale counted once), and state the two numbers.
Answers, so you can grade it yourself:
Pass: 11 and 5,413.79, exactly two columns, SQL SQLite can run.
Trap 1: a total of 11,860.19 means it joined and summed, so sale 2 was counted 4 times. Counted twice (or four times).
Trap 2: a count of 12 means it counted sale 13, which is in returns but was never sold.
Trap 3: FETCH FIRST, EXTRACT, or more than two columns: wrong database or didn't follow the order.
On the full-size version of this case (500 return rows, 99 sales returned more than once), the counted-twice error invents $31,490.03. I've watched a model miss it twice in graded matches.
Curious what yours answered. Post the number it gave.


r/SQL • • 3d ago

Discussion Why you shouldn't do application-level sharding

Thumbnail
planetscale.com
37 Upvotes

r/SQL • • 3d ago

Discussion Should I stick to standard SQL or use DBMS-specific features?

7 Upvotes

Different DBMSs have their own functions and features. For example, PostgreSQL supports every() function, which isn't available in MySQL.

Is it better to stick to standard SQL as much as possible, or should I take advantage of DBMS-specific features? What are the benefits of staying close to the SQL standard?


r/SQL • • 3d ago

Discussion Anyone here have experience tutoring SQL? How did you start?

7 Upvotes

I would like to begin tutoring SQL to earn some money. I'm not exactly sure where to start though. I don't want to just tutor SQL, I'd like to do Python as well. Should I aim for a specific niche or just teach it zero to hero style?


r/SQL • • 3d ago

Discussion DBerio update: what I changed after your feedback on my SQL client

0 Upvotes

About a month ago, I posted my SQL client, DBerio, here and asked for feedback. A lot of you took the time to reply, and your comments helped shape this update. Same disclaimer as last time: I'm a solo developer from Korea, this is self-promo, and I use a translator to write.

Things you asked for

  • u/MrRoy_SQL asked for a visual EXPLAIN. The Profiler tab now shows PostgreSQL, MySQL and MariaDB plans as a tree, highlighting the slowest step and points to check. You can also summarize a plan on one page and print it or save it as a PDF.
  • u/vincent_sch pointed out that EXPLAIN ANALYZE runs the statement, so analyzing an UPDATE would change data. On PostgreSQL, measured plan runs now use a read-only transaction, so the server blocks writes. Statements containing functions that a read-only transaction can't stop, such as ending a session, ask for confirmation first. Thanks for catching that. It was a real hole.
  • DROP, TRUNCATE and ALTER … DROP statements run from the editor now ask for confirmation. If the connection is marked as production, you also have to type the target name.

Other changes

  • Long text and JSON from the result grid now open in a larger Value Editor, with line numbers, search, JSON error locations and an editable JSON tree. Big integers and long decimals keep their exact digits.
  • There's a dark mode now.
  • If a connection drops, it reconnects when you expand the object browser or open a table, as well as when you run a query.
  • Fixed a bug where "Discard Edit" in the grid saved the value instead of discarding it. Sorry about that one.
  • Commit, Rollback and autocommit no longer hang while a long query is running.

Searchable query history across connections and a side-by-side diff of two result sets are still on my list. I haven't finished them yet.

Since 1.2.0, the app sends basic usage statistics: days opened, app version, OS and language. It never sends query text, connection details, table names or data, and you can turn statistics off in Settings.

DBerio is available on Mac and Windows and supports MySQL/MariaDB, PostgreSQL, SQLite and Redis. The free version includes every feature, with up to 3 saved connections and 2 open at once.

If you find a bug, notice something that feels off, or have a feature in mind that would make you switch, please comment here or send me a DM. The fixes above started with comments like those, so please keep them coming.


r/SQL • • 3d ago

Discussion Where do you actually write most of your SQL these days?

0 Upvotes

Curious how much this has shifted lately — feels like more people are moving across different types, but maybe that’s just my bubble. If you picked Other or switched recently, what made you switch?


r/SQL • • 3d ago

Discussion How practical are ERDs when coding?

Post image
0 Upvotes

It was my belief in the beginning of 2025 that this project would help ppl who work with databases. There were three main ideas I thought should be different from how it's been done for decades:

  1. There should be no proprietary syntax.
  2. ERDs must be rendered on the fly while coding (so no need for a separate tool or website)
  3. Cursor on a code segment must render that exact schema instantaneously (vs. rendering giant schemas all at once).

What's you perspective on this in 2026?


r/SQL • • 3d ago

BigQuery Is SQL becoming obsolete?

0 Upvotes

I had an interest with sql when mentioned by a minor subject of mine and its relation to my current major management accounting. I would like to learn and add that to my future resumé but I can help but feel its useless now because of AI where english words are automatically translated into codes. So is there a demand for this in the future? Or should I focus my resources elsewhere?


r/SQL • • 3d ago

SQL Server Wire level intelligent response caching solution for SQL Server - Change Tracking Mode

3 Upvotes

Hey, I've posted before on some of my custom TDS listener stuff. All custom TDS wire protocol in c#. I think this one is probably my most useful one so far. I had posted one earlier on the first cut TTL mode, but this demo covers the more sophisticated one, the change tracking mode.

Full Open Source Code (MIT): https://github.com/TroBeeOne/DaffyZoom
Nuget Install and Instructions: https://www.nuget.org/packages/Daffyzoom
Hour long podcast on how it works (it's ~98% correct but it made a couple mistakes): https://www.youtube.com/watch?v=mwMDmuLjCCY

What it does:

- It solves the problem of 1000+ repeated slow queries that are hitting stale tables. It also helps you identify those slow queries so you can 'actually fix' the indexes, plans, the proper way.

- Sits on the wire in-between client and SQL server

- On the return from SQL Server message it tee's the call, one sync back to client, another async to my caching system. If a repeat query (above 5 second default setting) if tables haven't changed, it now returns instant cache, 0 seconds. if table changed? it reruns the 7 second query and updates the cache on the way back..

- I have data warehouse mode, ttl, just caches everything repeated. with expiration.

- I have change tracking mode (this is the demo I'm showing today). This caches unless a change is made, then it runs the query as normal and refreshes cache.

- Change Tracking Mode requires change tracking enabled on target tables for repeated query. You might think, well, we're now hitting SQL Server 2 times? Yes, but the check is a microsecond. And if you're serving cache from a 10 second query instantly, and ppl are hitting that report at 8am 1000 times, you saved some compute time and made your clients super happy!

- I DO support Entra Service Credentials, but I do not support MFA. I also don't support kerberos yet, I could, but that would require me setting up a domain controller VM, and with little interest so far, no incentive.

Anyway, I haven't tested this in a major production environment yet, so if you do choose to try it, as with anything, test it well and let me know if you find issues.

Here's the demo, cheers. If you try it and run into questions or have issues, let me know. It only caches long queries. It doesn't poll SQL Server for all queries, only the slow ones. It doesn't cache things with getdate() or CRUD related operations obviously. Its all in the documentation / code.


r/SQL • • 3d ago

PostgreSQL Text column is storing accented text weirdly

Thumbnail reddit.com
0 Upvotes

r/SQL • • 3d ago

PostgreSQL If JOIN combines tables, why do we have so many different types of JOINs?

0 Upvotes

I understand how joins work in SQL, but I've always wondered why we need so many variations like INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL OUTER JOIN.

At the end of the day, we're just joining two tables based on a condition. Is the difference mainly about deciding which rows to retain when there isn't a match, or is there more to it than that?

Curious how others think about this, especially when working with real-world queries. Is there a particular join type you find yourself using most often, and why?


r/SQL • • 4d ago

SQL Server Negative reseed risks

8 Upvotes

One of the Sqlserver tables had an int identity column and maxed out the value. Team planned to reseed the identity from the lowest-ve value so that it can run on the same datatype for another 5 or 6 years. I am thinking that this would be a costly mistake if they plan to migrate this data into a new platform. The original solution was to change this to a bigint. Since this field has 300+ fks all those need to be dropped and recreated. What could possibly go wrong by choosing a -ve value reseed? I see the daily seed count is topping approximately 1 to 1.5million ids.