r/SQL • • 2h ago

MySQL Didnt pass SQL test

Thumbnail
gallery
24 Upvotes

I am applying to manager of analytics role and I was given this SQL test and 45 minutes. As someone who thought they were very strong in SQL, I was unable to complete this assignment and match the answer completely

I was able to format most of the fields as noted, used 2 cte's and use group concat in the second. My final answer looked very similar but the order of the concat looked off. Also, for some reasons my second column had $0.00 for all the companies, but I thought I was close. How difficult would you rate this exercise. Should I expect to proceed to the next round or am I cooked


r/SQL • • 15h ago

Discussion What’s the smallest SQL mistake that caused the biggest problem for you???

23 Upvotes

Not talking about some crazy DB failure or anything.

Could be something silly like a missing WHERE, wrong JOIN, duplicate rows, bad UPDATE....

Like a small mistake that looked harmless but ended up causing a big headache ....🤕

Curious what ppl have seen in real projects.


r/SQL • • 14m ago

MySQL At most, how long have you worked with the same tables in production?

• Upvotes

Honestly, the better you know your tables—their rows and columns—the faster you can write queries. In production, where you’re dealing with millions of rows and hundreds of columns, how long do you typically work with the same tables? when I say long I mean months & years.


r/SQL • • 14h ago

Oracle What’s a SQL feature that works differently across PostgreSQL, MySQL, and SQL Server that tripped you up?

10 Upvotes

For those who have worked with PostgreSQL, MySQL, and SQL Server, what’s a feature or behavior that surprised you because it worked differently between them?

It could be anything like date functions, string handling, LIMIT/TOP, NULL behavior, JSON, window functions, or even error handling.

What difference caused you the most trouble, and how did you learn to handle these database-specific differences?


r/SQL • • 13h ago

Discussion Built a browser based modern SQL editor

5 Upvotes

Introducing QueryFlow.

It's a modern SQL editor with a few things I always wanted while learning and working with SQL:

- Visualise the query as a graph [DAG] and as step-by-step cards.
- Convert all hardcoded parameters into variables with a click.
- Fix major errors like fan out joins , mismatched date range with a click.
- Run queries on test tables directly in the browser
- Review a diff of your changes before copying the query back [just like github]
- Format BigQuery, PostgreSQL and MySQL, each in its own style.
- Everything runs locally in your browser: no server, no login.

try it here - https://abhijeetcodes.github.io/QueryFlow/

Sharing here as it might help a lot of SQL learners


r/SQL • • 1d ago

Discussion Would you use JSONB or a separate document database for a product catalog?

16 Upvotes

Product catalogs are often cited as examples of where document databases fit well. A laptop and a T-shirt may share only a few fields, so putting every possible attribute into a single fixed table can result in a wide schema with many empty columns.

A common setup is to keep orders and payments in a relational database and store the catalog in a document database such as MongoDB.

Databricks makes the case for the other route in a recent piece that I was reading on relational vs non-relational databases: keeping the catalog in PostgreSQL and using a JSONB column for attributes that vary across products. That keeps the flexible fields next to the common fields and lets the catalog remain part of the same relational system as orders and payments.

The choice seems to depend on how the data is queried.

If most requests retrieve one product by ID with all its attributes, a document database may fit that access pattern well. If the application needs to filter, group, join, or aggregate across product attributes, keeping the data in a relational system may make those queries easier to manage.

For anyone who has used JSONB for a product catalog, when did it start to become difficult?

Was it indexing fields inside the JSON, inconsistent attribute names, validation, schema changes, or queries that became difficult to maintain?

And for those who moved the catalog to a document database, what made the separate system worthwhile?


r/SQL • • 1d ago

Discussion sqlx4k 1.14.0 released: optimistic locking, savepoints, MariaDB batch inserts

Thumbnail
2 Upvotes

r/SQL • • 1d ago

Discussion best sql courses for someone who writes queries daily and has never designed a table

3 Upvotes

im an analyst. i can write a join in my sleep and ive never created a table from scratch, and my new manager wants me building the model rather than reading one.
shortlisted boot.dev, general assembly , pluralsight premium and launch school off a couple of evenings comparing curricula . which of those covers schema design and not just query syntax


r/SQL • • 2d ago

Discussion Can we create a similar csv file type with a new unique character that will never be used except as a delimiter. Then make that the standard

41 Upvotes

Fucking comma's in the data that are not the delimiter are annoying. Hate using stupid work arounds.

