Explore a curated collection of practical examples demonstrating various SQL Server features and functionalities. These snippets are designed to help you understand and implement common scenarios effectively.
Retrieve data from a table, specifying the columns you need.
SELECT CustomerID, CompanyName, ContactName
FROM Customers
WHERE Country = 'USA';
Use the WHERE clause to filter records based on specified conditions.
SELECT OrderID, OrderDate, ShipVia
FROM Orders
WHERE OrderDate BETWEEN '1996-07-01' AND '1996-07-31'
ORDER BY OrderDate DESC;
Combine rows from two or more tables based on a related column between them.
SELECT o.OrderID, c.CompanyName, o.OrderDate
FROM Orders AS o
JOIN Customers AS c ON o.CustomerID = c.CustomerID
WHERE c.City = 'London';
Add new rows of data to a table.
INSERT INTO Products (ProductName, SupplierID, CategoryID, Unit, Price)
VALUES ('Chai Tea', 1, 1, '10 boxes x 20 bags', 18.00);
Modify existing data within a table.
UPDATE Customers
SET Country = 'Canada'
WHERE CustomerID = 5;
Remove rows from a table that meet specific criteria.
DELETE FROM OrderDetails
WHERE Quantity < 5;
Perform calculations on sets of rows.
SELECT COUNT(CustomerID) AS NumberOfCustomers,
AVG(CAST(Freight AS DECIMAL(10,2))) AS AverageFreight
FROM Orders
WHERE ShipCountry = 'Germany';
Group rows that have the same values in specified columns into summary rows.
SELECT City, COUNT(CustomerID) AS NumberOfCustomers
FROM Customers
GROUP BY City
ORDER BY NumberOfCustomers DESC;
A pre-compiled SQL query that can be executed repeatedly.
CREATE PROCEDURE GetCustomerOrders (@CustomerID INT)
AS
BEGIN
SELECT OrderID, OrderDate, ShipCity
FROM Orders
WHERE CustomerID = @CustomerID;
END;
GO
-- To execute:
-- EXEC GetCustomerOrders @CustomerID = 10;
A temporary named result set that you can reference within a single SQL statement.
WITH RecentOrders AS (
SELECT OrderID, CustomerID, OrderDate
FROM Orders
WHERE OrderDate > DATEADD(year, -1, GETDATE())
)
SELECT c.CompanyName, ro.OrderID, ro.OrderDate
FROM Customers AS c
JOIN RecentOrders AS ro ON c.CustomerID = ro.CustomerID;