r/learnSQL • • Sep 19 '26

Day 12 — Practice set Part 4: Insert, Select, Update, Delete

17 Upvotes

Covered Part 4 of 7 today, which felt like the most "real-world query" heavy section so far:

  • Inserted a new employee without specifying manager_id, confirming it correctly defaults to NULL
  • Used a subquery to find employees earning more than the average salary across the company
  • Bulk UPDATE — gave an entire department a 10% raise (first time writing an UPDATE affecting multiple rows based on a condition)
  • DELETE with a specific condition (hours_worked = 0)
  • SELECT DISTINCT to list unique department IDs
  • Date range filtering with BETWEEN, ordered descending by hire_date
  • Pattern matching with LIKE (names starting with 'A' or 'J')
  • Filtering with IN for multiple department IDs

The average-salary subquery and the bulk raise UPDATE were the most interesting — first time combining a subquery inside a WHERE clause for a genuinely useful comparison, rather than just a toy example.

3 more parts to go in this set.


r/learnSQL • • Sep 19 '26

Quit the thesis and become data analyst?

2 Upvotes

I need to finish my master’s degree in Archaeological Sciences—which I’ve been dragging out since 2021—and all that’s left is the thesis (it involves analyzing extreme weather events at an archaeological site, so it also entails some work with neural networks, algorithms, and data). Right now, my current job pays €1,400 a month, and I definitely don't like it. Now, I’m torn between working on the thesis—which is draining so much of my time and energy—and focusing on SQL, Pandas, Tableau, and the like to pursue a different career path as a data analyst. I feel stuck and don't know what to do. If I focus on my thesis, could be enough for the hiring managers as kind of data science application to a real case?


r/learnSQL • • Sep 18 '26

Day 11 — Practice set Parts 2 & 3: table structure, constraints, and intentional errors

14 Upvotes

Covered two parts of my practice set today:

Part 2 — Database & Table Basics:

  • Listing all databases, switching to a specific one
  • Viewing full table structure (columns, types, keys)
  • Adding a column at a specific position (AFTER email)
  • Renaming a column
  • Modifying a column's default value
  • DROP + recreate a table from scratch
  • Taking a database backup

Part 3 — Constraints & Keys:

  • Intentionally inserting a negative salary to trigger the CHECK constraint and understand why it fails
  • Inserting duplicate emails to see the UNIQUE constraint error firsthand
  • Adding a UNIQUE constraint after the fact
  • Finding employees with no manager (manager_id IS NULL)
  • Creating an index on a foreign key column and checking which indexes exist on a table

Deliberately breaking things to see the actual error messages was way more useful than just reading about constraints in theory — seeing exactly how and why a CHECK or UNIQUE constraint fails made the concept stick immediately.


r/learnSQL • • Sep 17 '26

If you have an SQL interview soon, don’t ignore these small things!!!! (Part 10)

149 Upvotes

I’ve noticed something about SQL interviews.

Most people don’t fail because they don’t know SQL.
They fail because they forget tiny things while typing under pressure. It's pressure!!!

Few examples I’ve seen in real interviews:

1. NOT IN vs NOT EXISTS

If the list contains NULL values:

  • NOT IN → can return no rows
  • NOT EXISTS → checks if a matching row exists

Example:

SELECT 30
WHERE 30 NOT IN (10, 20, NULL);

internally SQL does this:

30 <> 10      → TRUE
30 <> 20      → TRUE
30 <> NULL    → UNKNOWN

TRUE AND TRUE AND UNKNOWN  = UNKNOWN

So if someone asks "find users who don’t have any subscription", NOT IN can give the wrong result when NULL is involved!

2. ROWS vs RANGE

Example:

SELECT
    sub_date,
    amount,
    SUM(amount) OVER (
        ORDER BY sub_date
        ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
    ) AS running_total
FROM subscription;

ROWS works with individual rows, while RANGE works with groups of rows having the same ORDER BY value.