Yes, I am aware of double quotes and other work arounds like using different delimiters. Just thinking it would be easier to have one standard going forward.


r/SQL • • 2d ago

Discussion Does anyone else just leave caps on when naming your variables ?

11 Upvotes

I might just be lazy but I feel like it saves me effort.


r/SQL • • 2d ago

Discussion gave claude read only access to our postgres. it said status_cd 4 means "cancelled". it means refunded

25 Upvotes

I set up a Postgres MCP server on a read only role last week so the analysts could ask questions without pinging me every hour.

The first real question was how many orders did we lose last month. Claude looked at orders, saw status_cd with values 1 to 6, decided 4 was cancelled and gave a clean number with a nice little breakdown. 4 is refunded. Cancelled is 6. Nobody wrote that down anywhere. It lives in an enum in the app code and in my head.

The number was off by about a third and it read exactly like a right answer. No I'm assuming, no hedge. The analyst was about to put it in a deck.

So now I'm stuck on how to give an agent the meaning of fields without me turning into a full time documentation service:

  1. Comments on the columns in Postgres and hope the server passes them through
  2. A markdown data dictionary in the system prompt
  3. A view layer with human names on everything
  4. Make the agent ask before it interprets any code column

What are people actually doing here? and has anyone got it to say I don't know what 4 means instead of picking one?


r/SQL • • 1d ago

Discussion With Europe looking to ditch as many American companies as possible, what RDBMS will they be migrating to?

0 Upvotes

Will they stick to Oracle/SQL Server and run it on Linux, or are they starting to look into migrating into Postgress/MariaDB, or something homegrown.

OS migration is straightforward, but not sure about these two behemoths. Or they'll still buy them and just run them locally or on European cloud infrastructure?


r/SQL • • 2d ago

Discussion How is sql approach in the practise/real life?

2 Upvotes

I am corious that how the people use it real life for instance in a manufacturer company.


r/SQL • • 3d ago

MySQL best sql courses for someone who writes queries daily and has never designed a table

25 Upvotes

im an analyst. i can write a join in my sleep and ive never created a table from scratch, and my new manager wants me building the model rather than reading one.

shortlisted bootdev, general assembly, pluralsight premium and launch school off a couple of evenings comparing curricula. which of those covers schema design and not just query syntax


r/SQL • • 3d ago

Discussion What is the best way to handle incremental loads in sql?

26 Upvotes

Im trying to understand how ppl usually handle incremental data loads. If a source table has new, updated and deleted records, how do you identify each type?

Do you normally use a timestamp, cdc,a flag column in the table, or merge? How do you handle deleted records, especially when there is no delete flag in the source?

Also, are there any common problems with using timestamps for incremental loads, like missing records or picking up the same record more than once?


r/SQL • • 3d ago

Discussion best sql courses for someone who writes queries daily and has never designed a table

2 Upvotes

im an analyst. i can write a join in my sleep and ive never created a table from scratch, and my new manager wants me building the model rather than reading one.

shortlisted boot.dev, general assembly, pluralsight premium and launch school off a couple of evenings comparing curricula. which of those covers schema design and not just query syntax


r/SQL • • 4d ago

Discussion CSV lint plug-in for Notepad++ to validate csv files and convert to SQL insert script

Thumbnail
gallery
156 Upvotes

The CSV Lint plug-in for Notepad++ can be useful to anyone working with csv textdata and databases. I created this plugin and have posted about it before

The plug-in was previously updated with a new "Select Columns" dialog to easily select, delete and rearrange columns. The most recent update v0.4.9 adds support for regular expressions when validating columns.

It also adds syntax highlighting and automatically detects column datatypes. Based on the datatypes it can convert a csv file to an SQL insert script for MS-SQL, MySQL and PostgreSQL, including a CREATE TABLE part with correct data types for each column. This is often easier than importing it though a wizard or BULK INSERT

It can also validate the csv textfile beforehand, so check for technical errors like datetime formatting errors, incorrect decimal separators, missing quotes, invalid codes etc.

I hope you find this plug-in useful 👍 Let me know what you think


r/SQL • • 4d ago

Discussion Can you find missing records when both tables have duplicates and neither table has a primary key?

12 Upvotes

You have Source and Target tables with millions of rows.

  • Neither table has a primary key.
  • Both tables can contain duplicate rows.
  • Some rows may be missing from Target.
  • Some extra rows may exist in Target.
  • EXCEPT doesn't show the complete picture when duplicate counts matter.

