4 min read•august 16, 2024
is the backbone of database management, letting you , modify, and query data with precision. It's like a superpower to control vast amounts of information effortlessly.
In this section, we dive into SQL's structure, key commands, and advanced techniques. From basic statements to complex JOINs and optimizations, you'll learn how to wield SQL like a pro in managing databases.
COMMAND [OPTION] [TARGET] [ACTION] [CONDITION];
CREATE TABLE Customers (CustomerID INT PRIMARY KEY, Name VARCHAR(50), Email VARCHAR(100));
INSERT INTO Customers (CustomerID, Name, Email) VALUES (1, 'John Doe', 'john@example.com');
INSERT INTO Customers (CustomerID, Name, Email) VALUES (2, 'Jane Smith', 'jane@example.com'), (3, 'Bob Johnson', 'bob@example.com');
UPDATE Customers SET Email = 'newemail@example.com' [WHERE](https://www.fiveableKeyTerm:where) CustomerID = 1;
DELETE FROM Customers WHERE CustomerID = 2;
DELETE FROM Customers;
SELECT Name, Email FROM Customers;
SELECT * FROM Customers WHERE Name LIKE 'J%';
SELECT * FROM Products WHERE Price > 50 AND Category = 'Electronics';
SELECT Orders.OrderID, Customers.Name FROM Orders INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
SELECT Customers.Name, Orders.OrderID FROM Customers LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID;
SELECT Name FROM Customers WHERE CustomerID IN (SELECT CustomerID FROM Orders WHERE TotalAmount > 1000);
SELECT * FROM Products ORDER BY Price DESC;
SELECT Category, [COUNT](https://www.fiveableKeyTerm:count)(*) AS ProductCount FROM Products GROUP BY Category;
SELECT Category, [AVG](https://www.fiveableKeyTerm:avg)(Price) AS AvgPrice FROM Products GROUP BY Category HAVING AVG(Price) > 100;
SELECT UPPER(Name) AS UppercaseName, LENGTH(Email) AS EmailLength FROM Customers;
SELECT OrderID, OrderDate, DATEDIFF(day, OrderDate, GETDATE()) AS DaysSinceOrder FROM Orders;
SELECT ProductName, Price, ROUND(Price * 0.9, 2) AS DiscountedPrice FROM Products;
SELECT COUNT(*) AS TotalCustomers, AVG(TotalPurchases) AS AveragePurchase FROM Customers;
SELECT COUNT(DISTINCT Category) AS UniqueCategories FROM Products;
SELECT ProductName, Price, AVG(Price) OVER (PARTITION BY Category) AS AvgCategoryPrice FROM Products;
CREATE FUNCTION dbo.CalculateDiscount(@price DECIMAL(10,2), @discountRate DECIMAL(5,2)) RETURNS DECIMAL(10,2) AS BEGIN RETURN @price * (1 - @discountRate) END;
SELECT ProductName, Price, CASE WHEN Price < 50 THEN 'Budget' WHEN Price < 100 THEN 'Mid-range' ELSE 'Premium' END AS PriceCategory FROM Products;
SELECT AVG(COALESCE(Salary, 0)) AS AverageSalary FROM Employees;
EXPLAIN SELECT * FROM Orders WHERE CustomerID = 1000;
CREATE INDEX idx_CustomerID ON Orders (CustomerID);
SELECT * FROM Customers WHERE LastName LIKE 'Smith%';
SELECT * FROM Customers WHERE LastName LIKE '%Smith';
CREATE TABLE Sales (SaleID INT, SaleDate DATE, Amount DECIMAL(10,2)) PARTITION BY RANGE (YEAR(SaleDate));