TGViewer
Data Analytics & AI | SQL Interviews | Power BI Resources Data Analytics & AI | SQL Interviews | Power BI Resources @data_visual · 27.5K subscribers
Post #547 843
SQL Tricks to Level Up Your Database Skills 🚀

SQL is a powerful language, but mastering a few clever tricks can make your queries faster, cleaner, and more efficient. Here are some cool SQL hacks to boost your skills:

1️⃣ Use COALESCE Instead of CASE
Instead of writing a long CASE statement to handle NULL values, use COALESCE():
SELECT COALESCE(name, 'Unknown') FROM users;

This returns the first non-null value in the list.

2️⃣ Generate Sequential Numbers Without a Table
Need a sequence of numbers but don’t have a numbers table? Use GENERATE_SERIES (PostgreSQL) or WITH RECURSIVE (MySQL 8+):
SELECT generate_series(1, 10);


3️⃣ Find Duplicates Quickly
Easily identify duplicate values with GROUP BY and HAVING:
SELECT email, COUNT(*) 
FROM users
GROUP BY email
HAVING COUNT(*) > 1;


4️⃣ Randomly Select Rows
Want a random sample of data? Use:
- PostgreSQL: ORDER BY RANDOM()
- MySQL: ORDER BY RAND()
- SQL Server: ORDER BY NEWID()

5️⃣ Pivot Data Without PIVOT (For Databases Without It)
Use CASE with SUM() to pivot data manually:
SELECT 
user_id,
SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) AS active_count,
SUM(CASE WHEN status = 'inactive' THEN 1 ELSE 0 END) AS inactive_count
FROM users
GROUP BY user_id;


6️⃣ Efficiently Get the Last Inserted ID
Instead of running a separate SELECT, use:
- MySQL: SELECT LAST_INSERT_ID();
- PostgreSQL: RETURNING id;
- SQL Server: SELECT SCOPE_IDENTITY();

Like for more ❤️
  • 👍 5
  • ❤ 1
More from @data_visual
  1. Oct 2, 2026Data Analyst Roadmap
  2. Sep 28, 2026🎯 GigaChat 3.5 Reasoning: 5 Key Features 1️⃣ Advanced Reasoning: Explores multiple step-b…
  3. Sep 23, 2026🚀 The 10 Levels of AI Agents — Where We Stand Today AI isn’t a single goal — it’s an evol…
  4. Sep 14, 2026AI tools to increase your productivity in 2026 👇 1/ Granola: AI meeting notes that captur…
  5. Sep 6, 2026Data Analyst interviews will be easier if you learn these tools in sequence: ➤ 𝗗𝗮𝘁𝗮 𝗙…
  6. Aug 29, 2026SQL Joins — A Practical Cheatsheet for Professionals If you’re working with relational dat…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →