10 Essential SQL Queries for SQL Server Beginners
1. SELECT basic columns
sql
SELECT FirstName, LastName, Email FROM Employees;
- Use: retrieve specific columns.
2. SELECT with WHERE
sql
SELECT FROM Orders WHERE OrderDate >= ‘2023-01-01’ AND CustomerID = 42;
- Use: filter rows by conditions.
3. SELECT with ORDER BY
sql
SELECT ProductName, Price FROM Products ORDER BY Price DESC;
- Use: sort results.
4. SELECT with GROUP BY and aggregate
sql
SELECT CustomerID, COUNT() AS OrderCount, SUM(TotalAmount) AS TotalSpent FROM Orders GROUP BY CustomerID;
- Use: aggregate per group.
5. HAVING to filter groups
sql
SELECT CustomerID, COUNT() AS OrderCount FROM Orders GROUP BY CustomerID HAVING COUNT() > 5;
- Use: filter aggregated groups.
6. JOIN (INNER JOIN)
sql
SELECT o.OrderID, c.CustomerName, o.OrderDate FROM Orders o INNER JOIN Customers c ON o.CustomerID = c.CustomerID;
- Use: combine related tables.
7. LEFT JOIN (include unmatched)
sql
SELECT c.CustomerName, o.OrderID FROM Customers c LEFT JOIN Orders o ON c.CustomerID = o.CustomerID;
- Use: get all left-side rows even with no match.
8. INSERT single row
sql
INSERT INTO Products (ProductName, Price, Stock) VALUES (‘Widget’, 9.99, 100);
- Use: add a new record.
9. UPDATE rows
sql
UPDATE Products SET Price = Price * 1.05 WHERE Category = ‘Office’;
- Use: modify existing data.
10. DELETE rows safely
sql
DELETE FROM Sessions WHERE LastActive < ‘2024-01-01’;
- Use: remove rows; run a SELECT with the same WHERE first to confirm.
Tips:
- Always back up or run transactions for destructive queries.
- Use parameterized queries from applications to avoid SQL injection.
- Use SET NOCOUNT ON in scripts to reduce extra messages.