r/learnSQL • • 15d ago

Turn rows into columns without PIVOT, using CASE

29 Upvotes

Not every database has PIVOT, but you can do the same thing with CASE.

Say you have sales by month in rows:

productmonthsales
AJan100
AFeb150
BJan200

And you want each month as a column:

SQL:
SELECT product,SUM(CASE WHEN month = 'Jan' THEN sales ELSE 0 END) AS jan,SUM(CASE WHEN month = 'Feb' THEN sales ELSE 0 END) AS feb FROM sales GROUP BY product;

Result:

productjanfeb
A100150
B2000

Works in almost every database. Do you use this trick, or do you prefer PIVOT?


r/learnSQL • • 16d ago

I am new to SQL , help me to find approach.

36 Upvotes

I started solving SQL questions since last week from youtube videos and LearnSQL I encountered new type of problems which I couldn’t solve or half solve or do hit & trial methods like new queries like - “ROUND,LIKE and more”.
But the main problem is I can’t memorise every new problem and solve thousands of problem.
In some questions i couldn’t find how to approach a problem like should i apply sub queries or Group by Or JOINS.

Is there any approach how to identify a problem?
What are the mistakes I should avoid while solving the questions or learning?
I am aiming for Data Analyst role, first I am trying to get grasp on these queries then i’ll move to CTE, window functions.
Thanks


r/learnSQL • • 16d ago

Ruddy is now running DuckDB 2.0!

3 Upvotes

Hey everyone,

I’m an independent developer who started building Ruddy in my free time: a fast, modern macOS IDE for data management, analysis, and data science powered 100% by DuckDB.

With this new release, the core engine has officially been upgraded to DuckDB 2.0!

Ruddy runs on a true Pay-What-You-Want (PWYW) model—support independent development with whatever you feel it’s worth, or start exploring for free.

Check it out: ruddy.pro

I’d love your thoughts, benchmark requests, or features you'd like to see next!

What’s inside Ruddy:

  • DuckDB 2.0 Core Engine: Blazing-fast columnar processing over local files, Parquet, Arrow, CSV, and Iceberg/Delta Lake tables without spinning up heavy infra.
  • Multi-Cloud Direct Querying: Federate and query across AWS S3, Cloudflare R2, Google Cloud Storage, Azure Blob, and MotherDuck seamlessly in a single SQL statement.
  • Reactive Notebooks & Marimo: Build reproducible, reactive Python data science notebooks that sync directly with your in-memory DuckDB tables.
  • First-Class Geospatial Analytics: Full DuckDB spatial extension support—render GeoParquet, Shapefiles, and spatial geometries interactively on high-performance maps.
  • Auto-Ontology & Modular Semantic Layer: Automatically infers FACT/DIMENSION roles, deduces canonical SQL metrics, verifies joins via physical data overlap, and generates Open Semantic Interchange (OSI v1.0 / Apache Ossie) YAML specifications per dataset domain.
  • Context-Aware AI Assistant (Ruddynie): Text-to-SQL agent grounded in your workspace ontology and self-improving query memory—zero phantom table or join hallucinations.
  • Model Context Protocol (MCP) Integration: Expose your DuckDB catalogs, query tools, and semantic context to any external MCP-compatible AI agent or client.
  • Built-in Git Version Control: Track schema migrations, SQL queries, notebooks, and semantic models with standard Git repositories right from the workbench.
  • Force-Directed Semantic Graphs & Visual SQL Builder: Explore domain schemas visually or drill down with interactive force-directed relationship maps.

r/learnSQL • • 16d ago

Title: Day 65-67 — Combined update: revised all my Java so far and started the Collections framework (ArrayList)

5 Upvotes

After building two OOP projects, I used these three days to revise everything I’ve covered in Java, then moved on to a new topic: the Collections framework, starting with ArrayList.

Tomorrow I’m covering LinkedList, HashMap, and HashSet. For each one I plan to write a small exercise based on a real-life situation (for example, a contact book for HashMap, or removing duplicate entries with HashSet), because I learned from SQL that I remember a topic much better when I use it on something concrete.

For people who’ve learned collections: which real-life exercises helped you understand when to pick one collection over another? I’m especially unsure about LinkedList, since ArrayList seems to cover most cases.


r/learnSQL • • 17d ago

SQL cheat sheet table

9 Upvotes

Sharing my SQL cheatsheet table. This is meant to be a useful starter pack covering the essentials, in the quickest format I could think of: a table with examples.

https://github.com/kixwho/PostgreSQL-cheatsheet

