SQL Queries: Core Commands for Database Management
SQL (Structured Query Language) is the standard language for interacting with relational database management systems (RDBMS). Understanding SQL commands is essential for managing data, retrieving information, and maintaining the integrity of a database. This document outlines the fundamental SQL commands with detailed explanations and practical examples.
1. Data Definition Language (DDL): Defining the Database Structure
DDL commands are used to define and manage the structure of the database itself. This includes creating, altering, and deleting database objects like tables, indexes, and views.
CREATE DATABASE CompanyDB;
CREATE TABLE Employees ( EmployeeID INT PRIMARY KEY, FirstName VARCHAR(50) NOT NULL, LastName VARCHAR(50) NOT NULL, Department VARCHAR(50), Salary DECIMAL(10, 2) );
Employees
with columns for EmployeeID
, FirstName
, LastName
, Department
, and Salary
, specifying data types and constraints like PRIMARY KEY
and NOT NULL
.CREATE INDEX idx_LastName ON Employees (LastName);
This creates an index on the LastName
column of the Employees
table.ALTER TABLE Employees ADD HireDate DATE;
This adds a HireDate
column of type DATE
to the Employees
table.ALTER TABLE Employees MODIFY COLUMN Salary DECIMAL(12, 2);
This modifies the Salary
column to allow for larger salary values.ALTER TABLE Employees DROP COLUMN Department;
This removes the Department
column from the Employees
table.DROP DATABASE CompanyDB;
DROP TABLE Employees;
DROP INDEX idx_LastName ON Employees;
DELETE
and resets the auto-increment counter (if applicable). TRUNCATE TABLE Employees;
2. Data Manipulation Language (DML): Managing Data Within Tables
DML commands are used to manipulate the data within the database tables. This includes inserting, updating, deleting, and retrieving data.
INSERT INTO Employees (EmployeeID, FirstName, LastName, Department, Salary) VALUES (1, 'John', 'Doe', 'Sales', 50000.00);
INSERT INTO Employees VALUES (2, 'Jane', 'Smith', 'Marketing', 60000.00);
(Only works if you provide values for all columns in the correct order.)INSERT INTO Employees (EmployeeID, FirstName, LastName, Department, Salary) SELECT EmployeeID, FirstName, LastName, 'New Department', Salary FROM OldEmployees WHERE Department = 'Old Department';
This inserts employees from the OldEmployees
table into the Employees
table, but only those from the ‘Old Department’, changing the department to ‘New Department’ in the process.WHERE
clause to avoid unintentionally updating every row in the table. UPDATE Employees SET Salary = 55000.00 WHERE EmployeeID = 1;
This updates the salary of the employee with EmployeeID
1 to 55000.00. UPDATE Employees SET Salary = Salary * 1.10 WHERE Department = 'Sales';
This gives all employees in the Sales department a 10% raise.WHERE
clause to avoid deleting all rows from the table. DELETE FROM Employees WHERE EmployeeID = 1;
This deletes the employee with EmployeeID
1.DELETE FROM Employees WHERE Department = 'Finance' AND Salary < 40000;
This deletes all employees in the Finance department who earn less than $40,000.*
in production code; it’s better to explicitly specify the columns you need. SELECT * FROM Employees;
SELECT FirstName, LastName, Salary FROM Employees;
SELECT FirstName, LastName FROM Employees WHERE Department = 'Sales';
ASC
is ascending order (default), DESC
is descending order. SELECT FirstName, LastName, Salary FROM Employees WHERE Department = 'Sales' ORDER BY Salary DESC;
This retrieves the first name, last name, and salary of all employees in the Sales department, sorted by salary in descending order (highest salary first).SELECT DISTINCT Department FROM Employees;
This retrieves a list of all unique department names from the Employees table.SELECT COUNT(*) FROM Employees;
This returns the total number of employees in the Employees table.SELECT AVG(Salary), SUM(Salary), MIN(Salary), MAX(Salary) FROM Employees;
This returns the average, sum, minimum, and maximum salaries of all employees.SELECT Department, COUNT(*) FROM Employees GROUP BY Department;
This returns the number of employees in each department.SELECT Department, COUNT(*) FROM Employees GROUP BY Department HAVING COUNT(*) > 5;
This returns only those departments that have more than 5 employees.3. Data Control Language (DCL): Controlling Access to Data
DCL commands are used to control access to the database and its objects. These commands are often used by database administrators.
GRANT SELECT ON Employees TO 'user1'@'localhost';
This grants the SELECT
permission on the Employees
table to the user user1
from the localhost.REVOKE SELECT ON Employees FROM 'user1'@'localhost';
This revokes the SELECT
permission on the Employees
table from the user user1
from the localhost.4. Transaction Control Language (TCL): Managing Transactions
TCL commands are used to manage transactions, which are logical units of work that consist of one or more SQL statements. Transactions ensure data consistency and integrity.
START TRANSACTION; UPDATE Accounts SET Balance = Balance - 100 WHERE AccountID = 123; UPDATE Accounts SET Balance = Balance + 100 WHERE AccountID = 456; COMMIT; -- Makes these changes permanent.
ROLLBACK: Undoes all changes made during a transaction, reverting the database to its previous state.
START TRANSACTION; UPDATE Accounts SET Balance = Balance - 100 WHERE AccountID = 123; UPDATE Accounts SET Balance = Balance + 100 WHERE AccountID = 456; ROLLBACK; -- Cancels both updates, reverting the balance to its original values.
SAVEPOINT savepoint_name: Creates a point within a transaction to which you can rollback.
START TRANSACTION; UPDATE Accounts SET Balance = Balance - 100 WHERE AccountID = 123; SAVEPOINT sp1; UPDATE Accounts SET Balance = Balance + 100 WHERE AccountID = 456; ROLLBACK TO sp1; -- Rolls back only the second UPDATE statement. The first update remains. COMMIT;
Joins: Combining Data from Multiple Tables
Joins are essential for retrieving data from multiple related tables.
SELECT Employees.FirstName, Employees.LastName, Departments.DepartmentName FROM Employees INNER JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;
LEFT JOIN (or LEFT OUTER JOIN): Returns all rows from the left table, and the matching rows from the right table. If there is no match, the right table’s columns will contain NULL
values.
SELECT Employees.FirstName, Employees.LastName, Departments.DepartmentName FROM Employees LEFT JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;
RIGHT JOIN (or RIGHT OUTER JOIN): Returns all rows from the right table, and the matching rows from the left table. If there is no match, the left table’s columns will contain NULL
values.
SELECT Employees.FirstName, Employees.LastName, Departments.DepartmentName FROM Employees RIGHT JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;
FirstName
and LastName
will be NULL
.sql SELECT Employees.FirstName, Employees.LastName, Departments.DepartmentName FROM Employees FULL OUTER JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;
This retrieves all employees and all departments, regardless of whether they have a match.Subqueries: Queries Within Queries
A subquery is a query nested inside another query. Subqueries can be used in the SELECT
, FROM
, and WHERE
clauses.
SELECT FirstName, LastName FROM Employees WHERE DepartmentID IN (SELECT DepartmentID FROM Departments WHERE Location = 'New York');
This retrieves employees who work in departments located in New York.SELECT FirstName, LastName, (SELECT AVG(Salary) FROM Employees) AS AverageSalary FROM Employees;
This retrieves the first name, last name, and the average salary of all employees for each employee row.SELECT Department, AVG(Salary) FROM (SELECT Department, Salary FROM Employees WHERE Salary > 50000) AS HighEarners GROUP BY Department;
This finds the average salary for each department, considering only employees who earn more than $50,000.Other Important SQL Features:
AS
to rename columns or tables for brevity and clarity.UPPER()
, LOWER()
, SUBSTRING()
, CONCAT()
).NOW()
, DATE()
, YEAR()
, MONTH()
, DAY()
).ROW_NUMBER()
, RANK()
, LAG()
, LEAD()
).WITH
clause). CTEs help improve readability and can be used to break down complex queries into smaller, more manageable parts.This overview covers the core SQL commands and concepts necessary for managing databases effectively. Different database systems (MySQL, PostgreSQL, SQL Server, Oracle, etc.) may have slightly different syntax or additional features, so consulting the specific documentation for your RDBMS is always recommended. Understanding and mastering these commands will allow you to effectively store, retrieve, and manage data.
WordPress development has evolved significantly, and modern tooling plays a crucial role in creating efficient…
I. Project Overview The goal is to automate the process of notifying search engines (like…
1. Database Structure (MySQL) We'll need a database table to store information about our website's…
This explanation aims to provide a solid foundation for understanding the process and implementing your…
Okay, here's a comprehensive guide on building a real-time website chat script using PHP, HTML,…
Comprehensive guide on creating a simple website analytics system using PHP, HTML, CSS, JavaScript, and…