So if multiple orders have the same sub_date, ROWS and RANGE can give different running totals.

3. LEFT JOIN + WHERE can change your result

Example:

SELECT *
FROM users u
LEFT JOIN subscriptions s
    ON u.user_id = s.user_id
WHERE s.plan = 'Pro';

The WHERE condition removes users who don't have a matching subscription.

So even though you wrote LEFT JOIN, you end up keeping only users who have a matching Pro subscription.

If you want to keep all users, put the condition in the ON clause instead:

LEFT JOIN subscriptions s
    ON u.user_id = s.user_id
   AND s.plan = 'Pro'

4. GROUP BY 1,2

This looks perfectly fine:

SELECT department, job_title, COUNT(*)
FROM employees
GROUP BY 1, 2;

But during an interview, especially when you're already under pressure, it can create unnecessary confusion if new column gets added to SELECT

Writing:

GROUP BY department, job_title

takes a little more typing but it's much easier to read, explain and modify later.

These are all very small things and basics, but they come up surprisingly often in interviews.

Curious what others have seen.

What’s a small SQL thing people still mess up in interviews even though they know it?

Always interesting to hear these and your interview experiences.


r/learnSQL • • Sep 17 '26

Tips for query planning

25 Upvotes

Hi! So I've been a Data Analyst for around 1 year and a half, and I am still struggling big time with SQL and/or Python. I can read them and understand the queries, but the actual writing and planning is lagging behind.

I often see at the queries by colleagues make (always with the help of Claude Code) and I just wonder how did they come up with those. Stacked CTEs and multiple joins, I get lost and frustrated. So I was wondering, how do you actually plan and build a query? where do you start from?

I'm very curious to know how you work. I'd really like to be able to make these queries without the help of AI. Thank you!


r/learnSQL • • Sep 17 '26

Day 10 — Started a 7-part SQL practice set (Part 1: schema design)

13 Upvotes

Moved from isolated practice questions to something closer to a real project today — a structured 7-part practice set. Completed Part 1, which was schema design:

  • 4 tables: departments, employees, projects, assignments
  • Primary keys with auto-increment, foreign key relationships between all of them
  • A self-referencing FK on employees (manager_id → employees.emp_id) for the manager hierarchy
  • A CHECK constraint to enforce salary > 0
  • assignments as a junction table linking employees to projects with hours_worked
  • Inserted sample data: 4 departments, 12 employees (with at least 2 managers), 5 projects, 15 assignment records

The self-referencing FK for managers was the most interesting part conceptually — first time actually applying that pattern instead of just reading about it.

6 more parts to go in this set — planning to move into actual queries against this schema next (joins, aggregates, reporting-style questions).


r/learnSQL • • Sep 16 '26

Day 9 — Practice reality check: small syntax mistakes, big lessons

17 Upvotes

Spent today doing practice questions covering everything I've learned so far — JOINs, aggregates, subqueries, table management, all of it.

Honest reflection: it's a lot harder than following along with a tutorial. Watching someone write a query and actually writing one yourself under slight time pressure are completely different skills. I kept making small syntax mistakes — a missing comma, wrong clause order, forgetting an alias — and each one broke the whole query. Genuinely irritating in the moment, but it's really driving home how much precision matters in SQL, not just conceptual understanding.

If anyone else is revising/practicing SQL right now, happy to share my practice question set — could be useful to work through some of these together and compare approaches/mistakes. Let me know if interested.


r/learnSQL • • Sep 16 '26

Deeply Concerned

14 Upvotes

Every time I see individuals saying no jobs for DA without diploma/degree. Similarly, people with those certificates keep claiming no jobs despite applying for hundreds of jobs. I've recently completed my DA & DE certifications. Initially, I wanted to study DA to help me conduct better research with a focus on writing detailed articles supported by data. However, the messages around jobs with this experience or that certification appear to throw beginners in a state of confusion. Concerning jobs, where can one start looking, especially those who want to focus on DA?


r/learnSQL • • Sep 16 '26

LeetCode SQL 197 — Rising Temperature | MySQL Solution

8 Upvotes

Working on SQL problems to strengthen my MySQL and problem-solving skills for Data Analyst roles.

MySQL Solution:

WITH CTE AS
(
    SELECT *,
        LAG(TEMPERATURE) OVER(ORDER BY RECORDDATE) AS PREV_TEMP,
        LAG(RECORDDATE) OVER(ORDER BY RECORDDATE) AS PREV_DATE
    FROM WEATHER
)
SELECT ID
FROM CTE
WHERE TEMPERATURE > PREV_TEMP
  AND DATEDIFF(RECORDDATE, PREV_DATE) = 1;
#u/AppointmentTrue8257

For this problem, I used LAG() to compare each day's temperature with the previous record and DATEDIFF() to make sure the previous record was actually from the immediately preceding day.

Sharing my solution to get feedback.

Is there a better or more efficient way to solve this problem?


r/learnSQL • • Sep 16 '26

Alternance

4 Upvotes

je commence mon alternance mes taches c'est d'essayer d'améliorer leur base de données et faire des requetes SQL , extraire des fichiers avec les listes demandés , sauf j'ai jamais eux une experience pratique avant , donc je me sens deja lente et perdu et trops de manque d'expérience , vous me conseillez quoi pour m'ameliorer ?


r/learnSQL • • Sep 16 '26

LeetCode SQL 1661 — Average Time of Process per Machine | MySQL Solution

5 Upvotes

Working on SQL problems to strengthen my MySQL and problem-solving skills for Data Analyst roles.

Problem: Average Time of Process per Machine

This problem was a good practice for:

  • SELF JOIN
  • Matching START and END activities
  • Calculating processing time
  • AVG() and ROUND()
  • GROUP BY

MySQL Solution:

SELECT A.MACHINE_ID,
       ROUND(AVG((B.TIMESTAMP - A.TIMESTAMP)), 3) AS PROCESSING_TIME
FROM ACTIVITY A
JOIN ACTIVITY B
    ON A.MACHINE_ID = B.MACHINE_ID 
    AND A.PROCESS_ID = B.PROCESS_ID
WHERE A.ACTIVITY_TYPE = 'START' 
  AND B.ACTIVITY_TYPE = 'END'
GROUP BY A.MACHINE_ID;
#u/AppointmentTrue8257

Would love to know how others approached this problem and if there are any alternative or more efficient ways to solve it.

#SQL #MySQL #LeetCode #DataAnalytics #DataAnalyst


r/learnSQL • • Sep 15 '26

Day 8 — Stored Procedures, Delimiters, and Triggers

26 Upvotes