Note: Based on Practical SQL (O'Reilly Media), a very good textbook. If there's another essential SQL concept you'd like to see included, just let me know! :D


r/learnSQL • • 17d ago

Keep hearing AI can write good SQL. Can AI write complex SQL involving Window functions, CTE etc for complex business purposes?

19 Upvotes

r/learnSQL • • 17d ago

What are some interesting SQL problems or query mistakes worth discussing?

23 Upvotes

I'm planning to share some SQL-related content on LinkedIn, but I want to avoid the usual beginner-level tutorials or generic interview questions.

I'm particularly interested in intermediate-level SQL concepts, window functions, CTEs, tricky query behavior, or situations where a query looks correct but produces unexpected results.

I'd love to hear from people working with SQL regularly.

What's an interesting SQL problem, subtle query mistake, or unexpected behavior you've encountered that made you think twice?

Looking for something technically meaningful that could spark a good discussion rather than another basic SQL tutorial.


r/learnSQL • • 16d ago

The one-character bug that fails a lot of SQL interview answers

0 Upvotes

A pattern I keep seeing when people practice SQL for analyst interviews.

The question: "Return every active subscription paying at least $1,500 a month."

A very common answer:

SELECT company_name, plan_tier, monthly_amount
FROM subscriptions
WHERE status = 'active'
  AND monthly_amount > 1500
ORDER BY monthly_amount DESC;

It runs, it returns rows, and it looks right. But "at least" means >=, so the customer paying exactly 1500.00 silently disappears. In an interview the query "works", so you don't notice. Against the expected output it's simply wrong.

Things worth checking every time a question has a threshold:

  • "at least" / "minimum of" -> >=
  • "more than" / "over" -> >
  • "between" -> BETWEEN is inclusive on both ends; dates with timestamps need care
  • Does the sample data contain a row exactly on the boundary? Interviewers often add one on purpose.

I built a free practice site around this kind of feedback: you write real PostgreSQL in the browser and it shows you which rows are missing or extra compared to the expected result. This exact problem is the first one, no signup: https://dbexercises.vercel.app/exercise/saas-active-subscriptions

Happy to hear what other "looks right, is wrong" traps you've run into.


r/learnSQL • • 17d ago

Can a LEFT JOIN Accidentally Behave Like an INNER JOIN Without Changing the JOIN Condition?

12 Upvotes

If we apply a WHERE condition on a column from the right-side table after a LEFT JOIN, can it eliminate NULL rows and change the result? Are there cases where moving the condition into the ON clause produces completely different results? Why does this happen internally?


r/learnSQL • • 17d ago

What are some interesting SQL problems or query mistakes worth discussing?

5 Upvotes

I'm planning to share some SQL-related content on LinkedIn, but I want to avoid the usual beginner-level tutorials or generic interview questions.

I'm particularly interested in intermediate-level SQL concepts, window functions, CTEs, tricky query behavior, or situations where a query looks correct but produces unexpected results.

I'd love to hear from people working with SQL regularly.

What's an interesting SQL problem, subtle query mistake, or unexpected behavior you've encountered that made you think twice?

Looking for something technically meaningful that could spark a good discussion rather than another basic SQL tutorial.


r/learnSQL • • 17d ago

What are some interesting SQL problems or query mistakes worth discussing?

Thumbnail reddit.com
3 Upvotes

r/learnSQL • • 18d ago

Superstore Dataset

5 Upvotes

🚀 Just published a new 3NF relational dataset on Kaggle!

I took the classic flat Superstore dataset and refactored it into a clean, normalized Third Normal Form (3NF) relational database structure.

By decomposing flat records into distinct dimension tables (dim_customers, dim_locations, dim_products) and header/line-item fact tables (fact_orders, fact_order_items), this schema eliminates data redundancy and enforces relational integrity.

Great for anyone looking to:

Practice multi-table SQL joins and data modeling

Build modular ETL ingestion pipelines

Stage realistic relational schemas for analytics projects

🔗 Check out the dataset on Kaggle: https://www.kaggle.com/datasets/kartikanidhi/superstore-database

#DataEngineering #SQL #DatabaseDesign #DataNormalization #Kaggle #OpenSource #Analytics


r/learnSQL • • 18d ago

Beginner in SQL, can’t work in person. How can I land remote projects?

13 Upvotes

Hi everyone,

I’m a beginner in SQL and I’m looking for ways to start earning remotely. In-person work isn’t an option for me, so I’m focusing on freelance or remote opportunities.


r/learnSQL • • 18d ago

MariaDB Foundation TAF: Profiling MariaDB Subsystems Across Hardware Using Targeted Performance Profiles

1 Upvotes

Just published a deep dive on how we profile MariaDB subsystems using TAF + HammerDB TPROC‑C.

Each profile flips exactly one switch (binlog, isolation, PFS, charset, threadpool, etc.) to measure subsystem cost cleanly and reproducibly across hardware.

If you’re interested in performance engineering or regression hunting, here’s the full article:

https://mariadb.org/mariadb-foundation-taf-profiling-mariadb-subsystems-across-hardware-using-targeted-performance-profiles/


r/learnSQL • • 19d ago

Title: Day 62-64 — Combined update: built and published a Car Rental System in Java (feedback welcome)

5 Upvotes

Over the last three days I built a console-based Car Rental System in Java, applying the OOP concepts from the past few weeks. Repo: https://github.com/Sumitgupta2005/Car_Rental_System

What it does:

  • Menu with three options: rent a car, return a car, exit
  • A Car class with private fields (ID, brand, model, base price per day, availability), a constructor, and getters
  • Asks for confirmation (Y/N) before completing a rental
  • Keeps the cars in a list and updates availability when a car is rented or returned

After the feedback I got here on my last project (don’t leave the errors for the end), I tried to test each part as I wrote it.

I’d appreciate a review of the code structure and README. What would you improve first: input validation, splitting into more classes, exception handling, or saving data to a file or database?


r/learnSQL • • 19d ago

I made SQL practice where you debug an AI's queries, and the hints never give you the answer

8 Upvotes

I'm learning-adjacent: I build tools for people learning SQL for analyst jobs, and this is mine, so it's self-promo. Mods, remove it if it doesn't fit.

What bugged me about practice sites is that a different toy table every time doesn't build the "I know this company's data" feeling you get at work. Practisheet uses one fictional company for everything, so by exercise 20 you know where revenue, refunds and late deliveries live.

How it works:

  • You write the query in the browser and it checks your result.
  • If it's wrong, you get a hint about your attempt (e.g. "you're counting order lines, not orders"). The answer is never shown, and after 3 tries you can skip.
  • It starts with SELECT/WHERE and goes up to window functions, CTEs and cohort-style questions.
  • About 1 in 4 exercises are "here's a query an AI wrote, find the bug", which I think is a skill people will need more and more.

The first 4 SQL exercises are free with no sign-up: https://practisheet.com/practice

Free guides that go with it, if you just want to read:

Feedback welcome, especially where you got stuck and the hint didn't help.


r/learnSQL • • 19d ago

[Showoff Saturday] I built a 100% client-side, in-browser SQLite editor using WebAssembly (No backend, offline-first)

2 Upvotes

I wanted to share a project I've been working on: sqliteWeb, a lightweight SQLite editor that runs entirely inside the browser. link online sqlite browser
I needed a fast way to inspect and query .sqlite / .db files on machines where I didn't want to (or couldn't) install desktop clients like DB Browser. Existing web tools often require uploading files to a remote server, which is a major privacy concern.

