Did you know you can override the order that ORDER BY sorts by in SQL? I didn't — not until recently, at least. How it came up, I was writing a query that subdivided years into decades — including a catch-all “Pre-1950s” category. When I ordered by decade, though, “Pre-1950s” came out at the bottom — which is to say, 𝘢𝘧𝘵𝘦𝘳 the 2020s. Naturally, I wanted it on top, in chronological order. That’s when I learned this very handy trick: 𝐎𝐑𝐃𝐄𝐑 𝐁𝐘 𝐂𝐀𝐒𝐄 𝐖𝐇𝐄𝐍 𝐝𝐞𝐜𝐚𝐝𝐞 = '𝐏𝐫𝐞-1950𝐬' 𝐓𝐇𝐄𝐍 0 𝐄𝐋𝐒𝐄 1 𝐄𝐍𝐃, 𝐝𝐞𝐜𝐚𝐝𝐞; ORDER BY is basically creating an ad hoc table with a zero next to “Pre-1950s” and a 1 next to everything else: It’s like a temporary sort key. SQL does the preliminary sort according to the 0 and 1’s, and then the standard sorting by decade takes over after that. I’d never realized you could 𝘢𝘤𝘵𝘪𝘷𝘦𝘭𝘺 𝘣𝘶𝘪𝘭𝘥 𝘢𝘯 𝘰𝘳𝘥𝘦𝘳 within ORDER BY — I had always perceived its role as more passive than that. But now: A nifty new brush in the SQL paintbox! #dataanalytics #dataanalyticsjourney #sql #orderby
Override ORDER BY in SQL with CASE WHEN
More Relevant Posts
-
🚀 7-Day SQL Challenge – Day 4 (The Power of JOINs 🔗) Today I learned how SQL connects data across multiple tables using JOINs. Imagine two tables: Customers and Orders. ✅ INNER JOIN Shows only customers who have placed orders. → The intersection of both tables. ✅ LEFT JOIN Shows all customers — even those with no orders (NULLs appear for missing data). → Keep everything from the left, match where possible. ✅ RIGHT JOIN Shows all orders — even if the customer record is missing. → Keep everything from the right, match where possible. ✅ FULL OUTER JOIN Shows all customers AND all orders, matched or unmatched. → The union of both tables. 💡 My Biggest Takeaway: JOINs aren't just a SQL feature — they reflect how real-world data is structured. Most databases split information across tables to avoid duplication. JOINs bring it all back together. 📌 When to use which: → Need exact matches only? → INNER JOIN → Don't want to lose left table rows? → LEFT JOIN → Right table is your anchor? → RIGHT JOIN → Want the full picture? → FULL OUTER JOIN Day 4 done ✅ Each day, SQL feels less like a language and more like a lens for understanding data. #SQL #DataAnalytics #LearningJourney #7DayChallenge #DataAnalyst #SQLJoins
To view or add a comment, sign in
-
-
For weeks, SQL JOINs felt like a personal enemy 🥹 I stared at those Venn diagrams until my eyes blurred. Inner? Left? Full? It all felt very overwhelming. I’d write a query, get 0 rows and have no idea why. I almost convinced myself I wasn't "technical enough." Then, I stopped looking at diagrams and started looking at the data. I realized a JOIN isn't a math problem. It’s just a conversation between two tables. "Hey Table A, do you have any info on customer 001?" "Table B says yes, here is their order." Once I started "talking" to my data, it clicked. However, this didn't happen overnight. I practiced oftenly. If you're struggling with JOINs today, don't quit. I see you. I was you. Let me break it down for you. Think of SQL JOINs as a way of combining data from two or more tables based on a related column (like a common ID). Types of JOINS INNER JOIN What it does: Returns only matching records from both tables. LEFT JOIN (LEFT OUTER JOIN) What it does: Returns all records from the left table + matching ones from the right. You might be wondering which is the left table (just like I did for the longest). It's the table that appears immediately after the FROM statement. RIGHT JOIN (RIGHT OUTER JOIN) What it does: Returns all records from the right table + matching from the left. The right table appears after the JOIN statement. FULL JOIN (FULL OUTER JOIN) What it does: Returns all records from both tables SELF JOIN What it does: Joins a table to itself Today, I joined orders table and customers table using an INNER JOIN. The orders table contains customer id numbers, but not the actual names of the customers. The INNER JOIN finds matches between the customer id in the orders table and the customer id in the customers table. #DataAnalytics #Datascience #SQL #JOINS #Techcommunity #BuildinginPublic
To view or add a comment, sign in
-
-
Day 1/30 of SQL Challenge Today I learned: -> SELECT & FROM Key idea: SELECT is used to choose columns, and FROM tells SQL which table to get the data from. This is the foundation of every SQL query - without it, nothing starts. Examples: 1. Select specific columns: SELECT name, age FROM customers; 2. Select all columns: SELECT * FROM customers; 3. Select multiple columns from another table: SELECT product_name, price, stock FROM products; 4. Combine simple math with SELECT: SELECT price, price * 0.9 AS discounted_price FROM products; What I understood: SELECT + FROM is like telling SQL, “Hey, give me THIS data from THAT table.” Even simple queries let you explore your data and understand its structure. Playing with a few columns at a time makes learning much easier. Practice for yourself: Pick a table and list just 2–3 columns. Try selecting all columns using *. Multiply a numeric column by a number using AS to see new column results. #SQL #LearningInPublic #Data #SQLPractice #BuildInPublic
To view or add a comment, sign in
-
-
✅ Solved a SQL problem on StrataScratch — Day 52 of my SQL Journey 💪 Numbers don’t mean much… until you compare them over time 📊 Today’s problem was about calculating the month-over-month percentage change in revenue — a simple metric, but one that tells a powerful story. The approach: • Aggregated total revenue per month • Joined each month with its previous month • Calculated percentage change using the classic MoM formula • Handled NULL cases for the first month cleanly What I practised: • Time-based aggregation using DATE_FORMAT() • Self joins for period comparison • Percentage calculations in SQL • Handling edge cases in analytical queries What stood out — Raw numbers show what happened. Comparisons show what changed. A revenue of 10K means nothing alone… but +25% or -10% tells the real story. That shift — from totals to trends — is what turns data into insight. Consistent learning, one query at a time 🚀 #SQL #StrataScratch #DataAnalytics #LearningInPublic #SQLPractice
To view or add a comment, sign in
-
-
I wrote a SQL query to filter high-revenue countries… and it failed. The logic looked correct. But SQL threw an error. Here’s what I tried: 👉 Filtering total revenue using WHERE Something like: WHERE SUM(order_total) > 10000 And SQL didn’t accept it. That’s when I realized: 👉 I was filtering at the wrong stage of the query. In SQL, execution doesn’t happen the way we read the query. It actually works like this: FROM WHERE GROUP BY HAVING SELECT ORDER BY 💥 The mistake: WHERE runs before aggregation So it can’t use functions like SUM(), COUNT(), etc. ✅ The fix: Use HAVING for aggregated conditions: 👉 HAVING SUM(order_total) > 10000 💡 What I learned: WHERE filters rows HAVING filters grouped results Sounds simple… but easy to mess up in real queries. Now I think of it like this: 👉 WHERE → “filter raw data” 👉 HAVING → “filter summarized data” 📌 Lesson: If your query involves aggregation and filtering… Always ask: 👉 Am I filtering before grouping or after? This small distinction can save you from a lot of confusion. #SQL #DataEngineering #SQLTips #Analytics #LearnSQL #DataAnalytics #QueryOptimization #TechLearning #Debugging
To view or add a comment, sign in
-
-
🚀 𝗠𝗮𝘀𝘁𝗲𝗿 𝗦𝗤𝗟 𝗪𝗶𝗻𝗱𝗼𝘄 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀 If you're working with SQL and still relying heavily on GROUP BY, it's time to level up your skills. Window Functions allow you to perform calculations across rows without collapsing your dataset. This means you can: ✔ Rank data ✔ Calculate running totals ✔ Compare rows within the same result set All while keeping your original data intact. 🔍 𝗗𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝗰𝗲 𝗕𝗲𝘁𝘄𝗲𝗲𝗻 𝗥𝗔𝗡𝗞(), 𝗗𝗘𝗡𝗦𝗘_𝗥𝗔𝗡𝗞() & 𝗥𝗢𝗪_𝗡𝗨𝗠𝗕𝗘𝗥() These are the most commonly used window functions for ranking 👇 👉 𝗥𝗢𝗪_𝗡𝗨𝗠𝗕𝗘𝗥() Assigns a unique number to each row. Even if values are the same, the numbering will be different. 👉 𝗥𝗔𝗡𝗞() Gives the same rank to duplicate values, but skips the next rank. Example: 1, 2, 2, 4 👉 𝗗𝗘𝗡𝗦𝗘_𝗥𝗔𝗡𝗞() Also gives the same rank to duplicates, but does NOT skip ranks. Example: 1, 2, 2, 3 💡 𝗪𝗵𝗲𝗻 𝘁𝗼 𝗨𝘀𝗲 𝗪𝗵𝗮𝘁? Use 𝗥𝗢𝗪_𝗡𝗨𝗠𝗕𝗘𝗥() → when you need unique ordering (no duplicates) Use 𝗥𝗔𝗡𝗞() → when gaps in ranking are acceptable Use 𝗗𝗘𝗡𝗦𝗘_𝗥𝗔𝗡𝗞() → when you want continuous ranking #SQL #WindowFunctions #DataAnalytics #LearnSQL #SQLInterview #DataAnalyst #DataEngineering
To view or add a comment, sign in
-
-
SQL JOIN'S 📌 While learning SQL, one thing became clear to me — data is usually not stored in one place. It’s divided into multiple tables, and that’s where JOIN becomes important. So, what is SQL JOIN? SQL JOIN is used to combine data from different tables using a common column, so we can see the complete picture. Simple example: We have: Customers table (Customer_ID, Name) Orders table (Customer_ID, Order_Amount) Using JOIN, we can connect both tables and understand: which customer made which purchase Types of JOIN: INNER JOIN– gives only matching data from both tables, LEFT JOIN– gives all data from left table + matching from right, RIGHT JOIN – gives all data from right table + matching from left, FULL JOIN– gives all data from both tables, What I understood: JOIN is not just about writing queries… it’s about connecting data to understand what’s actually happening. #SQL #DataAnalytics #LearningJourney #BusinessAnalytics #DataScience
To view or add a comment, sign in
-
-
Here's an even more concise version ✅ 🔺 SQL Quick Reference ▪️ 1. Basics SELECT: Picks columns. FROM: Specifies the table. WHERE: Filters rows (LIKE, IN, BETWEEN, AND, OR). ORDER BY: Sorts results (ASC, DESC). AS (Alias): Renames columns or tables. ▪️ 2. Summarizing Functions: COUNT (), SUM(), AVG(, MIN(, MAX. GROUP BY: Groups rows for aggregate functions. HAVING: Filters after grouping. ▪️ 3. Combining INNER JOIN: Matching rows from both tables. LEFT JOIN: All from left, matches from right. RIGHT JOIN: All from right, matches from left. FULL JOIN: All rows from both tables. 🔺 Follow Saurabh Rai for more... #SQL #Data #Dataanalyst #Learning #Joins
To view or add a comment, sign in
-
-
SQL Execution Order (not how we write it, but how it actually runs) Most of us write queries like this: SELECT → FROM → WHERE → GROUP BY → ORDER BY But internally, SQL processes it very differently. SQL executes in this order: FROM JOIN WHERE GROUP BY HAVING SELECT DISTINCT ORDER BY LIMIT Here’s a simpler way to think about it FILTER → SHOW → SORT → LIMIT What this actually means • FILTER → FROM, JOIN, WHERE, GROUP BY, HAVING (Define data + reduce it step by step) • SHOW → SELECT, DISTINCT (Choose what you want to display) • SORT → ORDER BY (Organize the result) • LIMIT → LIMIT / TOP (Control how much data you return) Once we start thinking in execution order, we stop “trial and error” and start writing SQL with confidence. If you’re working with SQL daily, this mental model makes a huge difference. #SQL #DataAnalytics #LearnSQL #SQLTips #DataEngineering #Analytics
To view or add a comment, sign in
-
-
SQL "GROUP BY" Trap: Why your query is throwing an error? 🛑📊 One of the most common hurdles in SQL isn’t just writing the query—it’s understanding the logic behind grouping data. Have you ever tried to SELECT a column alongside a SUM() or COUNT() and got a "not a GROUP BY expression" error? The Golden Rule: If a column is not inside an aggregate function (like SUM, AVG, COUNT), it MUST be included in the GROUP BY clause. Think of it this way: If you ask for the total sales (SUM) per "Region", the database creates one bucket for each region. If you also try to select "Customer Name" without grouping it, the database gets confused: "Which specific customer should I show for this entire region's total?" Key Takeaways for Clean Queries: ✅ GROUP BY: Defines your "buckets" (e.g., Department, Year, Category). ✅ WHERE: Filters individual rows before they are grouped. ✅ HAVING: Filters the groups after the math is done. Understanding this distinction is the bridge between just "writing code" and truly performing data analysis. #SQL #DataAnalytics #Database #CodingTips #SQLDeveloper #TechCommunity #SQLProgramming
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