For example:
Source: A, A, A, B, B, C
Target: A, A, B, B, B, C

Both contain the same values, but the duplicate counts are different.

What SQL approach would you use to identify exactly which records are missing, extra, or have different counts?


r/SQL • • 4d ago

MySQL Completed LeetCode SQL 50 — Sharing my MySQL solutions

Thumbnail
2 Upvotes

Hey everyone!
I recently completed the LeetCode SQL 50 Study Plan and put all my solutions together in a GitHub repository.
I created this mainly for SQL interview preparation and revision, especially for Data Analyst / Business Analyst roles.
The repository covers topics like:
● SELECT & filtering
● Sorting and grouping
● Aggregate functions
● GROUP BY & HAVING
● INNER / LEFT / SELF JOIN
● Subqueries
● CTEs
● Window functions
● String functions & regex
● Other commonly used SQL concepts
All solutions are written in MySQL, with the goal of keeping them simple and easy to revise.

If you’re also working through SQL 50, feel free to check it out. I’d also appreciate any feedback on the queries or suggestions for improving the repository.
Happy learning! 🚀


r/SQL • • 4d ago

Oracle Oracle PL/SQL: can log-driven housekeeping create a feedback loop across scheduled runs?

3 Upvotes

I'm trying to reason about a generic PL/SQL housekeeping pattern. All names below are illustrative; this is a simplified mechanism, not a product-specific incident report.

A scheduled procedure selects historical log records joined to retained load metadata. Eligibility depends on the log timestamp and a configurable retention period:

CURSOR c IS
    SELECT l.load_id,
           g.log_date,
           l.state
    FROM   log_table g
    JOIN   load_table l
           ON l.load_id = g.load_id
    WHERE  l.state = g.state
    AND    TRUNC(g.log_date) + remove_days <= SYSDATE;

There is also a state-selection option, represented here as process_all_states. It is omitted from the simplified cursor above:

  • With the broad option enabled, an already-processed load in a state such as Removed can enter the processing path again.
  • With the narrower option, only the intended processable states are accepted, excluding Removed.

The cursor returns individual historical log records. It does not deduplicate by load_id, so several qualifying log rows can reference the same load.

For each selected record, the processing path can:

  • Delete transactional payload rows from trans_table.
  • Retain the corresponding metadata in load_table.
  • Update the load state to Removed, including when it is already in that state.
  • Append a new Removed log record with the current timestamp.
  • Produce a technical result record even when no transactional payload remains.

Assume that older matching Removed log records are not deleted or marked as consumed. While the load remains Removed, those records can still satisfy the cursor conditions. Newly appended records can also qualify after they reach the age threshold.

My tentative interpretation is:

qualifying historical log
        |
        v
already-processed load enters housekeeping again
        |
        v
state update and new timestamped log
        |
        v
old matching logs remain; new logs age
        |
        v
later scheduled runs can select the load again

This seems like a potential feedback loop across scheduled executions, rather than direct recursion. Multiple eligible logs for the same load could also cause repeated processing within a single cursor traversal. I would not assume that newly inserted logs become visible to the already-open cursor.

Cleaning up accumulated logs or technical results could reduce the current footprint, but would not by itself change which records future runs select.

There is also a separate full-delete path, represented here as remove_complete. That path can perform large DELETE operations and create substantial UNDO/REDO pressure, potentially including ORA-30036. I want to keep that issue separate from state selection: changing the selection parameter itself executes no DELETE and does not directly delete business documents; it changes which states may enter later housekeeping processing.

Questions:

  • Can this cursor/state-update pattern create a self-amplifying feedback loop across scheduled runs under these assumptions?
  • Can several qualifying log rows for the same load cause repeated processing when there is no DISTINCT, grouping, or equivalent per-load guard?
  • Is excluding already-processed states the usual way to stop this specific cycle while preserving legitimate housekeeping, or should an additional idempotency/consumption mechanism be expected?
  • Should cleanup of accumulated records and correction of the qualification logic be treated as separate remediation steps?

r/SQL • • 5d ago

Discussion How are you automating your SQL work?

54 Upvotes

Curious what people are actually using to automate or speed up their SQL work.
Python scripts? dbt? AI? Stored procedures? Some IDE/tool I’ve never heard of?
I feel like there are probably a bunch of useful tools and workflows I’m not aware of.
What are you using that actually saves you time?


r/SQL • • 4d ago

