Learned SQL Views today — one of the most powerful features in SQL Server. 👁️ Created a View (vwEmployeeInformation) that combines data from 3 tables using INNER JOIN: ✔️ Employees → Employee name & salary ✔️ Department → Department name ✔️ Designations → Job title What is a VIEW? A virtual table that doesn't store data — it just presents joined data in a clean, readable format. Query it just like a regular table. Why it matters: Instead of writing complex JOINs every time, just call the View. Clean, reusable, and easy to maintain. One step deeper into backend development. 🚀 #SQL #SQLServer #Views #INNERJOIN #Database #BackendDevelopment #LearningInPublic #CSE
SQL Server Views: Combining Data with INNER JOIN
More Relevant Posts
-
💡 **SQL Server Tip: What is a CTE and why should you use it?** A **CTE (Common Table Expression)** is a temporary result set that helps you write cleaner and more readable SQL queries. Instead of messy nested subqueries, you can break your logic into clear steps. --- 🔹 **Example Scenario:** Find employees whose salary is higher than their department average. --- ✅ **Using CTE (Clean & Readable):** ```sql WITH DepartmentAvgSalary AS ( SELECT Department, AVG(Salary) AS AvgSalary FROM Employees GROUP BY Department ) SELECT e. Name, e.Department, e.Salary, d.AvgSalary FROM Employees e JOIN DepartmentAvgSalary d ON e.Department = d.Department WHERE e.Salary > d.AvgSalary; ``` --- ❌ **Without CTE (Harder to read):** ```sql SELECT e. Name, e.Department, e.Salary, d.AvgSalary FROM Employees e JOIN ( SELECT Department, AVG(Salary) AS AvgSalary FROM Employees GROUP BY Department ) d ON e.Department = d.Department WHERE e.Salary > d.AvgSalary; ``` --- 🚀 **Why use CTE?** ✔ Improves readability ✔ Makes complex queries easier to debug ✔ Helps structure your SQL step-by-step ✔ Essential for recursive queries #SQLServer #Database #Backend #DotNet #SoftwareEngineering #CleanCode
To view or add a comment, sign in
-
🚀 **How to Use User-Defined Table Types in SQL Server** One powerful feature in SQL Server is the **User-Defined Table Type**. It allows you to create a reusable table structure and pass multiple rows of data into stored procedures in a single call. This is cleaner and faster than sending rows one by one. 📌 Best suited for **small to medium-sized batches of data**. 🔹 **1. Create a Table Type** CREATE TYPE EmployeeTableType AS TABLE ( Id INT, Name VARCHAR(100), Salary DECIMAL(10,2) ); This creates a reusable table definition inside your database. --- 🔹 **2. Use It in a Stored Procedure** CREATE PROCEDURE InsertEmployees @Employees EmployeeTableType READONLY AS BEGIN INSERT INTO Employees (Id, Name, Salary) SELECT Id, Name, Salary FROM @Employees; END 📌 Table-valued parameters must always be `READONLY`. --- 🔹 **3. Execute the Procedure** DECLARE @Emp EmployeeTableType; INSERT INTO @Emp VALUES (1, 'John', 5000), (2, 'Sara', 6000), (3, 'Ali', 7000); EXEC InsertEmployees @Emp; --- 💡 **Why Use It?** Instead of calling a procedure multiple times: EXEC InsertEmployee 1,'John',5000 EXEC InsertEmployee 2,'Sara',6000 EXEC InsertEmployee 3,'Ali',7000 You send all rows in one request. ✅ Better performance ✅ Cleaner code ✅ Less network traffic ✅ Easier maintenance --- 📌 **Common Use Cases** • Bulk inserts from applications • Passing list of IDs • Importing Excel data • Batch updates • Reusable structured parameters --- ⚡ If you need to pass multiple rows into SQL Server efficiently, User-Defined Table Types are a feature worth knowing. #SQLServer #Database #TSQL #DotNet #BackendDevelopment #SoftwareEngineering #Programming #Performance
To view or add a comment, sign in
-
This post describes how SQL Server will PROCESS a query the first time someone is running an Ad Hoc query or Stored Procedure. #SQLServer #QueryTuning
To view or add a comment, sign in
-
🚀 Why Your Index Isn’t Working? Understanding SARGability in SQL Server As developers, we often create indexes expecting fast query performance… But sometimes SQL Server still performs a Table Scan instead of an Index Seek 🤔 The reason is often something called SARGability. 🔍 What is SARGability? SARGable = Search ARGument Able It determines whether SQL Server can use an index efficiently to filter data. 👉 SARGable Query → ✅ Index Seek (Fast) 👉 Non-SARGable Query → ❌ Index Scan (Slow on large data) ⚠️ Common Mistake (Non-SARGable Query) SELECT * FROM Users WHERE YEAR(CreatedDate) = 2024; 🚫 Problem: Applying a function (YEAR) on an indexed column ➡️ SQL Server cannot use the index efficiently → results in Index Scan ✅ Optimized Query (SARGable) SELECT * FROM Users WHERE CreatedDate >= '2024-01-01' AND CreatedDate < '2025-01-01'; ✔ No function on the column ✔ SQL Server can directly navigate the index → Index Seek 💼 Real-World Scenario In one of my projects, we had a Users table with ~2 million records. A search feature was taking 4–5 seconds ⏳ The query looked like this: SELECT * FROM Users WHERE LOWER(Email) = 'user@example.com'; Even though an index existed on Email, SQL Server performed a full scan. 💡 Solution We removed the function and ensured consistent data storage: SELECT * FROM Users WHERE Email = 'user@example.com'; 📈 Result ⚡ Query time improved from 5 seconds → under 100ms 📉 Reduced CPU usage 🚀 Faster response for users 🧠 Key Takeaways ✔ Avoid functions on indexed columns (YEAR, LOWER, etc.) ✔ Avoid calculations in WHERE clauses ✔ Use range-based filtering for dates ✔ Design indexes based on actual query patterns 💬 Final Thought Indexes don’t guarantee performance… 👉 SARGable queries do. #SQLServer #PerformanceTuning #DatabaseOptimization #BackendDevelopment #DotNet #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 **Understanding VIEW in SQL Server** A **VIEW** in SQL Server is a **virtual table** created from a `SELECT` query. It does not usually store data itself — it displays data from one or more tables whenever you query it. Think of it as a **saved query** that you can use like a table. --- 🔹 **Why Use a VIEW?** ✅ Simplify complex JOIN queries ✅ Reuse business logic ✅ Improve security by exposing selected columns only ✅ Make application queries cleaner ✅ Easier maintenance --- 🔹 **Basic Syntax** ```sql CREATE VIEW vw_EmployeeList AS SELECT Id, Name, Department FROM Employees; ``` Now use it like this: ```sql SELECT * FROM vw_EmployeeList; ``` --- 🔹 **Example with JOIN** ```sql CREATE VIEW vw_CustomerOrders AS SELECT c.Name, o.OrderId, o.Amount FROM Customers c JOIN Orders o ON c.CustomerId = o.CustomerId; ``` Then simply: ```sql SELECT * FROM vw_CustomerOrders; ``` --- 🔹 **Real Benefit** Instead of repeating a long query in many places, create it once as a VIEW and reuse it everywhere. --- 🔹 **Important Notes** ⚠️ A normal VIEW does **not automatically improve performance** ⚠️ It is mainly for organization, reusability, and security ⚠️ Avoid using too many nested views --- 🔹 **When to Use It** ✔ Reports ✔ Repeated joins ✔ Shared business logic ✔ Cleaner backend queries ✔ Restrict direct table access --- 💡 **Simple Summary** A VIEW is a **virtual table based on a SQL query**. It helps developers write cleaner and more maintainable SQL code. #SQLServer #Database #TSQL #BackendDevelopment #SoftwareEngineering #Programming #DataEngineering #SQLTips
To view or add a comment, sign in
-
🚀 SQL Concepts Made Simple: Joins vs Subqueries Understanding the difference between Joins and Subqueries is essential for writing efficient SQL queries. Here’s a quick comparison 👇 ✅ Joins 🔹 Used to combine data from multiple tables 🔹 Generally faster for large datasets 🔹 Improves readability in most scenarios ✅ Subqueries 🔹 Query written inside another query 🔹 Useful for step-by-step filtering 🔹 Ideal for handling complex conditions 💡 Key Insight: There’s no one-size-fits-all approach. Choosing between Joins and Subqueries depends on the problem, data size, and query complexity. 📊 Mastering both techniques helps in writing optimized and scalable SQL queries. #SQL #Database #Joins #Subqueries #DataAnalytics #Oracle #SQLDeveloper #TechSkills
To view or add a comment, sign in
-
-
𝐐𝐮𝐞𝐫𝐲 𝐄𝐱𝐞𝐜𝐮𝐭𝐢𝐨𝐧 𝐏𝐥𝐚𝐧𝐬 When a SQL query is slow, many people look only at the query text. But SQL Server does not execute SQL the way people read it. It executes a **plan**. That is why **Query Execution Plans** are one of the most important tools in SQL Server performance tuning. A simple way to think about it: The query is your request. The execution plan is SQL Server’s strategy for answering that request. And that strategy decides: - how data is accessed - which indexes are used - how joins are performed - whether sorting is needed - how much data moves through the operators This is why two queries that look very similar can perform very differently. Because the real cost is often not in the SQL text itself. It is in the plan shape chosen by the optimizer. A plan can reveal problems like: - index scans instead of efficient seeks - expensive key lookups - poor join choices - missing indexes - inaccurate row estimates - sorts and spills - unnecessary parallelism That is the real value of execution plans. They help answer not just: **What is slow?** But: **Why is SQL Server executing it this way?** Good tuning starts when you stop reading only the query and start reading the path SQL Server took to execute it. Because a slow query is often not just bad syntax. It is an expensive plan. #SQLServer #ExecutionPlan #QueryPerformance #SQLInternals #DatabasePerformance #PerformanceTuning #DatabaseAdministration
To view or add a comment, sign in
-
-
Day 29 – EXISTS Operator There's a SQL operator most beginners completely skip. It's not SELECT. Not WHERE. Not even JOIN. It's EXISTS and once you learn it, you'll use it every week. EXISTS is like a bouncer checking a VIP list. "Is this person on the list?" YES or NO. That's literally all it returns. It doesn't care about names, amounts, dates. Just: does a matching row exist? SELECT c.name FROM customers c WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id) For each customer, EXISTS checks the orders table stops the moment it finds one match. Much faster than IN on large tables. And its twin — NOT EXISTS — is even more useful: It finds what's MISSING. Customers with zero orders. Employees who didn't submit timesheets. Products with no reviews. One golden rule you must know: NOT EXISTS > NOT IN If even ONE NULL exists in a NOT IN subquery it returns ZERO rows silently. NOT EXISTS never has this problem. #SQL #LearnSQL #SQLforBeginners #DataAnalytics #TechCareer #DataScience
To view or add a comment, sign in
-
-
Every time your application sends 50 lines of SQL to SQL Server, that SQL is parsed, compiled, and planned from scratch. A stored procedure does it once — and caches the plan forever. Day 20 of 60 — SQL Server from Scratch to Master. Today: Stored Procedures — the professional standard for encapsulating business logic in SQL Server. The pattern I use in every search SP I build: WHERE (@param IS NULL OR column = @param). If the caller does not pass a value, the filter is skipped entirely. If they do, it is applied. One stored procedure handles every combination of filters — no IF/ELSE branching, no dynamic SQL. The mistake that costs production performance: naming your SP with sp_ prefix instead of usp_. SQL Server searches the master database first for anything starting with sp_. Performance hit every single call. Always use usp_ for user-defined procedures. The safety rule I never break: IF @@TRANCOUNT > 0 ROLLBACK before every rollback in CATCH. Rolling back with no open transaction throws another error inside your CATCH block and destroys the original error information. Do you use stored procedures in production — or does your team send raw SQL from the app? ♻ Repost to help your network build professional SQL Server applications. #SQLServer #TSQL #SQLDeveloper #LearnSQL #SQLServerFromScratch #SQLServer2019 #DatabaseDeveloper #OpenToWork #TechIndia #ITJobsIndia #HiringIndia #IndianDeveloper #LinkedInIndia #ImmediateJoiner #SQLJobs #100DaysOfCode #SQLTips #StoredProcedures #BackendDeveloper #MicrosoftSQL #DataEngineering #DatabaseDesign #SQLTutorial
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