Would love to get your feedback on performance, UI responsiveness, or features you'd like to see added!

online sqlite browser


r/learnSQL • • 19d ago

How many ways can you find duplicate rows in a table?

4 Upvotes

I was cleaning a customers table and needed to find duplicate emails. I found a few different ways to do it,and now I’m curious how many more exist.

  1. GROUP BY with HAVING
    2.ROW_NUMBER()
    3.Self JOIN
    The first one is the simplest. The second one is great when you want to delete the extras and keep just one row.

What other ways do you know? Bonus points for creative ones!


r/learnSQL • • 19d ago

ID design and composite primary keys, pt. III

1 Upvotes

I've been writing a series of posts on ID design and primary keys, and just published the third part: https://anchorsandlinks.com/posts/primary-keys-3/. It discusses a well-known pattern of composite primary keys in entity tables. It is relatively rarely used, and the text explains why. This pattern can only be used when several criteria are satisfied, and it may become an obstacle when business requirements change. The rationale for using composite primary keys is that it can give performance improvements in some scenarios.


r/learnSQL • • 21d ago

Day 61 — Java OOP: access modifiers, encapsulation, and abstraction (all four pillars done)

11 Upvotes

Today I covered:

  • Access modifiers (public, private, protected, default), which control visibility
  • Encapsulation, meaning private fields with public getters and setters so data can only change in controlled ways
  • Abstraction, which hides implementation details behind abstract classes and interfaces

With inheritance and polymorphism from the last few days, that covers all four pillars of OOP. Encapsulation made the most sense once I connected it to access modifiers: the modifiers are the tool, and encapsulation is the reason to use them.

