Detailed_SQL_DDL_DML_Commands_Fixed
Detailed_SQL_DDL_DML_Commands_Fixed
CREATE DATABASE:
Creates a new database for storing tables and other database objects.
Syntax:
CREATE DATABASE database_name;
Example:
CREATE DATABASE SchoolDB;
CREATE TABLE:
Creates a new table with specified column names, data types, and constraints.
Syntax:
CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
...
);
Example:
CREATE TABLE Student (
StudentID INT PRIMARY KEY,
Name VARCHAR(50),
Age INT,
DepartmentID INT,
FOREIGN KEY (DepartmentID) REFERENCES Department(DepartmentID)
);
ALTER TABLE:
Modifies the structure of an existing table - add, remove, or alter columns.
Examples:
ALTER TABLE Student ADD Email VARCHAR(100);
ALTER TABLE Student DROP COLUMN Age;
ALTER TABLE Student ALTER COLUMN Name VARCHAR(100);
PRIMARY KEY:
A constraint that uniquely identifies each record in a table.
- Cannot contain NULL values.
- Usually defined on one or more columns.
Example:
PRIMARY KEY (StudentID)
A foreign key in one table points to a primary key in another table, establishing a relationship.
Example:
FOREIGN KEY (DepartmentID) REFERENCES Department(DepartmentID)
WHERE:
Adds conditions to a SELECT, UPDATE, or DELETE query to filter records.
Example:
SELECT * FROM Student WHERE Age > 17;
ORDER BY:
Sorts the result set by one or more columns.
- ASC for ascending (default), DESC for descending.
Example:
SELECT * FROM Student ORDER BY Name ASC;
GROUP BY:
Groups rows with the same value in specified columns.
Often used with aggregate functions (SUM, COUNT, AVG, etc.).
Example:
SELECT DepartmentID, COUNT(*) FROM Student GROUP BY DepartmentID;
INNER JOIN:
Returns only rows that have matching values in both tables.
Example:
SELECT Student.Name, Department.Name
FROM Student
INNER JOIN Department ON Student.DepartmentID = Department.DepartmentID;
SUM():
Returns the total sum of a numeric column.
Example:
SELECT SUM(Age) FROM Student;
COUNT():
Counts the number of rows or non-null entries in a column.
SQL DDL and DML Commands Explained
Examples:
SELECT COUNT(*) FROM Student; -- counts all rows
SELECT COUNT(Email) FROM Student; -- counts non-null emails
AVG():
Returns the average value of a numeric column.
Example:
SELECT AVG(Age) FROM Student;
INSERT INTO:
Adds new records to a table.
Syntax:
INSERT INTO table_name (column1, column2) VALUES (value1, value2);
Example:
INSERT INTO Student (StudentID, Name, Age)
VALUES (1, 'Kartik', 17);
DELETE FROM:
Deletes rows from a table based on a condition.
Syntax:
DELETE FROM table_name WHERE condition;
Example:
DELETE FROM Student WHERE StudentID = 1;
Note: Without WHERE, all rows are deleted.
UPDATE:
Modifies existing records in a table.
Syntax:
UPDATE table_name SET column1 = value1 WHERE condition;
Example:
UPDATE Student SET Age = 18 WHERE StudentID = 1;