Skip to content

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

Category: SQL

SQL

SQL: Use CTEs for Readable Complex Queries

- 30.03.26 - ErcanOPAK comment on SQL: Use CTEs for Readable Complex Queries

๐Ÿ“ Named Subqueries Nested subqueries everywhere? Can’t understand your own query? CTEs (WITH clause) create temporary named result sets. Makes complex queries readable. The Subquery Nightmare — โŒ Nested subqueries – Unreadable! SELECT customer_name, total_orders, avg_order_value FROM ( SELECT c.name AS customer_name, COUNT(o.id) AS total_orders, AVG(o.total) AS avg_order_value FROM customers c JOIN ( SELECT * […]

Read More
SQL

SQL: Use Window Functions for Advanced Analytical Queries

- 30.03.26 - ErcanOPAK comment on SQL: Use Window Functions for Advanced Analytical Queries

๐Ÿ“Š SQL Superpowers Need row numbers? Running totals? Rankings? Window functions perform calculations across table rows without GROUP BY. Game-changing for analytics. ROW_NUMBER() – Assign Row Numbers — โŒ Old way: Can’t number rows easily SELECT name, salary, department FROM employees ORDER BY salary DESC; — โœ… Window function: Add row numbers SELECT ROW_NUMBER() OVER […]

Read More
SQL

SQL: Read Execution Plans to Find Performance Bottlenecks

- 22.03.26 - ErcanOPAK comment on SQL: Read Execution Plans to Find Performance Bottlenecks

๐Ÿ” See What Database Actually Does Query slow? Don’t guess. Execution plans show exactly how database executes query. Find bottlenecks, fix performance. Get Execution Plan — SQL Server SET STATISTICS IO ON; SET STATISTICS TIME ON; — Show estimated plan (doesn’t run query) SET SHOWPLAN_TEXT ON; GO SELECT * FROM orders WHERE user_id = 123; […]

Read More
SQL

SQL: Use CTEs (WITH Clause) for Readable Complex Queries

- 22.03.26 - ErcanOPAK comment on SQL: Use CTEs (WITH Clause) for Readable Complex Queries

๐Ÿ“ Name Your Subqueries Nested subqueries everywhere? Unreadable mess? CTEs (Common Table Expressions) name intermediate results. Code becomes self-documenting. The Subquery Nightmare — โŒ Nested subqueries: Hard to read SELECT u.name, (SELECT COUNT(*) FROM orders o WHERE o.user_id = u.id) as order_count, (SELECT AVG(total) FROM orders o WHERE o.user_id = u.id) as avg_order FROM users […]

Read More
SQL

SQL: Use Indexed Views to Cache Complex Query Results

- 19.03.26 - ErcanOPAK comment on SQL: Use Indexed Views to Cache Complex Query Results

โšก Materialized Views in SQL Server Complex aggregation query taking 10 seconds? Create indexed view. Query becomes instant. Data stays fresh automatically. Problem: Slow Aggregate Query — This runs every time, slow on large tables SELECT CategoryId, COUNT(*) AS ProductCount, AVG(Price) AS AvgPrice, SUM(Stock) AS TotalStock FROM Products GROUP BY CategoryId; — 10 seconds on […]

Read More
SQL

SQL: Use Window Functions for Running Totals Without Self-Joins

- 19.03.26 - ErcanOPAK comment on SQL: Use Window Functions for Running Totals Without Self-Joins

๐Ÿ“Š Advanced Analytics Made Easy Need running totals, rankings, moving averages? Window functions do it in one query. No self-joins. Running Total Example — Calculate cumulative sales per day SELECT SaleDate, Amount, SUM(Amount) OVER (ORDER BY SaleDate) AS RunningTotal FROM Sales ORDER BY SaleDate; — Result: — SaleDate Amount RunningTotal — 2024-01-01 100 100 — […]

Read More
SQL

SQL: Use OFFSET FETCH for Pagination

- 19.03.26 | 19.03.26 - ErcanOPAK comment on SQL: Use OFFSET FETCH for Pagination

Building pagination? OFFSET FETCH is standard SQL way. — Page 1 (rows 1-10) SELECT * FROM Products ORDER BY ProductId OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY; — Page 2 (rows 11-20) SELECT * FROM Products ORDER BY ProductId OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY; — Dynamic pagination DECLARE @PageNumber INT = […]

Read More
SQL

SQL: Use COALESCE to Handle NULL Values

- 19.03.26 | 19.03.26 - ErcanOPAK comment on SQL: Use COALESCE to Handle NULL Values

NULL values breaking calculations? Use COALESCE for fallback. — Returns first non-NULL value SELECT COALESCE(Phone, Email, ‘No contact’) AS Contact FROM Users; — Default values in calculations SELECT Name, Price * COALESCE(Quantity, 0) AS Total FROM Orders; — Multiple fallbacks SELECT COALESCE(PreferredName, FirstName, ‘Unknown’) AS DisplayName FROM Users; vs ISNULL: COALESCE is ANSI standard (works […]

Read More
SQL

SQL: Use CROSS APPLY for Correlated Subqueries Performance

- 19.03.26 | 19.03.26 - ErcanOPAK comment on SQL: Use CROSS APPLY for Correlated Subqueries Performance

โšก Faster Correlated Queries Correlated subqueries in SELECT run for every row. CROSS APPLY runs once. — โŒ SLOW (subquery runs per row) SELECT c.Name, (SELECT TOP 1 OrderDate FROM Orders WHERE CustomerId = c.CustomerId ORDER BY OrderDate DESC) AS LastOrder FROM Customers c; — โœ… FAST (CROSS APPLY optimized) SELECT c.Name, o.OrderDate FROM Customers […]

Read More
SQL

SQL: Use CTEs for Readable Complex Queries

- 19.03.26 | 19.03.26 - ErcanOPAK comment on SQL: Use CTEs for Readable Complex Queries

๐Ÿ“– Readable SQL Nested subqueries hurt readability. CTEs (Common Table Expressions) make complex queries clear. — Clear, readable, step-by-step WITH ActiveUsers AS ( SELECT * FROM Users WHERE IsActive = 1 ), RecentOrders AS ( SELECT * FROM Orders WHERE CreatedAt > DATEADD(month, -1, GETDATE()) ) SELECT u.Name, COUNT(o.OrderId) AS OrderCount FROM ActiveUsers u LEFT […]

Read More
SQL

SQL: Protecting Sensitive Data with Dynamic Data Masking

- 01.03.26 - ErcanOPAK comment on SQL: Protecting Sensitive Data with Dynamic Data Masking

Don’t let developers see customer credit card numbers. Mask them at the database level. ALTER TABLE Users ALTER COLUMN Email ADD MASKED WITH (FUNCTION = ’email()’); The data remains intact in the DB, but users without special permissions only see uXXX@XXXX.com. Essential for GDPR compliance.

Read More
SQL

SQL: Writing Readable Queries with Common Table Expressions (CTE)

- 01.03.26 - ErcanOPAK comment on SQL: Writing Readable Queries with Common Table Expressions (CTE)

Stop nesting subqueries. It makes SQL unreadable. Use WITH. WITH MonthlySales AS ( SELECT Month, SUM(Amount) as Total FROM Sales GROUP BY Month ) SELECT * FROM MonthlySales WHERE Total > 10000; It reads like a story from top to bottom, making it much easier for your team to maintain.

Read More
SQL

SQL: Why Your Query Plan is Wrong – The Importance of Statistics

- 01.03.26 - ErcanOPAK comment on SQL: Why Your Query Plan is Wrong – The Importance of Statistics

The SQL Optimizer uses Statistics (histograms of data distribution) to decide between a Scan or a Seek. If stats are stale, SQL makes bad decisions. The Fix: Regularly run UPDATE STATISTICS MyTable. If you just performed a massive data import, this is more important than rebuilding indexes to maintain performance.

Read More
SQL

SQL: Identifying and Resolving Deadlocks in High-Concurrency DBs

- 01.03.26 - ErcanOPAK comment on SQL: Identifying and Resolving Deadlocks in High-Concurrency DBs

A Deadlock occurs when Task A waits for Task B, and Task B waits for Task A. The DB kills one to save the other. Prevention Strategy Implementation Access Order Always update Table A then B, never mix. Snapshot Isolation READ_COMMITTED_SNAPSHOT ON. Use DBCC TRACEON (1222, -1) to capture detailed deadlock graphs in the error […]

Read More
SQL

SQL: Eliminating Key Lookups with Covering Indexes (INCLUDE)

- 01.03.26 - ErcanOPAK comment on SQL: Eliminating Key Lookups with Covering Indexes (INCLUDE)

Even with an index, SQL might still go to the main table (Key Lookup) to find extra columns. Use INCLUDE to make it a ‘Covering Index’. CREATE INDEX IX_Users_City ON Users(City) INCLUDE (Email, Status); By including the extra columns in the index leaf nodes, SQL Server finds everything it needs in the index itself, cutting […]

Read More
SQL

SQL: Querying NoSQL Data Inside Relational SQL Server

- 01.03.26 - ErcanOPAK comment on SQL: Querying NoSQL Data Inside Relational SQL Server

Storing JSON in a NVARCHAR(MAX) column? You can query it just like a table using JSON_VALUE and OPENJSON. SELECT Name, JSON_VALUE(LogData, ‘$.IP’) as LoginIP FROM Logs WHERE JSON_VALUE(LogData, ‘$.Status’) = ‘Failed’; This provides the flexibility of NoSQL with the strict ACID compliance of SQL Server. Best of both worlds.

Read More
SQL

SQL: Multi-tenant Security with Row-Level Security (RLS)

- 28.02.26 - ErcanOPAK comment on SQL: Multi-tenant Security with Row-Level Security (RLS)

Protecting data between different customers in the same table is hard. Instead of complex WHERE TenantId = @id in every query, use RLS. You define a security policy at the database level. The database itself will automatically filter the rows based on the logged-in user context, making it impossible for one customer to accidentally see […]

Read More
SQL

SQL: Optimizing Multiple WHERE Clauses with Index Intersection

- 28.02.26 - ErcanOPAK comment on SQL: Optimizing Multiple WHERE Clauses with Index Intersection

If you query WHERE City=’NYC’ AND Age > 30, SQL doesn’t always need a single composite index. It can use Index Intersection. It scans two separate indexes and finds the overlapping rows. However, for maximum performance, a composite index (City, Age) is usually superior because it avoids the merge step.

Read More
SQL

SQL: The ‘IsDeleted’ Pattern vs Data Integrity

- 28.02.26 - ErcanOPAK comment on SQL: The ‘IsDeleted’ Pattern vs Data Integrity

Never physically DELETE data in enterprise apps. Use a bit column IsDeleted. But how do you handle unique constraints? Pro Tip: Use a Filtered Unique Index. This allows you to have the same email address in a ‘Users’ table if the previous ones are marked as deleted. CREATE UNIQUE INDEX UI_ActiveEmail ON Users(Email) WHERE IsDeleted […]

Read More
SQL

SQL: Calculating Running Totals with the OVER() Clause

- 28.02.26 - ErcanOPAK comment on SQL: Calculating Running Totals with the OVER() Clause

Before Window Functions, calculating a running total required a complex self-join. Now, it’s a one-liner. SELECT OrderDate, Amount, SUM(Amount) OVER (ORDER BY OrderDate) as RunningTotal FROM Sales; Why? It’s significantly faster because the database only scans the table once (O(N) vs O(N^2)).

Read More
SQL

SQL: Fixing Slow Queries with Index Rebuilding

- 28.02.26 - ErcanOPAK comment on SQL: Fixing Slow Queries with Index Rebuilding

Even with indexes, your DB can slow down due to Fragmentation. This happens after many Inserts/Deletes. The Pro Check: Run this to rebuild all indexes on a table and reclaim performance: ALTER INDEX ALL ON MyTableName REBUILD;

Read More
SQL

SQL: Making Complex Queries Readable with Common Table Expressions (CTE)

- 28.02.26 - ErcanOPAK comment on SQL: Making Complex Queries Readable with Common Table Expressions (CTE)

Subqueries are hard to read and debug. CTEs allow you to create ‘Virtual Results’ that you can reference easily. WITH HighValueSales AS ( SELECT * FROM Sales WHERE Amount > 1000 ) SELECT p.ProductName, hvs.Amount FROM HighValueSales hvs JOIN Products p ON hvs.ProductId = p.Id;

Read More
SQL

SQL Query Optimization: The 5 Tricks That Saved Our Database from Collapse

- 23.02.26 | 23.02.26 - ErcanOPAK comment on SQL Query Optimization: The 5 Tricks That Saved Our Database from Collapse

๐Ÿ’ฅ The Database Meltdown 9 AM Monday. Database CPU: 98%. Queries timing out. Users can’t log in. Boss is screaming. You have 1 hour to fix it before the CEO finds out. The 5 Performance Killers (And How to Fix Them) ๐Ÿ’ฃ Killer #1: SELECT * โŒ SLOW (transfers 50 columns, 10MB) SELECT * FROM […]

Read More
SQL

SQL: Use EXISTS Instead of IN for Better Performance

- 22.02.26 | 22.02.26 - ErcanOPAK comment on SQL: Use EXISTS Instead of IN for Better Performance

IN processes entire subquery. EXISTS stops at first match (faster). Slow (IN): SELECT * FROM Customers WHERE CustomerId IN ( SELECT CustomerId FROM Orders WHERE Total > 1000 ); — Processes ALL matching orders Fast (EXISTS): SELECT * FROM Customers c WHERE EXISTS ( SELECT 1 FROM Orders o WHERE o.CustomerId = c.CustomerId AND o.Total […]

Read More
SQL

SQL: Use UNION ALL Instead of UNION When Duplicates Don’t Matter

- 22.02.26 | 22.02.26 - ErcanOPAK comment on SQL: Use UNION ALL Instead of UNION When Duplicates Don’t Matter

UNION removes duplicates (expensive operation). UNION ALL keeps them (fast). UNION (Slow): SELECT Name FROM ActiveUsers UNION SELECT Name FROM InactiveUsers; — Removes duplicates: Sorts, scans, filters — Slow on large datasets! UNION ALL (Fast): SELECT Name FROM ActiveUsers UNION ALL SELECT Name FROM InactiveUsers; — Keeps duplicates: No sorting or filtering — Much faster! […]

Read More
SQL

SQL: Identifying and Preventing Deadlocks in High-Concurrency Systems

- 21.02.26 - ErcanOPAK comment on SQL: Identifying and Preventing Deadlocks in High-Concurrency Systems

Deadlocks occur when two processes wait for each other to release locks. Learn how to use Extended Events to capture deadlock graphs and rewrite queries to avoid ‘Victim’ status.

Read More
SQL

SQL: Advanced Query Tuning with CTEs and Recursive Logic

- 21.02.26 - ErcanOPAK comment on SQL: Advanced Query Tuning with CTEs and Recursive Logic

Common Table Expressions (CTEs) are not just for readability. They allow for Recursive Queries, essential for hierarchical data like organizational charts or folder structures.

Read More
SQL

SQL: Fixing Slow Queries with Index Rebuilding

- 21.02.26 - ErcanOPAK comment on SQL: Fixing Slow Queries with Index Rebuilding

If your database is slow despite having indexes, they might be fragmented. Check fragmentation with sys.dm_db_index_physical_stats. The Fix: ALTER INDEX ALL ON MyTable REBUILD;

Read More
SQL

SQL Server: Querying JSON Columns Like a Pro

- 21.02.26 - ErcanOPAK comment on SQL Server: Querying JSON Columns Like a Pro

Modern SQL Server can handle NoSQL-style JSON data. Stop serializing/deserializing in C#; do it in SQL! SELECT JSON_VALUE(LogData, ‘$.Browser’) as Browser FROM WebLogs WHERE JSON_VALUE(LogData, ‘$.Status’) = ‘Error’

Read More
SQL

SQL: Professional Soft Delete Strategy for Data Safety

- 21.02.26 - ErcanOPAK comment on SQL: Professional Soft Delete Strategy for Data Safety

Never DELETE from production. Use an IsDeleted bit column and a Global Query Filter to hide deleted data while keeping it recoverable.

Read More
Page 1 of 9
1 2 3 4 5 6 … 9 Next ยป

Posts navigation

Older posts
April 2026
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
27282930  
« Mar    

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (950)
  • How to add default value for Entity Framework migrations for DateTime and Bool (859)
  • Get the First and Last Word from a String or Sentence in SQL (836)
  • How to select distinct rows in a datatable in C# (805)
  • How to make theater mode the default for Youtube (754)
  • Add Constraint to SQL Table to ensure email contains @ (578)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (564)
  • Average of all values in a column that are not zero in SQL (531)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (489)
  • Find numbers with more than two decimal places in SQL (448)

Recent Posts

  • C#: Use Init-Only Setters for Immutable Objects After Construction
  • C#: Use Expression-Bodied Members for Concise Single-Line Methods
  • C#: Enable Nullable Reference Types to Eliminate Null Reference Exceptions
  • C#: Use Record Types for Immutable Data Objects
  • SQL: Use CTEs for Readable Complex Queries
  • SQL: Use Window Functions for Advanced Analytical Queries
  • .NET Core: Use Background Services for Long-Running Tasks
  • .NET Core: Use Minimal APIs for Lightweight HTTP Services
  • Git: Use Cherry-Pick to Apply Specific Commits Across Branches
  • Git: Use Interactive Rebase to Clean Up Commit History Before Merge

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (950)
  • How to add default value for Entity Framework migrations for DateTime and Bool (859)
  • Get the First and Last Word from a String or Sentence in SQL (836)
  • How to select distinct rows in a datatable in C# (805)
  • How to make theater mode the default for Youtube (754)

Recent Posts

  • C#: Use Init-Only Setters for Immutable Objects After Construction
  • C#: Use Expression-Bodied Members for Concise Single-Line Methods
  • C#: Enable Nullable Reference Types to Eliminate Null Reference Exceptions
  • C#: Use Record Types for Immutable Data Objects
  • SQL: Use CTEs for Readable Complex Queries

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com