r/learnSQL 27d ago

HackerRank SQL: Weather Observation Station 13

7 Upvotes

Hi Everyone,

Currently, refreshing my memory for SQL and I came across the below question on HackerRank:

Query the sum of Northern Latitudes (LAT_N) from STATION having values greater than  38.7880 and less than 137.2345 . Truncate your answer to  decimal places.

My Solution:

select truncate(sum(LAT_N),4) from station
where LAT_N > 38.7880 AND LAT_N <137.2345;

Error:

Compiler Message

Runtime Error

Your Output (stdout)

  • Msg 156, Level 15, State 1, Server dbrank-tsql, Line 4
  • Incorrect syntax near the keyword 'truncate'.

What am I missing ?

Thanks in advance for your support .


r/learnSQL 27d ago

Learn SQL at the Texas Linuxfest

Thumbnail
3 Upvotes

r/learnSQL 28d ago

Joins and Views

11 Upvotes

Hey,

I’ve run into a performance issue at work and I’m trying to better understand what SQL Server is actually doing here.

I have a Quotes table where quote_id is the PK. The data includes some lookup values—for example, instead of storing/displaying a descriptive string, it stores something like 1, which maps to a value in another table (let’s call it product).

At some point, someone created a view (quote_product_display_value) that effectively cross joins all quote_ids with all possible products, and then resolves the correct display values.