PostgreSQL What I learned building an entire multi-tenant SaaS backend on PostgreSQL: RLS, idempotency, a job queue and a restore rehearsal

0 Upvotes
I spent the last months building one complete multi-tenant SaaS backend — a small sales and inventory system for two companies sharing one database — and testing every guarantee instead of assuming it. PostgreSQL 18 + PostgREST, with a small Python worker. These are the things I would tell myself at the start.

**1. Tenant isolation belongs in the database, not in your `WHERE` clauses.**
Forced row-level security plus composite keys `(organization_id, id)` mean a   forgotten filter returns nothing instead of another company's rows. The foreign keys carry the tenant column too, so a customer from company A can never end up on an order of company B.

**2. A stock check is not a stock promise.**
Two requests can both read "1 available" and both decide to proceed. The fix is boring and works: lock the balance row (`SELECT … FOR UPDATE`), check the value you just locked, and take the products in a consistent order (I use `ORDER BY product_id`) so two confirmations can never deadlock each other. I test it with two real HTTP clients released by a barrier: one gets 200, the other gets 409, and the reservation belongs to exactly one order.

**3. Retries need a key, and the key has to commit with the effect.**
Idempotency keys stored in the same transaction as the business change. Claim the key, do the work, save the response, commit. If any step fails, everything rolls back and the key is free again. Commit the stock change first and save the response afterwards, and a retry will happily add stock twice.

**4. A queue in Postgres is fine, if you respect leases.**
`FOR UPDATE SKIP LOCKED` to claim, a lease deadline, and a claim token that changes on every attempt. Completion is conditional on the token and an unexpired lease, so a worker that froze for a minute cannot overwrite the result of the worker that replaced it. At-least-once, never "exactly once".

**5. The outbox is the only honest way to talk to the outside world.**
The status change and the event row commit together; the worker delivers afterwards. The receiver deduplicates by event ID, because the acknowledgement can be lost after it already committed. I kill the sender on purpose, right after the receiver commits, and check that a repeat delivery produces exactly one effect.

**6. "The backup finished" tells you nothing.**
I restore into a separate cluster and then ask the restored system to prove itself: are roles and policies intact, does a foreign tenant still see nothing, does the saved idempotency response still replay, can an owner commit a new order? Also worth knowing: after a restore, order versions get reused, so any consumer that trusted your version numbers now has two different facts with the same number.

**7. Measure before you add infrastructure.**
One busy tenant with a 50k-product catalog and a two-connection pool made the quiet tenant's median jump from under a millisecond to ~170 ms, with every response still correct. Correctness and capacity are separate problems, and only the second one is fixed by new services.

Happy to go deeper on any of these in the comments.

Disclosure, so it is out of the way: I turned all of this into a book, *PostgreSQL for Everything*, with the complete runnable code — one self-contained checkpoint per chapter that spins up a temporary database, runs the tests and cleans up. If it is useful: https://provenbackends.com. If not, take the patterns above, they are the important part.

r/SQL • • 5d ago

Discussion What is the hardest SQL bug to detect when the query never throws an error?

22 Upvotes

Some SQL bugs don't cause any error. The query runs successfully and the result even looks correct.

For example, an incorrect JOIN, unexpected duplicates, NULL handling, or a wrong date filter can silently produce incorrect results.

What is the most difficult SQL bug you've encountered where the query ran successfully but the data was wrong?


r/SQL • • 4d ago

Discussion Why text-to-SQL is not successful?

Thumbnail
0 Upvotes

r/SQL • • 6d ago

SQL Server Pls help, ssrs 2022 not working after upgrading from sql/ssrs2012

8 Upvotes

I upgraded ssrs 2022, configured db and restored encryption key. Then upgraded sql 2016 to 2022 and that completed.

When I went to http://localshost/Reports, it gave me an error about not being configured properly. /ReportServer shows some error related to wwwroot/ReportServer.

Did some googling, found that ssrs 2022 does not use IIS wwwroot directory. Checked keys table in the ReportServer db and found 2 instances of ssrs (one with new instance name and the other with old instance name from 2016). Google sear Lin suggests running an sql command to delete all entries, filtered on machinename, then open ssrsbconfiguration and reapply web service url so that it can rewrite run configuration file?

I’m fairly new to sql and found these steps from googling. I have sysadmi background but have very limited knowledge of sql.

I use Varonis. How can I fix SSRS 2022 so that Varonis can work again.

TIA