Here are some basic SQL queries that demonstrate fundamental operations in SQL:
1. Selecting Data Query: Retrieve all columns from a table.
SELECT * FROM Employees;
SELECT FirstName, LastName FROM Employees;
Selects only the FirstName and LastName columns.
2. Filtering Data Query: Filter data with a condition.
SELECT * FROM Employees WHERE LastName = 'Smith';
SELECT * FROM Employees WHERE BirthDate < '1990-01-01' AND HireDate > '2010-01-01';
SELECT * FROM Employees WHERE FirstName LIKE 'J%';
LIKE 'J%' matches any FirstName that starts with 'J'.
3. Sorting Data Query: Sort data in ascending order (default).
SELECT * FROM Employees ORDER BY LastName;
SELECT * FROM Employees ORDER BY HireDate DESC;
ORDER BY HireDate DESC sorts the results by HireDate in descending order.
4. Limiting Results Query: Limit the number of results returned.
SELECT TOP 5 * FROM Employees ORDER BY HireDate DESC;
TOP 5 returns the top 5 rows when sorted by HireDate in descending order.
5. Aggregating Data Query: Count the number of rows.
SELECT COUNT(*) AS EmployeeCount FROM Employees;
SELECT AVG(Salary) AS AverageSalary FROM Employees;
SELECT MAX(Salary) AS MaxSalary, MIN(Salary) AS MinSalary FROM Employees;
MAX(Salary) returns the highest salary, and MIN(Salary) returns the lowest salary.
6. Grouping Data Query: Group data by a column and aggregate.
SELECT Department, COUNT(*) AS EmployeeCount FROM Employees GROUP BY Department;
SELECT Department, AVG(Salary) AS AverageSalary FROM Employees GROUP BY Department HAVING AVG(Salary) > 50000;
HAVING AVG(Salary) > 50000 filters groups to only include departments with an average salary greater than $50,000.
7. Joining Tables Query: Join two tables (e.g., Employees and Departments) on a common column. Assuming a Departments table:
CREATE TABLE Departments ( DepartmentID INT PRIMARY KEY, DepartmentName NVARCHAR(50) );
SELECT e.FirstName, e.LastName, d.DepartmentName FROM Employees e INNER JOIN Departments d ON e.DepartmentID = d.DepartmentID;
SELECT e.FirstName, e.LastName, d.DepartmentName FROM Employees e LEFT JOIN Departments d ON e.DepartmentID = d.DepartmentID;
LEFT JOIN includes all rows from Employees, with NULL for DepartmentName where there is no match in Departments.
8. Inserting Data Query: Insert a new row into a table.
INSERT INTO Employees (FirstName, LastName, BirthDate, HireDate) VALUES ('Emily', 'Davis', '1989-12-04', '2020-07-15');
Adds a new employee with the given values.
9. Updating Data Query: Update existing data in a table.
UPDATE Employees SET HireDate = '2021-01-01' WHERE LastName = 'Davis';
Updates the HireDate for employees with the last name 'Davis'.
10. Deleting Data Query: Delete specific rows from a table.
DELETE FROM Employees WHERE LastName = 'Davis'; Deletes rows where the LastName is 'Davis'.