Structured Query Language (SQL) is used to perform certain operations on the existing database. These SQL commands are mainly categorized into four categories as:
- DDL - Data Definition Language
- DQL - Data Query Language
- DML - Data Manipulation Language
- DCL - Data Control Language
Following are the SQL Command
- DDL (CREATE, DROP, ALTER AND TRUNCATE)
- DML (INSERT, UPDATE, DELETE, CALL, EXPLAIN CALL, LOCK)
- DQL - SELECT
- DCL - (GRANT, REVOKE)
DDL could be used to define the database schema.
- UNIQUE - The UNIQUE constraint ensures that all values in a column are different.
- NOT NULL - The NOT NULL constraint enforces a column to NOT accept NULL values.
- PRIMARY KEY - The PRIMARY KEY constraint uniquely identifies each record in a table.
- CHECK - The CHECK constraint is used to limit the value range that can be placed in a column.
- DEFAULT - The DEFAULT constraint is used to set a default value for a column.
- FOREIGN KEY - The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.
CREATE TABLE DEPARTMENTS (
dept_name INT NOT NULL PRIMARY KEY,
dept_building INT NOT NULL,
dept_budget INT,
);
CREATE TABLE STUDENTS (
dept_name INT NOT NULL,
student_id INT NOT NULL UNIQUE,
student_name varchar(255),
student_total_credit INT,
student_enronment_date DATE DEFAULT GETDATE(),
student_city varchar(255),
student_age INT,
CHECK (student_age>= 21 AND student_city= 'Bangalore'),
PRIMARY KEY (student_id),
FOREIGN KEY(dept_name) REFERENCES dbo.DEPARTMENTS(dept_name)
);
* First Lets ADD column called date of birth for students, before adding lets check the column description using below select command
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'STUDENTS'
ALTER TABLE STUDENTS
ADD DateOfBirth date;
same way we could use drop, rename, add constraints and drop constraints
ALTER TABLE STUDENTS
DROP COLUMN DateOfBirth;
sp_rename 'STUDENTS.[student_enronment_date]', 'student_enrollment_date','COLUMN';
Note: We cant use ALTER for renaming rather we have to use Transact-SQL
ALTER TABLE STUDENTS
ADD CONSTRAINT PK_dept_name PRIMARY KEY (dept_name);
ALTER TABLE STUDENTS
DROP CONSTRAINT PK_dept_name;
TRUNCATE TABLE STUDENTS;
DROP TABLE STUDENTS;
Note: The TRUNCATE TABLE command deletes the data inside a table, but not the table itself. The DROP TABLE command deletes a table in the database.
A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real tables in the database. Here we are creating view of students > 30
CREATE VIEW STUDENTGREATER30 AS
SELECT *
FROM STUDENTS
WHERE student_age > 30;