SQL Basics: 2 Sem, MSC
SQL Basics: 2 Sem, MSC
Disadvantages of SQL
• Cost
• Interface is Complex
• Partial Database control: business rules are hidden
SSS Shameem May/Apr-2022 MSc_BA, DoC
DIFFERENT TYPES OF COMMANDS
✓ DDL commands: -
To create and modify database objects - CREATE, ALTER, DROP
✓ DML commands: -
To manipulate data of a database objects- INSERT, DELETE, UPDATE
✓ DQL command: -
To retrieve the data from a database - SELECT
✓ DCL commands: -
To control the data of a database – GRANT, REVOKE
✓ TCL commands:-
To control and manage transactions – COMMIT, SAVEPOINT,
o CREATE command
o UPDATE command
o DELETE command
o SELECT command
o DROP command
o INSERT command
DELETE Command: helps in removing or erasing saved records from database tables.
SELECT Command: helps in accessing single/multiple rows from one/multiple tables of database
DROP Command: helps in deleting entire table, table view, and other objects from database.
• use databaseName;
• show TABLES;
• describe tableName;
column_name Datatype(size), . . . );
Example:
create table instructor
( ID varchar(5),
name varchar(20),
dept_name varchar(20),
salary numeric(8,2));
designer has to ensure that data entered by user has to be checked against these rules and allowed
to store if valid otherwise need to be rejected.
Integrity constraints guard against accidental damage to the database, by ensuring that
authorized changes to the database do not result in a loss of data consistency.
Example:
Data in some Column such as Phone_numeric is mandatory for user to enter.
Data in some Column such as Registration_numeric has to be Unique ( No duplicated allowed).
Data in some Column such as Registration_numeric is used to identify every student distinctly.
Valid range of Data for some Column such as Under_Gradate is BSc, B.Tech. BE.
A SB account must have a balance greater than 1000/-
Table Level Constraint.- Defined at the end after defining all the columns.
Multi-level Column.
– Assume that are two columns in the table say- Date_of_Birth and Date_of_Join.
not null -
primary key (A1, ..., An )
foreign key (Am, ..., An ) references r
Unique
Check
Default
dept_name varchar(20),
salary numeric(8,2) );
Example:
CREATE TABLE Student(
ID varchar(5) PRIMARY KEY,
Name Varchar(10),
Phone numeric(10) UNIQUE,
tot_credit numeric(2) );
Example:
Example:
CREATE TABLE BsnL_Customer (
CREATE TABLE Student(
Customer_ID numeric(7) PRIMARY KEY,
ID varchar(5) PRIMARY KEY,
Name varchar(10) NOT NULL,
Name Varchar(10),
Address varchar(20),
Phone numeric(10) UNIQUE,
Area_Code numeric(4),
Phone_Num numeric(6), tot_credit numeric(2) );
UNIQUE(Area_Code , Phone_Num ) );
from Emp
where regNo = ‘101’;
Enrollment can be done to only to those who are student, therefore SID column in Enrollment can have only values
which are present in SID in Student table → SID in Enrollment as Foreign key referencing Students
Note: In relation R, attribute A can’t contain a value which is not existing in attribute A of relation S.
In the example above , at this instance A in R can’t have a value a6 or a7 etc.
CREATE TABLE Courses (CID varchar (9) PRIMARY KEY , C_Name varchar(25) not null,
Credits numeric(2), Duration numeric(2));
After Creating Parent Table/s, create Child tables
CREATE TABLE Enrollment
( SID varchar (9) NOT NULL,
CNo varchar (9),
FOREIGN KEY (sid) REFERENCES students(sid),
FOREIGN KEY (Cno) References Courses(CID),
Year numeric (2) not null,
Grade varchar (2), Primary key (SID, CNO, Year) );
Parent(Master) Table:
CREATE TABLE Items( Item_name varchar(10), Comp_name varchar(10),
Price numeric(3),
PRIMARY KEY (Item_name, Comp_name) );
Child(Detail) Table
CREATE TABLE Transactions( It_name varchar(10), Comp_name varchar(10),
Tr_Date date, Qty numeric(3),
FOREIGN KEY(It_name, Comp_name) REFERENCES Items(Item_name,Comp_name));
EMP FACULTY
Attribute Datatype size Constraint
Attribute Datatype size Constraint
RegNo numeric 3 Primary key Faculty_ID numeric 3 Primary Key
Name Varchar 10 not null Name Varchar 10 not null
References with
Faculty_Advisor F.key referring Faculty Dept_ID Dept
DEPT
FACULTY
Attribute Datatype size Constraint
Faculty_ID numeric 3 Primary Key
Name Varchar 10 not null
References with
Dept_ID Dept
* constraint definition – maybe Primary key, Foreign key, Check, Unique, Not Null etc.
Example:
CREATE TABLE table_name(
column_name1 datatype(size), column_name2 datatype(size) …. ,
The DROP TABLE statement allows you to remove or delete a table from the database.
Syntax:
Adding Column
Syntax:
DROP a Column
Syntax:
ALTER TABLE table_name
DROP column_name;
RENAME a Table
Syntax:
ALTER TABLE table_name
RENAME TO New_table_name;
RENAME a Column
Syntax:
ALTER TABLE table_name
RENAME COLUMN old_column_name TO New_column_name;
Syntax:
ALTER TABLE table_name
ADD CONSTRAINT constraint_name UNIQUE( column1,column2,..columnn ) );
Removing Constraints
Syntax:
ALTER TABLE table_name
DROP CONSTRAINT constraint_name ;
Example: Assume that Person(Fname, Lname, Address) table is already created with (Fname,LName) as
Primary Key. Also a table Customer(Cust_Id, Cust_FName, Cust_Lname,Credits) is also created already.
Example: Assume that Person(Fname, Lname, Address,Phone) table is already created with
(Fname,LName) as Primary Key and Unique constraint on Phone with constraint name –
‘PHONE_UNQ’. Rename the PHONE_UNQ to UNIQUE_PHONE.
Syntax:
ALTER TABLE table_name
ADD CONSTRAINT constraint_name PRIMARY KEY (column1, column2, ... column_n) ;
Example: Assume that Person(Fname, Lname, Address) table is already created. Add constraint to
Person table to make (FName,LName) column as Primary Key.
ALTER TABLE Person
ADD CONSTRAINT F_L_Name_PK PRIMARY KEY (FName, LName);
Example: ensure that Type of Courses offered by a Department is any one of MCA, MTech, MS.
Example: Add constraint to Students table to check Mark2 column takes values only in
the range 0 to 100.
Example:
Create a table CANDIDATES(CandtID, Name, Branch) appearing for entrance exam at MIT. Candidate
numbers must be Unique & every candidate numeric must start with MIT.
Name varchar(10),
Branch varchar(10));
Create a table PRODUCT(ProdID, Name, Price) to store products of JOI company. Product numbers must be of
the form JOI- followed by any 5 characters(use 5 under score character).
Name varchar(10),
Price numeric(5));
Create a table PRODUCT(ProdID, Name, Price) to store products of JOI company. Product numbers must be
of the form JOI- followed by any 5 characters(use 5 under score character).
Table CANDIDATES(CandtID, Name, Branch) for appearing entrance exam at MIT. Candidate
numbers must be Unique & every candidate numeric must start with MIT. User must enter Branch in
Capital letters only.
CREATE TABLE CANDIDATE(
CandtId varchar(7) PRIMARY KEY CHECK (CandtId LIKE 'MIT%’),
Name varchar(10),
Branch varchar(10) CHECK(Branch=UPPER(Branch)));
INSERT INTO CANDIDATE VALUES('MIT1021', 'Raghu', 'COMP.SC’); accepted
CUSTOMER
Attribute Datatype size Constraint Constraint Name
CustNo numeric 3 Primary key Pkey_Cust_numeric
Unique , Can't UNQ_Phone;
Phone numeric 10 be Null Ph_NoNULL
email varchar 20 Unique
City varchar 20 BNG/MUB/CHN Valid_City
ACCOUNT
Head varchar(10));
In_take_stud numeric(2),
Note the constraint name and error numbers displayed when data being inserted violates constraint
Head varchar(10));
Course_Type varchar (8) CONSTRAINT Course_Chk_Type CHECK( Course_Type IN( 'MCA','MTech ', 'BTech', 'MS')),
In_take_stud numeric(2),
Note the constraint name displayed when data being inserted violates constraint
Syntax-
INSERT INTO table_name VALUES (value1,value2,….)
Syntax-
INSERT INTO table_name(column1,column2,..) VALUES (value1,value2,….)
Example: Insert a record into Course table having values to Course_id, Dept_Name columns only.
Course(Course_id, title, Dept_Name, Credits)
It is equivalent to –
insert into course values (’CS-438’, NULL, ’Comp. Sci.’, NULL);
STUD Rollno Name Course Dept MARKS Rno Course Marks Attendanc
101 Ajit Algorithms CS e
102 Ravi IoT IT
Example: Insert Rollno and course information of students enrolled to MCA department into MARKS relation.
INSERT INTO MARKS(RNo, Course) SELECT Rollno, Course FROM STUD WHERE Dept=‘MCA’;
Example: Consider the tables Student(Id, Name, D_name, tot_cred) and Instructor(Id, Name,
Dept_name, Salary). Add all instructors to the student relation with tot_creds set to 0
insert into student
select ID, name, dept_name, 0
from instructor;
OR
insert into student(ID,name,D_name)
select ID, name, dept_name
from instructor;
The select from where statement is evaluated fully before any of its results are inserted into the relation
Example: Consider the table Instructor(Id, Name, Dept_name, Salary). Increase the salary of
instructor with ID I201 by 10%.
UPDATE instructor
SET salary = salary * 1.03
WHERE salary > 100000;
UPDATE instructor
SET salary = salary * 1.05
WHERE salary <= 100000;
Syntax:
DELETE FROM table_name WHERE condition;
Example:
• Delete all instructors
delete from instructor
Example:
• Delete all tuples in the instructor relation for those instructors associated with a department
located in the ‘Watson’ building.
String Functions
LEFT, RIGHT
LENGTH / CHAR_LENGTH / CHARACTER_LENGTH
CONCAT, REPLACE, REVERSE
LOWER, UPPER
Child(Detail) Table
Any Delete operation on Parent table Department first deletes dependent records in
EMP(child) table automatically.
Thus Delete operation restriction on Foreign key constraint is get resolved automatically.
Child(Detail) Table
When a record is deleted from Department(Parent) table it will not delete dependent
records in the EMP(child) table.
Thus removes dependency of corresponding records in child table on table records being
deleted in the Parent table.