Tomorrow I’m starting a project that uses all four pillars. After the feedback I got here on my last one (don’t leave all the errors for the end), I’m going to test each feature right after I write it.

For people who’ve built beginner OOP projects: which one forced you to use all four pillars naturally? I’m choosing between a bank system, a hospital system, and an e-commerce cart.


r/learnSQL • • 21d ago

Python to SQL Analysis Project

7 Upvotes

Use Python to collect data from a public API and pipe it to a SQL Server for analysis. The whole process can be automated with Windows Task Scheduler. https://youtu.be/KAHD9LmvH6g?si=Ev1y_s11pBl2cUKE


r/learnSQL • • 21d ago

WHERE vs HAVING - same question, three queries, three different answers

7 Upvotes

the question: "which customers spent more than 60?"

table:

```
order_id | customer | status | amount
1 | Asha | completed | 40
2 | Asha | completed | 30
3 | Asha | refunded | 50
4 | Ben | completed | 20
5 | Ben | refunded | 90
6 | Chen | completed | 80
```

**query 1, HAVING only**

```
SELECT customer, SUM(amount) AS spent
FROM orders
GROUP BY customer
HAVING SUM(amount) > 60;
```

Asha 120, Ben 110, Chen 80. looks fine but refunds are counted as spending. Ben only really spent 20.

**query 2, WHERE on amount**

```
SELECT customer, SUM(amount) AS spent
FROM orders
WHERE amount > 60
GROUP BY customer;
```

Ben 90, Chen 80. this answers a different question: "who had a single order over 60". Asha is gone even though she spent 70 in total, and Ben is back because of his refund.

**query 3, WHERE + HAVING**

```
SELECT customer, SUM(amount) AS spent
FROM orders
WHERE status = 'completed'
GROUP BY customer
HAVING SUM(amount) > 60;
```

Asha 70, Chen 80. this is the right one.

the way i think about it:

- WHERE filters **rows**, before grouping. "which orders count?"
- HAVING filters **groups**, after grouping. "which customers make the cut?"

and you cant do `WHERE SUM(amount) > 60`, the database hasnt added anything up yet at that point so it errors.

anyone else have a go-to way of explaining this one?


r/learnSQL • • 22d ago

Performance Tuning Report: A 'weekly' report was running about 400 times a day. We checked what each execution was costing.

11 Upvotes

We’ve collected a lot of performance tuning reports from our SQL Server work. I thought some would be useful to share here so people get to see the problem, the change and the measurements afterward.

This one involved a retail client’s reporting query which grouped quantities by week.

The query ran about 400 times a day. Each execution averaged 87,038.42 milliseconds and 6,445,851 logical reads.

“Weekly” described the grouping in the output but the database repeated the calculation throughout the day.

Our team added a nonclustered index with two key columns and included the quantity column used in the calculation. We captured the before-and-after measurements with Query Store and supplied a rollback script to remove the index.

The recorded averages per execution were:

  • Duration: 87,038.42 ms → 2,528.44 ms
  • CPU time: 41,509.80 ms → 9,062.34 ms
  • Logical reads: 6,445,851 → 232,779

The query finished sooner, consumed less CPU time and read fewer pages.

The included column is worth discussing. When reviewing an aggregation query, check the values SQL Server needs to calculate the result alongside the columns used to locate and join rows.

An included column stores its value at the leaf level of a nonclustered index without becoming part of the index key. Where the index supplies every column needed for a table access, SQL Server has the option to satisfy the access without fetching additional columns from the base table. Microsoft covers the mechanics in its included-column documentation.

Here, the quantity being aggregated was included in the new index.

The report records the index definition and measured results. It doesn’t contain enough execution-plan detail to say which operators changed. What we have is a documented reduction in duration, CPU time and logical reads after adding the index.

The execution count puts those measurements into context.

Using 400 executions a day as the working estimate:

  • Before: 6,445,851 × 400 = 2,578,340,400 logical reads a day.
  • After: 232,779 × 400 = 93,111,600 logical reads a day.

Those daily totals are calculated from the per-execution averages and estimated execution count. Logical reads count page accesses, including pages already in memory. They aren’t physical disk-read counts.

For anyone investigating a similar query, I’d work through:

  • The predicates and joins used to find the rows.
  • The columns needed for the aggregation and returned results.
  • Whether an existing index supplies those columns.
  • The execution plan and Query Store measurements.
  • The proposed index’s storage and write overhead.

Then compare representative executions after deployment and keep a rollback ready.

This is why I wanted to share the report.

A routine-looking calculation was doing substantial work hundreds of times a day. Looking at the aggregation inputs alongside the index keys gave the team a specific change to test, and the measurements showed the result.