Chapter-07 - SQL
Chapter-07 - SQL
Chapter-07 - SQL
SQL
For your Reference
SQL Components: DDL, DCL, & DML
• SQL is a very large and powerful language, but every type of SQL
statement falls within one of three main categories (or sub-
languages):
• Data Definition Language (DDL) for creating a DB
e.g. CREATE, DROP, ALTER
• Data Control Language (DCL) for administering a DB
e.g. GRANT, DENY, USE
• Data Manipulation Language (DML) to access a DB
e.g. SELECT, INSERT, UPDATE, DELETE
Relational Tables Can Answer
Many Queries
Student Enrolment Course
• How many courses are there & what are their names?
• Which students are enrolled for Java?
• How many students take 3 or more courses?
SQL - Structured Query Language
• Structured programming?
No! - Structured English (from ‘SEQUEL’)
(for Structured English QUEry Language)
• Creating tables…
• Character strings
• Fixed length: CHAR(n) or CHARACTER(n)
• Variable length: VARCHAR(n)
• Date and Time: DATE and TIME data types are supported in SQL2
Structured Query Language (contd.)
Example…
CREATE TABLE Student (
name CHAR(20),
address CHAR(25),
age INTEGER,
gpa REAL
);
Structured Query Language (contd.)
• Primary Key constraint
• PRIMARY KEY
• Alternative:
CREATE TABLE Student (
stdid CHAR (10),
name CHAR(20),
address CHAR(25),
age INTEGER,
gpa REAL,
PRIMARY KEY (stdid)
);
Structured Query Language (contd.)
• Alternative:
CREATE TABLE Grade (
subjectId CHAR(4),
stdid CHAR(10),
grade CHAR(2),
PRIMARY KEY(subjectId,stdid),
CONSTRAINT fk_Grade FOREIGN KEY(stdid)
REFERENCES Student(stdid)
);
Structured Query Language (contd.)
• Dropping tables
* SQL Server 2000 has only RESTRICT option which is the default
Structured Query Language (contd.)
• Altering tables…
• ALTER TABLE can be used to add or drop a column, change a column
definition, and adding or dropping table constraints
• For example…
-- The new column has null values. Hence, NOT NULL cannot be used here
Structured Query Language (contd.)
• Dropping a column…
• We can modify data using the following three commands: INSERT, DELETE and
UPDATE
• INSERT statement:
• Inserting a single row
*The order of values must be the same as in the CREATE TABLE statement
Structured Query Language (contd.)
* Only the columns are specified are filled with values. Unspecified
columns are filled with NULL if there is no default values.
Structured Query Language (contd.)
UPDATE <table>
SET <column> = <expression>
WHERE <selection condition>
Structured Query Language (contd.)