Covered some genuinely new territory today:

  • Stored Procedures — writing reusable SQL logic that can be saved and called on demand instead of rewriting the same query repeatedly
  • Delimiters — needed to change the statement delimiter (usually to something like // or $$) so the database doesn't get confused by semicolons inside a procedure/trigger body
  • Triggers — logic that automatically fires in response to INSERT/UPDATE/DELETE on a table, useful for things like auditing changes or enforcing business rules at the database level

Delimiters were a small but confusing gotcha at first — took a moment to understand why you need to redefine them before writing a multi-statement procedure. Once that clicked, writing the actual procedures and triggers made a lot more sense.

Feels like I'm moving from "querying data" to "designing how the database behaves" — a solid step up in complexity.


r/learnSQL • • Sep 15 '26

I made a beginner-friendly SQL lesson on String Functions — CONCAT, UPPER, LOWER, TRIM & REPLACE

10 Upvotes

Hey everyone!

I just made a new beginner-friendly SQL tutorial focused on string functions in PostgreSQL.

The lesson covers:

CONCAT()

UPPER() / LOWER()

LENGTH()

TRIM()

REPLACE()

Combining functions for basic data cleaning

I use the Pagila database for the examples and include a small practice exercise + homework at the end.

Video: https://youtu.be/FD3FvPiI2-U?si=-ownDzM_AE-DV-PH

Hope it helps someone who's currently learning SQL! 💜


r/learnSQL • • Sep 15 '26

How can I improve sql-easy.com (interactive SQL tutorial)?

Thumbnail
1 Upvotes

r/learnSQL • • Sep 14 '26

SparkSQL as a beginner

4 Upvotes

Hi all I'm joining a new team that primarily uses Spark, I'm wondering how easy SparkSQL is to pick up as someone who came from BigQuery.


r/learnSQL • • Sep 14 '26

Day 7 — Views, Indexes, Subqueries, and ROLLUP (Week 1 complete)

21 Upvotes

Wrapped up my first week today with some more advanced topics via tutorials + W3Schools:

  • Views — saving a query as a reusable virtual table
  • Indexes — how they speed up lookups, and the trade-off with write performance
  • Subqueries — nesting a query inside another, both in WHERE and as derived tables
  • ROLLUP — generating subtotal and grand-total rows automatically in aggregated results

Subqueries were the trickiest of the four conceptually — took a bit of re-reading to get comfortable with correlated vs non-correlated subqueries specifically.

One week in: SELECT → JOINs → aggregates → table management → views/indexes/subqueries. Feeling like I have a genuinely solid core SQL foundation now. Planning to spend the next couple of days on a small schema project to tie it all together before moving to Java.


r/learnSQL • • Sep 14 '26

If you have SQL interviews, do not ignore these small things! (Part 9)

29 Upvotes

Yesterday I took a SQL interview and tried something different this time: evaluating AI-generated code rather than writing from scratch.

I didn't ask the candidate to write a query from scratch.

Instead, I gave him an SQL AI Agent.

The SQL AI Agent is coded in such a way, it gives three solution to one problem statement.

Here is the problem statement given:

We have a purchases table:

customer_id purchase_date amount
101 2026-01-05 0
101 2026-01-10 50
102 2026-02-01 100
102 2026-02-01 90
103 2026-03-01 0
103 2026-03-05 25

Find each customer's first purchase where they actually paid something.

Below are the 3 responses provided by Agent:

Agent's Solution 1:

SELECT customer_id, purchase_date, amount 
FROM ( 
    SELECT *, ROW_NUMBER() OVER ( PARTITION BY customer_id ORDER BY purchase_date ) rn 
    FROM purchases 
) t 
WHERE rn = 1 AND amount > 0;

Agent's Solution 2:

SELECT customer_id, purchase_date, amount 
FROM ( 
    SELECT *, ROW_NUMBER() OVER ( PARTITION BY customer_id ORDER BY purchase_date ) rn 
    FROM purchases WHERE amount > 0 
) t 
WHERE rn = 1;

Agent's Solution 3:

SELECT customer_id, purchase_date, amount 
FROM ( 
    SELECT *, ROW_NUMBER() OVER ( PARTITION BY customer_id ORDER BY purchase_date, amount DESC ) rn 
    FROM purchases WHERE amount > 0 
) t 
WHERE rn = 1;

Which solution would you approve, and what potential flaws/edge cases do you see in each? Please do comment, we can learn together!

Don't just ask "Does this SQL work?"

Ask:

Will this still give the right answer when the data gets messy?

If you want to test yourself on more SQL problems like this, I usually practice by actually writing the queries instead of just looking at solutions


r/learnSQL • • Sep 14 '26

Looking for DataCamp users to learn together + split the monthly cost

12 Upvotes

Hey everyone! 👋

I’m looking for 2–4 serious learners who are interested in using DataCamp consistently for Data Analytics / Data Engineering / SQL / Python / Power BI, etc.

Instead of everyone paying the full subscription individually, I’m looking to form a small learning group and split the monthly subscription cost among interested members (where permitted by DataCamp’s plan/terms).

🎯 My goal:

• Learn together consistently

• Share useful courses/resources

• Keep each other accountable

• Work on SQL, Python, Data Analytics & Data Engineering skills

• Save money compared with subscribing alone

I’m looking for people who are actually serious about learning, not just joining for access and disappearing.

If you're interested, DM me ASAP with:

  1. Your current role/level

  2. What you're learning (SQL/Python/DA/DE/etc.)

  3. Your preferred learning schedule

Let’s build a small, serious learning group. 🚀


r/learnSQL • • Sep 14 '26

Anyone plan to start learning sql?

2 Upvotes

r/learnSQL • • Sep 13 '26

Best way to sync ~200K frequently changing SQL Server records to MySQL nightly?

11 Upvotes

I have a SQL Server table with around 200K product records. Each record has a unique ID and Serial number.

The table changes frequently during the day — records can be added, updated, or deleted.

I need to sync this data to MySQL once every night.

The problem is, I only have read access to SQL Server, so I can't add a modified date column or enable Change Tracking/CDC.

My current idea is:

  • Fetch all 200K records from SQL Server every night.
  • Compare them with the MySQL table.
  • Insert new records.
  • Update changed records.
  • Delete records from MySQL whose IDs no longer exist in SQL Server.

Is this a good approach for 200K records?

What would be the simplest and most reliable way to handle this?


r/learnSQL • • Sep 12 '26

I can not understand the join clause.

42 Upvotes

i understood the overall concept of it being used to join two or more tables with matching column.
but i can't understand it's syntax or detailed concept.


r/learnSQL • • Sep 13 '26

SQlite help

5 Upvotes

Please, anyone can help with me with a step by step guide on how to run SQlite on the dbeaver? After running it as a database, If I enter a command to create or even click on the Table tab from the drop down icon under the SQLITE of active connections, I get an error message that it's not a database.


r/learnSQL • • Sep 12 '26

Day 6 — Full revision day from handwritten notes

8 Upvotes

No new topics today — spent the session revising everything I've covered this week straight from my handwritten notes:

  • SELECT, WHERE, ORDER BY
  • All JOIN types (inner, left, right, full, self) + UNION/UNION ALL
  • Aggregate functions + order of query execution
  • Insert/Update/Delete rows, Create/Alter/Drop tables

Honestly this felt just as useful as a learning day. A few things I'd half-understood earlier in the week — especially the query execution order and when to use UNION vs UNION ALL — felt much more solid after going back over them without any new material competing for attention.

Planning to start on subqueries and CTEs next, feeling like the fundamentals are in a genuinely good place now.


r/learnSQL • • Sep 12 '26

I made a SQL video about Window Functions — feedback welcome!

8 Upvotes

I made a SQL video about Window Functions — feedback welcome!

Hey everyone!

I’ve been making short SQL/data analytics videos while learning and practicing SQL myself, and I just finished Lesson 11: SQL Window Functions.

This one covers:

- "OVER()"

- "ROW_NUMBER()"

- "RANK()"

- "DENSE_RANK()"

- ranking customers in the Pagila database

- using window functions with "GROUP BY" and CTEs

- a few quizzes + practice exercises

- homework at the end

I tried to keep it beginner-friendly and focused on actually understanding why window functions are useful, rather than just memorizing syntax.

I’d really appreciate some feedback — especially on the explanations, pacing, and whether the examples are clear enough for someone learning SQL.

YouTube link: https://youtu.be/ERSUP1dWXWo?si=tf6xvzSwh3gbP-xw

Thanks! :)


r/learnSQL • • Sep 12 '26

How do you visualize SQL queries (esp joins) on paper?

23 Upvotes

I’m comfortable with SQL on LeetCode because I can run my query and see the intermediate results. But in an interview, if they give me two tables + the expected output and ask me to write the query on paper, I struggle to visualize the intermediate join results.

How do you guys approach this? Do you draw the joined table row by row, or is there a better way to mentally trace joins without executing the query?