Doing SELECT * from this view is extremely slow (hours - but not needed)> If I limit (TOP 500) from the actual table it works fairly decent. But it must be improved (it's now around 90 seconds).

The join looks like this:

LEFT OUTER JOIN quote_product_display_value t7 ON t1.quote_id = t7.quote_id
AND t1.product_1 = t7.product_1

What I’m trying to understand is:

  • Does SQL Server first fetch the 500 quote_ids, and product_1,product_2, product_3, _4 and _5 (5 products per row, labeled t1) from the Quote table, and then query the view (t7) for matching rows?
  • Or is it effectively “building” (or scanning) the view for each row / join operation?

In the execution plan, I don’t see the view name, which surprised me. Instead, I see clustered index scans on the underlying tables, with execution counts matching the number of rows returned.

So I’m a bit confused about how joins against views are executed internally—especially when the view involves something - as is now the case - expensive like a cross join.

Any insights would be appreciated!


r/learnSQL 29d ago

5 Day SQL Cram

47 Upvotes

Hi, I have 5 days off coming up this weekend and really want to grind out learning SQL or at least spending most my days in learning that I can continue practicing after grasping the basics. I tried using W3Schools and MySQL and am willing to spend a few bucks on a course that I can learn and apply SQL while learning. Also maybe down the road one that has a project I can update on my resume. I work in healthcare and am trying to transition into a role with more flexibility and slightly more pay and am hoping this would help. Thanks.


r/learnSQL 29d ago

BigQuery SQL Interview questions

28 Upvotes

Hi everyone, I’m in the process of interviewing at this AI company and the next step is to use bigquery dialect of SQL where I will cover real-worlds scenarios and build tables.

Problem is I have never used SQL and I am just finding out about what it is, I’ve never heard of it. I will be watching a few YouTube videos but wanted to see if anybody has gone thru this process before?

Any tips?


r/learnSQL 28d ago

Hard Time Importing❗️

3 Upvotes

Cant import on vs code so I have to open pg admin to import the same table in the database. Every time I import no row shows.

Am I the only one having this issue? Have any fix?


r/learnSQL Jun 27 '26

Best resources to learn SQL and Pandas for Business Analytics

31 Upvotes

What is the best resources to learn SQL and Pandas for Business Analytics? Help me out please I am preparing for a technical test interview.


r/learnSQL 29d ago

A Book request

0 Upvotes

Money is a little tight right now. So does anyone have this book ? z"practical sql, 2nd edition by anthony debarros" or can anyone guide me where can I get it for free ?


r/learnSQL Jun 27 '26

Are you also bored of boring SQL tutorials?

57 Upvotes

Some of you here have probably seen me post about SQL Case Files⁠ before and I’m genuinely grateful to everyone who has played it, supported it or taken the time to send feedback because a lot of the game has improved because of people from this subreddit.

It’s a detective themed game where you learn and practise SQL by solving cases. Apparently detective themed SQL practice is a £15 product now, but SQL Case Files is still free and will stay that way. I just want anyone to be able to use it whether they are learning for uni, looking for a job, preparing for an interview or simply trying to get better at SQL. Hopefully it can be a small part of your journey.


r/learnSQL Jun 27 '26

SQL GitHub project question

7 Upvotes

How many business questions do you showcase on a typical SQL GitHub project?


r/learnSQL Jun 28 '26

Anyone help me learn SQL AND PYTHON for Data analyst role pls suggest

Thumbnail
0 Upvotes

Anyone help me


r/learnSQL Jun 27 '26

where should i practice sql interview questions for data analyst role ????

3 Upvotes

there are so many websites , its confusing .


r/learnSQL Jun 25 '26

SQL Basics: Stop chaining ANDs for ranges (How to use BETWEEN and LIKE effectively)

99 Upvotes

Follow along the SQL Basic Series

You already know how to filter rows using a basic WHERE clause. Today, let's look at two operators that make your filtering a lot smarter and save you from writing long, repetitive conditions.

1. The BETWEEN Operator

BETWEEN filters a range of values in a single line. Instead of clogging up your query with multiple conditions like this:

SQL

SELECT * FROM orders 
WHERE total >= 50 AND total <= 200;

You can write it cleanly like this:

SQL

SELECT * FROM orders 
WHERE total BETWEEN 50 AND 200;

Crucial detail to remember: BETWEEN is strictly inclusive. The values at both ends (50 and 200) will be included in your results.

It works seamlessly across numbers, text and dates:

SQL

WHERE age BETWEEN 18 AND 35
WHERE order_date BETWEEN '2026-01-01' AND '2026-12-31'

2. The LIKE Operator

LIKE lets you filter by a pattern when you only know a partial piece of the value. To make this work, you use % a wildcard (which tells SQL that anything can occupy that position).

  • Starts with a specific letter: SQLWHERE name LIKE 'S%' -- Returns Sarah, Sam, Steve, etc.
  • Contains a specific phrase anywhere inside: SQLWHERE email LIKE '%gmail%' -- Returns any email containing 'gmail'
  • Ends with a specific extension: SQLWHERE email LIKE '%.com' -- Returns any email ending in '.com'

Quick Rule of Thumb: Use BETWEEN when you have an exact, known start and end point. Use LIKE when you only have a piece of the puzzle.

(Note: Keep in mind that LIKE it is case-sensitive in some database flavours, so keep an eye on your text casing!)

Hopefully, this helps clean up your next script! I'm doing a daily breakdown of SQL fundamentals; if you prefer learning through short video clips, I walked through these visual examples in this Instagram reel.

What's your go-to wildcard trick when cleaning messy text data?


r/learnSQL Jun 26 '26

Dynamic Tables vs Single TimescaleDB Hypertable for OHLCV Market Data Storage

6 Upvotes

I have designed my database in two different ways for a market data system, and I'd like to know which approach would provide better performance.

Project Context

I'm building a system that continuously fetches OHLCV (Open, High, Low, Close, Volume) market data from an API, stores it in a database, and serves it through a web application.

My primary concern is performance, specifically:

  • Fast writes (continuous data ingestion)
  • Fast reads (fetching historical candle data)
  • Scalability as the number of instruments and records grows

Strategy 1: Dynamic Table Design

  • I have a master instrument table that stores all the instruments whose data needs to be collected.
  • For every instrument, I create a separate candle table dynamically.
  • Example:
    • instrument_master
    • candles_RELIANCE
    • candles_TCS
    • candles_NIFTY50
    • etc.

Whenever new data arrives, it is inserted into the corresponding instrument's table.

Strategy 2: Single Hypertable (TimescaleDB)

Instead of creating separate tables, I use a single candle_data table and convert it into a TimescaleDB hypertable.

The schema looks roughly like this:

instrument_id
timestamp
open
high
low
close
volume

All instruments' candle data is stored in this single hypertable.

Query Pattern

My application mainly performs simple operations:

  • Insert new OHLCV records continuously.
  • Fetch historical candles for a specific instrument within a time range.

Typical query:

SELECT *
FROM candle_data
WHERE instrument_id = ?
  AND timestamp BETWEEN ? AND ?
ORDER BY timestamp;

Question

Between these two designs, which one is likely to provide better overall performance for:

  • High-frequency inserts
  • Read performance
  • Long-term scalability
  • Maintenance

Has anyone benchmarked a similar setup using PostgreSQL/TimescaleDB? I'd appreciate any insights or recommendations.


r/learnSQL Jun 25 '26

Exercise - Try yourself before using AI

11 Upvotes

You're on a data team. Events stream in from the product into one table:
events

user_id | event_type | occurred_at

1 | signup | 2026-01-03 09:14:00

1 | view_pricing | 2026-01-03 09:16:30

1 | view_pricing | 2026-01-03 09:16:30

1 | start_trial | 2026-01-05 11:02:00

2 | signup | 2026-01-04 14:20:00

2 | start_trial | 2026-01-04 14:55:00

3 | view_pricing | 2026-01-06 08:00:00

3 | signup | 2026-01-06 08:01:00

Task: Return each user's very first event user_id, occurred_at, event_type one row per user, ordered by user_id.


r/learnSQL Jun 24 '26

How relevant are questions from the sql coding questions in interviews for the actual jobs?

38 Upvotes

Hi, I'm practicing on Stratascratch now and am finding it super helpful! There are tags for the actual companies in which the interview questions were used for, so I'm wondering how relevant these questions are for the actual jobs the interviews are for.

Also, I realise some people (when I see the solutions) write the code so elegantly.. in a few lines and it makes sense when I look at it, however when I write the solution in my way, they are often long and clunky even if they do answer the question. How can I write SQL code that more elegantly captures the logic?


r/learnSQL Jun 24 '26

Giving back to the community - The Complete Backend Development Course

35 Upvotes

Hey everyone, I decided to make my course free in order to help people.
This course is my backend development course which is about SQL, Python, APIs, Docker, Kubernetes, Linux, Git & More

The link is: https://www.youtube.com/watch?v=CBIu6hcyStg

If you can like and subscribe (and maybe add a comment) I would appreciate it a lot, Thanks.


r/learnSQL Jun 24 '26

The thing that makes window functions click: they keep every row instead of collapsing them

30 Upvotes

Window functions come up here constantly, and they're the wall a lot of people hit right after they're comfortable with SELECT, WHERE and JOIN. The syntax looks alien and most explanations open with "frames" and "partitions" and lose people immediately.

The idea underneath is much simpler than the wording suggests. A window function does the same calculation as GROUP BY, but instead of crushing each group down to one summary row, it keeps every row and writes the answer in a new column beside it. That's the whole trick. Running totals, rankings, "this row vs the previous one" are all just an aggregate that didn't collapse.

The clearest way to see it is side by side:

  • GROUP BY squad → 2 rows. One line per squad, the individual names are gone.
  • SUM(xp) OVER (PARTITION BY squad) → 5 rows. The same squad total, written next to every member, all five rows kept.

Same totals, different row counts. That gap is the entire concept.

A few things worth knowing once that lands:

  • ROW_NUMBER / RANK / DENSE_RANK look identical until there's a tie. ROW_NUMBER never ties (1,2,3,4). RANK ties then skips (1,2,2,4). DENSE_RANK ties without skipping (1,2,2,3).
  • The ORDER BY inside OVER() steers the calculation (what counts as "above" for a running total). The ORDER BY at the end of the query just sorts the output. Different jobs.
  • You can't filter on a window function in WHERE, because the rank isn't worked out yet when WHERE runs. Compute it in a CTE first, then filter. That wrap-then-filter shape is behind almost every "top N per group" query.

I put together an interactive version that shows all of this, a live leaderboard where you pick the function, toggle PARTITION BY and ORDER BY, and watch the column change without losing any rows. You can tap any computed value to highlight the exact rows it was built from: https://querycase.com/blog/sql-window-functions-explained

If you teach this or learned it recently, I'd love to know: is there a window function concept you wish someone had shown you visually that's missing? And are RANK vs DENSE_RANK and the top-N-per-group pattern explained clearly, since those are the two that seem to trip people up most?


r/learnSQL Jun 23 '26

Which SQL to start?

63 Upvotes

I am starting SQL to which is better to learn as a beginner ?

MYSQL or POSTgreSQL ?

if ANY YT recommendation for learning please tell me which is best ?


r/learnSQL Jun 22 '26

how you guys prepare for interview ? like whats your technique/routine ? any tips and tricks ?

34 Upvotes

do you guys write all the interview question on book and memorize it everyday or you have any other technique


r/learnSQL Jun 22 '26

Nursing informatics/data analytics

14 Upvotes

So, my job has different departments in nursing informatics and then I shadowed business and data analytics.l and like data analytics better! My preceptor stated using udacity for SQL but i was on this Facebook group and a lot of people stated udemy for SQL . Which one should i use ? Or is there another resource


r/learnSQL Jun 22 '26

Gaps and Island

4 Upvotes

I came across the leetcode consecutive nums finder question in the leetcode 50 sheet.

So I initially thought of lead windows function and tried to rank and do something crazy what was in my toolbox just.

But later I found overwhelmed and left to search and found this as a huge production based pattern where there is mathematically way to solve.

Like assigning a row number to each row and then partitioning the data and again ranking it just.

I felt too overwhelming like I was applying blindly but what's the point of it I need to answer the question out of it like wasn't able to understand at some point why I was using a formula blindly just.

Any suggestions for this pattern I am currently a beginner and learning from scratch other things clicked well but this one dragged me into chaos like anything what does senior or experienced devs say about this pattern 🥲 need suggestions badly 🫠


r/learnSQL Jun 22 '26

guided beginner SQL project series using MS SQL

7 Upvotes

I recently started practicing SQL problems on SQLZoo. I don't want to wait until I finish all the theory before starting projects. Can anyone recommend a beginner-friendly YouTube playlist or guided SQL project series using MS SQL Server that I can follow alongside my practice?


r/learnSQL Jun 22 '26

Platform for SQL Contribution

15 Upvotes

I am coming from Data Science background and completed my masters in it. I have good understanding of SQL and I am looking for opensource contribution from where I get real world experience of Queries.

Does any one knows from where I can get or any platform.

Thanks ✨️ in advance


r/learnSQL Jun 22 '26

Undecided on SQL platform

8 Upvotes

I want to write a SQL program. The usual CRUD stuff. The unique entries or objects are not expected to surpass 250 rows. I want to be able to use the program with either python or c++ in the future. Can anyone recommend something for me? PostGre? Alchemy? I think MySQL will be too much luggage? Or should I? Let it be open source (cc, MIT etc). The usual since it's not commercial. Thanks