🚀 Another SQL problem solved — and this one was a great exercise in aggregation + date handling! **Problem:** For each user, find the number of days between their first and last post in 2021 — but only include users who posted at least twice. **My Approach:** * Filter data for the year 2021 * Group by `user_id` * Use `MIN()` and `MAX()` to get first & last post dates * Subtract dates to get the duration * Use `HAVING` to ensure at least 2 posts **Final Query (PostgreSQL):** SELECT user_id, MAX(post_date)::date - MIN(post_date)::date AS days_between FROM posts WHERE EXTRACT(YEAR FROM post_date) = 2021 GROUP BY user_id HAVING COUNT(*) >= 2; **Key Learnings 💡** * `MAX(date) - MIN(date)` is a clean way to compute activity span * `HAVING` is essential when filtering aggregated results * Type casting (`::date`) ensures correct subtraction behavior * Always think: filter → group → aggregate → filter again Shoutout to Nick Singh 📕🐒 for creating and sharing such practical SQL problems 🙌 #SQL #PostgreSQL #DataAnalytics #BackendDevelopment #DataEngineering #InterviewPrep
SQL Query to Calculate Days Between First and Last Post in 2021
More Relevant Posts
-
𝗙𝗜𝗟𝗧𝗘𝗥 𝗰𝗹𝗮𝘂𝘀𝗲 — 𝗰𝗹𝗲𝗮𝗻𝗲𝗿 𝗰𝗼𝗻𝗱𝗶𝘁𝗶𝗼𝗻𝗮𝗹 𝗮𝗴𝗴𝗿𝗲𝗴𝗮𝘁𝗶𝗼𝗻 CASE WHEN inside aggregations is everywhere. But there's a cleaner way in modern SQL. The 𝗙𝗜𝗟𝗧𝗘𝗥 clause. Old way: SELECT SUM(CASE WHEN status = 'paid' THEN amount END) AS paid, SUM(CASE WHEN status = 'pending' THEN amount END) AS pending FROM orders; New way with FILTER: SELECT SUM(amount) FILTER (WHERE status = 'paid') AS paid, SUM(amount) FILTER (WHERE status = 'pending') AS pending FROM orders; Same result. Much cleaner. Works with COUNT, AVG, MIN, MAX — any aggregate function. The best SQL isn't always the most complex — sometimes it's just more readable. Have you used FILTER before? #SQL #DataAnalysis #PostgreSQL #DataEngineering #Analytics
To view or add a comment, sign in
-
Here are some Essential SQL Tips for Beginners 👇👇 ◆ Primary Key = Unique Key + Not Null constraint ◆ To perform case insensitive search use UPPER() function ex. UPPER(customer_name) LIKE 'A%A' ◆ LIKE operator is for string data type ◆ COUNT(*), COUNT(1), COUNT(0) — all return the same result ◆ All aggregate functions ignore NULL values ◆ SUM and AVG work on numeric data types. MIN, MAX work on numeric, string & date types. STRING_AGG is for string data type ◆ For row level filtration use WHERE; for aggregate level filtration use HAVING ◆ UNION ALL includes duplicates; UNION excludes them ◆ If no duplicates are expected, prefer UNION ALL — it's faster! ◆ Always alias a subquery when using its columns in the outer SELECT ◆ Subqueries can be used with NOT IN condition ◆ CTEs are more readable than subqueries — performance wise both are similar ◆ Joining two tables where one has only one row? Use 1=1 as condition — that's a CROSS JOIN ◆ Window functions work at ROW level ◆ RANK() skips ranks for ties; DENSE_RANK() does not ◆ EXISTS works on true/false conditions — if the query returns at least one row, condition is TRUE and all matching records are returned 💾 Save this for your next SQL interview! ♻️ Repost to help others learn SQL faster! #SQL #SQLTips #DataAnalytics #DataAnalyst #LearnSQL #SQLForBeginners #DatabaseManagement #SQLQuery #DataEngineering #Analytics #TechEducation #DataScience #SQLServer #MySQL #PostgreSQL #CareerGrowth #LinkedInLearning #DataProfessionals #TechSkills #CodingTips
To view or add a comment, sign in
-
-
You write SQL from top to bottom. Your database reads it in a completely different order. 🧠🔍 Ever wondered why you can't use an alias you created in a SELECT statement inside your WHERE clause? Or why HAVING feels like a second WHERE? It’s because of the Logical Order of Execution. If you want to debug like a pro and stop guessing why your queries are failing, you need to memorize this "Cheat Code." 📜 The SQL Execution Cheat Sheet: Think of your query like a filter. It doesn't start at the top; it starts with the Source. FROM / JOIN: "Where is the data coming from?" (The database grabs the tables first). WHERE: "Which rows do I need?" (It filters the raw data). GROUP BY: "How should I bucket them?" (It organizes rows into groups). HAVING: "Which groups do I keep?" (It filters the groups, NOT the rows). SELECT: "What columns do I show?" (Finally! This is where aliases are born). DISTINCT: "Any duplicates?" (It cleans the final view). ORDER BY: "How should it look?" (The very last thing—sorting). TOP / LIMIT: "How many should I send back?" #SQL #DataEngineering #CodingTips #MsSQL #Database #CareerAdvice #TechHacks #SanthoshS
To view or add a comment, sign in
-
-
🧠 SQL Functions — The Complete Cheat Sheet Every Analyst Needs! SQL isn't just SELECT and WHERE. The real power lies in its built-in functions. 👇 1️⃣ Aggregate Functions Summarize your data in one line → COUNT() · SUM() · AVG() · MAX() · MIN() 2️⃣ String Functions Clean, format & transform text → UPPER() · LOWER() · CONCAT() · SUBSTRING() · LENGTH() 3️⃣ Date Functions (MySQL Syntax) Work with time like a pro → NOW() · DATE_ADD() · DATEDIFF() · YEAR/MONTH/DAY 4️⃣ Mathematical Functions Precise calculations, zero effort → ROUND() · CEIL() · FLOOR() · ABS() 5️⃣ Conditional Functions Add logic directly into your queries → COALESCE() · CASE WHEN 🎯 Use these functions to: ✅ Summarize data ✅ Format & clean strings ✅ Handle NULLs gracefully ✅ Calculate time differences ✅ Add if/else logic in queries 💡 Master these 20 functions and you can handle 80% of real-world SQL problems. Save this post 🔖 — your future self will thank you! ♻️ Repost to help someone learning SQL today! #SQL #SQLFunctions #DataAnalytics #DataAnalyst #LearnSQL #SQLTips #DatabaseManagement #SQLInterview #DataEngineering #Analytics #TechLearning #SQLForBeginners #DataScience #CaseWhen #StringFunctions #DateFunctions #ShankarMaheshwari #UpskillDaily #DataCommunity #CareerGrowth
To view or add a comment, sign in
-
-
🗄️ Wrote a complete SQL Mastery Guide — here's what's inside. 14 chapters, 127+ exercises, 75+ functions. Zero to advanced, MySQL 8.0+. The one concept I made sure to nail in this guide: SQL doesn't run in the order you write it. FROM → JOIN → WHERE → GROUP BY → HAVING → SELECT → Window Functions → DISTINCT → ORDER BY → LIMIT That's why this fails: SELECT price * 0.9 AS discounted WHERE discounted < 100 And this works: WHERE price * 0.9 < 100 WHERE runs at step 3. Your alias is born at step 6. Simple as that. Also covered — NULL behaviour in JOINs, Window Functions vs GROUP BY, Recursive CTEs, and query optimization basics. Who this is for: Anyone prepping for interviews, working with data daily, or moving from basic queries to production-level SQL. #SQL #MySQL #DataAnalytics #LearningInPublic #DataEngineering
To view or add a comment, sign in
-
Why NOT EXISTS is faster than LEFT JOIN (in many cases) Both queries solve the same problem: Find records that don’t have a match But internally, they behave very differently. LEFT JOIN: • Joins entire tables • Creates intermediate result • Then filters NULLs NOT EXISTS: • Checks row by row • Stops at first match • Avoids unnecessary scans LEFT JOIN = “process everything, then filter” NOT EXISTS = “check and skip early” That’s why NOT EXISTS often performs better on large datasets. But remember: Modern SQL optimizers can rewrite both — always check execution plans. Small query change. Big performance difference. #SQL #SQLTips #AdvancedSQL #QueryOptimization #Database #DataEngineering #Analytics #SQLServer #PostgreSQL #CodingTips
To view or add a comment, sign in
-
-
📊 Strengthening My SQL Fundamentals – Date & Time Formatting in MySQL. Today, I explored how to work with date and time functions in MySQL, focusing on the powerful DATE_FORMAT() function to extract structured insights from datetime data. 🔍 Key Takeaways: • Extracted day, weekday, month, and year from a single datetime column • Worked with useful format specifiers like %d, %a, %m, %b, %M, %Y • Improved understanding of how formatted data enhances reporting and analysis. 💡 Why this matters: Formatting date-time data plays a crucial role in: • Building intuitive dashboards • Performing time-based analysis • Writing cleaner, more readable SQL queries Even small improvements like these contribute to writing more efficient and production-ready queries. 🚀 Consistency is key — growing one concept at a time. Baraa Khatib Salkini #SQL #MySQL #DataAnalytics #LearningInPublic #TechSkills #Database #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 SQL Joins Simplified: Left Join vs Right Join Explained with Examples 🚀 In SQL, understanding joins is crucial for working with relational databases. But when it comes to Left Join and Right Join, many people get confused about how and when to use them. In this video, I break down the difference between these two joins with simple explanations and real-life examples. 🔹 Left Join returns all records from the left table and the matched records from the right table. 🔹 Right Join returns all records from the right table and the matched records from the left table. Check out the video for a clearer understanding and some hands-on examples! 👉 https://lnkd.in/gBUJ_j9f #SQL #DataScience #Database #SQLJoins #LearningSQL
SQL Joins Simplified - Left Join vs Right Join Explained with Examples
https://www.youtube.com/
To view or add a comment, sign in
-
SQL Progress: Aggregations & Joins! What I learned and practiced today: 1. Aggregate Functions: It’s becoming easier to decide when to use GROUP BY and how to handle multiple aggregations in one query. 2. Data Precision: Handling decimal calculations and rounding is becoming second nature now. It’s all about making the final output clean and professional. I love to learn from you! If you have any tips or a better way to solve these, please type them in the comments! قليل مستمر خير من كثير منقطع #SQL #DataEngineering #PostgreSQL #LeetCode #100DaysOfCode #LearningInPublic #ProblemSolving #DataAnalytics
To view or add a comment, sign in
-
-
I recently spent some time strengthening my SQL fundamentals beyond just basic queries and joins. To prepare better for data analyst roles, I worked through a structured set of practice questions covering topics like subqueries, CTEs, window functions, CASE statements, conditional aggregation, date functions, and database objects such as procedures, triggers, and views. Instead of passively reading, I focused on solving interview-style questions and understanding when and why to use each concept. Some of the areas I practiced: • Correlated subqueries and EXISTS • Window functions like ROW_NUMBER, DENSE_RANK • CTEs for structured query building • Conditional aggregation using CASE I’ve documented this practice along with the dataset, questions, and solutions here: 🔗 https://lnkd.in/gN29KuwR This exercise really helped me improve my query logic and confidence while approaching SQL problems. I’m continuing to build more projects and deepen my understanding of data analytics. #SQL #MySQL #DataAnalytics #DataAnalyst
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development