You are on page 1of 90

IT 220: Database

Management System

Note: Please refer course book to explore further knowledge.


Agenda
 Introduction to SQL
 DDL
 Domain Types in SQL , Schema Definition in SQL
 DML
 Manipulation Language:
 Set Operations
 Aggregate Functions
 Nested Queries
 Database Modification
 Join Relations
 Embedded SQL , Dynamic SQL
 TCL
Structured Query Language(SQL)
IBM Sequel language developed as part of System R project at the
IBM San Jose Research Laboratory
Renamed Structured Query Language (SQL)
ANSI and ISO standard SQL:
• SQL-86
• SQL-89
• SQL-92
• SQL:1999 (language name became Y2K compliant!)
• SQL:2003
SQL is a standardized query language for requesting information from
a database
Cont…
The SQL Languages has several Parts
DDL
DML
TCL
Authorization
Embedded SQL & Dynamic SQL
Integrity
View Definition
Data Definition Languages (DDL)
SQL statements that can be used either interactively or
within programming language source code to define
databases and their components.
DDL Command
CREATE: use to create a table
ALTER: use to change table definition
DROP: use to delete the table
RENAME: use to modify table name
TRUNCATE: used to delete data from table
Domain Types in SQL (Basic)
char(n): Fixed length character string, with user-specified length n.
varchar(n): Variable length character strings, with user-specified maximum length
n.
Int: Integer (a finite subset of the integers that is machine-dependent).
Smallint: Small integer (a machine-dependent subset of the integer domain type).
numeric(p,d): Fixed point number, with user-specified precision of p digits, with d
digits to the right of decimal point. (ex., numeric(3,1), allows 44.5 to be stores
exactly, but not 444.5 or 0.32)
real, double precision: Floating point and double-precision floating point
numbers, with machine-dependent precision.
float(n): Floating point number, with user-specified precision of at least n digits.
Date: a calendar date, containing four digit year, month, and day of the month.
Time: the time of the day in hours, minutes, seconds,
Data Type and Storage
Bigint: 8 bytes: signed
Int: 4 bytes: signed
Smallint: 2 bytes: signed
Tinyint: 1 bytes: unsigned
Char: O char to 8000 chars (Define Width): fix width
Varchar: O char to 8000 chars (2 bytes +no. of chars): variable width
Varchar(max): O char to 2^31 chars (2 bytes +no. of chars): variable width
Text: O char to 214748347 chars (4 bytes +no. of chars): variable width
Nchar: O char to 4000 chars (Define width X 2): Fix width (Unicode)
Nvarchar: O char to 4000 chars. (Unicode)
Nvarchar (max):O char to 2^30 chars (Unicode)
Schema Definition in SQL
We define an SQL relation by using create table command.
In the given relation there are three attributes student_id which is
integer of maximum length 5, name, which is variable character of
maximum length 15, address, which is variable character of maximum
length 15. The table also specifies that std_id is a primary key of the
students relation.

Create table students


(
std_id integer(5),
name varchar(15),
address varchar (15),
Primary key (std_id
));
Cont…
The general structure of create table command is:

Create table <table_name>


(
attributes1 domain type1,
attributes2 domain type2,
……………. ,
attributesn domain typen

(integrity constraint1)
………….,
(integrity constraintk));
Integrity constraint in create table
Not null create table department(
dept_name varchar (20),
Primary key
building varchar (15),
Foreign key budget numeric (12,2),
Example: primary key (dept name));

create table instructor (


ID char(5),
name varchar(20) not null,
dept_name varchar(20),
salary numeric(8,2),
primary key (ID),
foreign key (dept_name) references
department);
Note: primary key declaration on an attribute automatically
ensures not null

Cont…
create table student (
ID varchar(5),
name varchar(20) not null,
dept_name varchar(20),
tot_cred numeric(3,0),
primary key (ID),
foreign key (dept_name) references department);

 create table takes (


ID varchar(5),
course_id varchar(8),
sec_id varchar(8),
semester varchar(6),
year numeric(4,0),
grade varchar(2),
primary key (ID, course_id, sec_id, semester, year) ,
foreign key (ID) references student,
foreign key (course_id, sec_id, semester, year) references section);
 Note: sec_id can be dropped from primary key above, to ensure a student cannot be
registered for two sections of the same course in the same semester
Cont…
 create table course (
course_id varchar(8),
title varchar(50),
dept_name varchar(20),
credits numeric(2,0),
primary key (course_id),
foreign key (dept_name) references department);
Cont…
ALTER :The SQL ALTER TABLE statement is used to add, modify, or drop/delete
columns in a table. The SQL ALTER TABLE statement is also used to rename a table.
Adding attributes to existing table

Syntax: alter table <table name> add attribute_name domain_type


Example: alter table student add gender varchar(10);

Adding constraint or changing data type to existing attributes

Syntax: alter table <table_name> alter column <column_name>


<domain type> <constraint>
Example: alter table student alter column address varchar(25) not
null;
Cont…
Dropping column from table

Syntax: alter table <table_name> drop column


<column_name>
Example: alter table student drop column gender;

Rename column in table

Mysql Syntax: alter table <table_name> change <old


column> to <new column>
Example: alter table student change address to add
Cont…
DROP: Deleting table
Syntax: drop table <table name>
Example: drop table student

RENAME: Changing table name


Mysql Syntax: alter table < old table name> rename
to <new table name>
Example: change the table name student to students
alter table student rename to students.
Cont…
TRUNCATE: Deleting all data from table
Syntax: truncate table <table name>
Example: truncate table student
Data Manipulation Languages (DML)
• A data-manipulation language (DML) is a language that enables users
to access or manipulate data as organized by the appropriate data
model.

• DML Command

INSERT: insertion of new information to the database.

SELECT: retrieve information from database

DELETE: delete information from database

UPDATE: modify or update values in database


Cont…
INSERT
INSERT into <<table_name>> values <v1,v2,v3….vn)
Example:
Insert into students values (1, ‘Ram Bahadur’,
‘Pokhara’)
SELECT
SELECT * from <<table_name>>
Example:
Select * from students
Select name from students
Cont…
DELETE
DELETE <attribute> from <table_name> where
<condition>
Example:
Delete from students where roll=1
UPDATE
UPDATE <table_name> set attribute=<tuple> where
condition
Example:
Update students set name=‘Krishna’ where roll=1
SELECT, WHERE, FROM CLAUSE
Select Clause: retrieve the specified column from the table.

Where Clause: specifies some condition on row to retrieve data.

From Clause: is a list of the relations to be accessed in the evaluation


of the query.
A typical SQL query has the form:
Select A1, A2, A3, …….., An
From R1, R2, R3, ……., Rn
Where P;
String Operation
In SQL strings are enclosed in the single quotes.

Any character having single quote can be specified by two


single quotes. Eg: its’okey can be written as its’’okey.
SQL String Functions
We can use UPPER(string) for convert string into upper case, LOWER
(string) form convert string into lower case, LEN(string) to retrieve
length of given string.
Eg: select upper(name) from table name;
Concat (): Returns the string that results from concatenating the
arguments.
Eg: Select concat(‘Ra’, ‘Jes’, ‘h’)returns: Rajesh.
Eg: select concat (first_name, ‘ ’, middle_name, ‘ ’, last_name) from
table
Cont..
LEFT(str, len): Returns the leftmost len characters from the string str,
or NULL if any argument is NULL.
Eg: select left (‘nepal’, 3) , return : nep
RIGHT(str, len): Returns the leftmost len characters from the string
str, or NULL if any argument is NULL.
Eg: select right (‘nepal’, 3) , return : pal
REPLICATE(str,count): Returns a string consisting of the string str
repeated count times. If count is less than 1, returns an empty string.
Returns NULL if str or count are NULL.
Eg: Select replicate(‘MSSQL ’, 3) , returns: display 3 times MSSQL
Cont
REVERSE(str): Returns the reverse of the given string.
Eg: select reverse(‘nepal’) , return : lapen
SUBSTRING(str, from, size): Returns the string from the specified
point upto given size.
Eg: select substring(‘nepal’,3,3) , return : pal
ASCII(char): Returns the ascii value of the character
Eg: select ascii(‘A’) , return : 65
LEN (str): Returns the length of the characters
Eg: select len(‘nepal’) , return : 4
Some Important Math Functions
Pi() : return the value of pi. Eg: select pi();
Power(base, exponent): return the value of a number raised to the power
of another number.
Eg: select power(2,3) ; return:8
Rand(): return random decimal number between 0 and 1.
Eg: select rand()
Round (number, decimal point): rounds a number to a specified number of
decimal places.
Eg: select round(102.5888,2); return 102.590
Floor(): returns the largest integer value that is equal to or less than given
value. Eg: select floor(23.75) return 23
Ceiling(): returns the smallest integer value that is equal to or greater than
given value. Eg: select floor(23.25) return 24
Some useful Math Functions
Sqrt(number) : return the square root of number. Eg: select sqrt(64) : return 8
square(num): return the square of a given number.
Eg: select square(3) ; return:9
Rand(): return random decimal number between 0 and 1.
Eg: select rand()
Round (number, decimal point): rounds a number to a specified number of
decimal places.
Eg: select round(102.5888,2); return 102.590
Floor(): returns the largest integer value that is equal to or less than given
value. Eg: select floor(23.75) return 23
Ceiling(): returns the smallest integer value that is equal to or greater than
given value. Eg: select floor(23.25) return 24
Some useful Date function
Getdate(): return current date and time.
Eg: select getdate()
Datediff(year, date1, date2): return the difference between two date
in year
Eg: select datediff(year, ‘2017-01-23’, ‘2020-05-25’) return: 3 years
Eg: select datediff(month, ‘2017-01-23’, ‘2017-10-25’) return: 9 months
Eg: select datediff(day, ‘2017-01-23’, ‘2017-02-23’) return: 31 days
Eg: select datediff(hh, ‘2017-01-23’, ‘2017-02-23’) return: 744 hours
Eg: select datediff(mi, ‘2017-01-23’, ‘2017-02-23’) return: 31 days
Eg: select datediff(ss, ‘2017-01-23’, ‘2017-02-23’) return:44640 minutes
Eg: select datediff(ms, ‘2017-01-23’, ‘2017-01-24’) return: 86400000 ms
Cont…
DATEPART(interval,date): returns a specified date.
Eg: select datepart(year, ‘2016-4-12’) : return 2016
SYSDATETIME(): returns sql server date time.
Eg: select sysdatetime()
Ordering the Display of Tuples
Ascending Order: to retrieve the data from database in ascending
order we use ASC
Eg: select * from students order by name ASC;

Descending Order: to retrieve the data from database in ascending


order we use DESC
Eg: select * from students order by name DESC;
Null Operation
Null values present special problems in relational operations,
including arithmetic operations, comparison operations, and set
operations.
if a query has an expression r.A+ 5, and r.A is null for a particular
tuple, then the expression result must also be null for that tuple.
Comparisons involving nulls are more of a problem. For example,
consider the comparison “1 < null”. It would be wrong to say this is
true since we do not know what the null value represents.
the predicate in a where clause can involve Boolean operations such
as and, or, and not on the results of comparisons, the definitions of
the Boolean operations are extended to deal with the value
unknown.
AND/ OR/ NOT
and: The result of true and unknown is unknown, false and unknown is false,
while unknown and unknown is unknown.
 SELECT * from Emp WHERE salary < 10000 AND age > 25
 The above query will return records where salary is less than 10000 and age greater
than 25.
 or: The result of true or unknown is true, false or unknown is unknown, while
unknown or unknown is unknown.
 SELECT * from Emp WHERE salary > 10000 OR age > 25
 The above query will return records where either salary is greater than 10000 or age
greater than 25.
not: The result of not unknown is unknown.
SELECT * from Emp WHERE not salary = 10000
Aggregate Functions
Aggregate Functions: functions that take a collection (a set or
multiset) of values as input and return a single value.
Average: avg() : return average value under the given condition.
Example :
Select avg(salary) from teacher where
dept_name=‘IT Dept’;
Minimum: min() : return smallest value under the given condition.
Example :
Select min(salary) from teacher where
dept_name=‘IT Dept’;
Cont…
Maximum: max() : return largest value under the given condition.
Example :
Select max(salary) from teacher where
dept_name=‘IT Dept’;

Total: sum(): return the total (sum) of the given row under given
condition
Example :
Select sum(salary) from teacher where
dept_name=‘IT Dept’;
Cont…
Count: count() : count the total no. of tuple in specified rows.
Example :Select count(teacher_id) from teacher where dept_name=‘IT
Dept’;

Note: You can use multiple condition in aggregate function and use ‘distinct’
keyword to remove duplicate values in count ().
** Aggregation with null values: count () ignore null values
Distinct keyword

• The distinct keyword is used with Select statement to retrieve unique


values from the table.
• Distinct removes all the duplicate records while retrieving from database.
• Syntax for DISTINCT Keyword
• SELECT distinct column-name from table-name;
• Example
• Select distinct(Fname) from student;
• Select distinct(age) from student;
• Select distinct(lname)from student;
Example
• Consider the following Emp table.
Eid name age salary

401 Anu 22 5000

402 Shane 29 8000

403 Rohan 34 10000

404 Scott 44 10000

405 Tiger 35 8000

• select distinct salary from Emp;


• The above query will return only the unique salary from Emp table
Salary

5000

8000

10000
Example to Perform Simple Calculations
using Select Query
• Consider the following Employee table eid Name age salary

101 Adam 26 5000

102 Ricky 42 8000

103 Abhi 22 10000

104 Rohan 35 5000

• SELECT eid, name, salary+3000 from Employee;


• The above command will display a new column in the result, showing 3000 added into existing
salaries of the employees.
eid Name salary+3000

101 Adam 8000

102 Ricky 11000

103 Abhi 13000

104 Rohan 8000


Like Clause
• Like clause is used as condition in SQL query.
• Like clause compares data with an expression using wildcard operators.
• It is used to find similar data from the table.
• Wild Card operators:
• There are two wildcard operators that are used in like clause in mysql.
 Percent sign % : represents zero, one or more than one character.
 Underscore sign _ : represents only one character. ( In some
implementations ? Is used.)
Example of LIKE clause
• SELECT * from Student where s_name like 'A%';
• The above query will return all records where s_name starts with character
'A’.
• SELECT * from Student where s_name like '_d%';
• The above query will return all records from Student table where s_name
contain 'd' as second character.
• SELECT * from Student where s_name like '%x';
• The above query will return all records from Student table where s_name
contain 'x' as last character.
SQL Alias
• Alias is used to give an alias name to a table or a column. This is quite
useful in case of large or complex queries. Alias is mainly used for giving
a short alias name for a column or a table with complex names.
• Syntax of Alias for table names,
• SELECT column-name from table-name as alias-name
• Following is an Example
• SELECT * from Employee_detail as ed;
• Alias syntax for columns will be like,
• SELECT column-name as alias-name from table-name
• Example using alias for columns,
• SELECT customer_id as cid from Emp;
SQL View
• A view in SQL is a logical subset of data from one or more tables. View is used to
restrict data access.
• Syntax for creating a View,
• CREATE or REPLACE view view_name AS SELECT column_name(s) FROM table_name
oid
WHERE condition
order_name previous_balance customer

11 ord1 2000 Alex

12 ord2 1000 Adam

13 ord3 2000 Abhi

14 ord4 1000 Adam

15 ord5 2000 Alex

• CREATE or REPLACE view sale_view as select * from Sale where customer = 'Alex';
SQL View
• Example of Displaying a View
• Syntax of displaying a view is similar to fetching data from table using
Select statement.
• SELECT * from sale_view;
• Force View Creation
• force keyword is used while creating a view. This keyword force to create View
even if the table does not exist. After creating a force View if we create the
base table and enter values in it, the view will be automatically updated.
• Syntax for forced View is,
• CREATE or REPLACE force view view_name AS SELECT column_name(s) FROM
table_name WHERE condition
SQL View
• Update a View
• Update command for view is same as for tables.
• Syntax to Update a View is,
• UPDATE view-name set value WHERE condition;
• If we update a view it also updates base table data automatically.
• Read-Only View
• We can create a view with read-only option to restrict access to the view.
• Syntax to create a view with Read-Only Access
• CREATE or REPLACE force view view_name AS SELECT column_name(s) FROM
table_name WHERE condition with read-only
• The above syntax will create view for read-only purpose, we cannot Update or
Insert data into read-only view. It will throw an error.
SQL View
• There are two types of view,
• Simple View
• Complex View
Simple View Complex View

Created from one table Created from one or more table

Does not contain functions Contain functions

Does not contain groups of data Contains groups of data


Group By Clause
• Group by clause is used to group the results of a SELECT query based on
one or more columns.
• It is also used with SQL functions to group the result from one or more
tables.
• The group by statement is used with aggregate functions to group the
result set by one or more than one column.
• Syntax.
SELECT column_name, function(column_name)
FROM table_name
WHERE condition
GROUP BY column_name
Example of Group by in a Statement
• Consider the following Emp table. Eid Name age salary

401 Anu 22 9000

402 Shane 29 8000

403 Rohan 34 6000

404 Scott 44 9000

405 Tiger 35 8000

• Here we want to find name and age of employees grouped by their salaries
• SQL query for the above requirement will be,
SELECT name, age Name age

from Emp group by salary Rohan 34

Shane 29

Anu 22
Example of Group by in a Statement with
WHERE clause
• Consider the following Emp table
eid name Age salary

401 Anu 22 9000

402 Shane 29 8000

403 Rohan 34 6000

404 Scott 44 9000

• SQL query 405 Tiger 35 8000

select name, salary


from Emp Name Salary

where age > 25 Rohan 6000

group by salary Shane 8000

Scott 9000
Group By clause
Example:
Select count(student_id), college_name from
college group by college_name;

Select count(student_id), college_name from


college group by college_name order by
count(student_id) desc;
Having Clause
Having clause is used in SQL because “where” keyword could not be
used with aggregate function.
Syntax:
Select column_name(n)
from table name
Where condition
Group by column_name(n)
Having condition
Example:
Select count (sid),lastname from student group
by lastname having count (sid)<5;
Example of HAVING Statement
• Consider the following Sale table.
oid order_name previous_balance customer

11 ord1 2000 Alex

12 ord2 1000 Adam

13 ord3 2000 Abhi

14 ord4 1000 Adam

15 ord5 2000 Alex

• Suppose we want to find the customer whose previous_balance sum is more than 1000.
• We will use the below SQL query,
• SELECT * from sale group customer having sum(previous_balance) > 1000
oid order_name previous_balance customer

11 ord1 2000 Alex


SQL Constraints
• SQL Constraints are rules used to limit the type of data that can go into a table, to maintain
the accuracy and integrity of the data inside table.
• If there is any violation between the constraint and the data action, the action is aborted.
• Constraints can be column level or table level.
• Column level constraints apply to a column,
• Table level constraints apply to the whole table.
• Constraints can be specified when the table is created with the CREATE TABLE statement, or
after the table is created with the ALTER TABLE statement.
• Syntax
CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
...........
ColumnN data tye,
Constraint constraint_name constraint_type field
);
SQL Constraints
• NOT NULL - Ensures that a column cannot have a NULL value
• UNIQUE - Ensures that all values in a column are different
• PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely
identifies each row in a table
• FOREIGN KEY - Uniquely identifies a row/record in another table
• CHECK - Ensures that all values in a column satisfies a specific condition
• DEFAULT - Sets a default value for a column when no value is specified
• INDEX - Used to create and retrieve data from the database very quickly
SQL NOT NULL Constraint
• By default, a column can hold NULL values.
• The NOT NULL constraint enforces a column to NOT accept NULL values.
• This enforces a field to always contain a value, which means that you cannot
insert a new record, or update a record without adding a value to this field.
• SQL NOT NULL on CREATE TABLE
• Example
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);
• SQL NOT NULL on ALTER TABLE
• Example
ALTER TABLE Persons
MODIFY Age int NOT NULL;
SQL UNIQUE Constraint
• The UNIQUE constraint ensures that all values in a column are different.
• Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness
for a column or set of columns.
• A PRIMARY KEY constraint automatically has a UNIQUE constraint.
• However, you can have many UNIQUE constraints per table, but only one PRIMARY
KEY constraint per table.
• SQL UNIQUE Constraint on CREATE TABLE
• Example
CREATE TABLE Persons (
ID int UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
SQL UNIQUE Constraint
• To name a UNIQUE constraint, and to define a UNIQUE constraint on multiple columns, use the
following SQL syntax:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT UC_Person UNIQUE (ID,LastName)
);
• SQL UNIQUE Constraint on ALTER TABLE
• To create a UNIQUE constraint on the "ID" column when the table is already created, use the following SQL:
ALTER TABLE Persons
ADD UNIQUE (ID);
ALTER TABLE Persons
ADD CONSTRAINT UC_Person UNIQUE (ID)
• DROP a UNIQUE Constraint
• To drop a UNIQUE constraint, use the following SQL:
ALTER TABLE Persons
DROP CONSTRAINT UC_Person;
SQL PRIMARY KEY Constraint
• The PRIMARY KEY constraint uniquely identifies each record in a table.
• Primary keys must contain UNIQUE values, and cannot contain NULL values.
• A table can have only ONE primary key; and in the table, this primary key can
consist of single or multiple columns (fields).
• SQL PRIMARY KEY on CREATE TABLE
• Example
CREATE TABLE Persons (
ID int NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
SQL PRIMARY KEY Constraint
• PRIMARY KEY constraint on multiple columns
• Example
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT PK_Person PRIMARY KEY (ID,LastName)
);
• SQL PRIMARY KEY on ALTER TABLE
• Example
ALTER TABLE Persons
ADD PRIMARY KEY (ID);
ALTER TABLE Persons
Add CONSTRAINT PK_Person PRIMARY KEY (ID,LastName)
• DROP a PRIMARY KEY Constraint
• Example
ALTER TABLE Persons
DROP CONSTRAINT PK_Person;
SQL FOREIGN KEY Constraint
• A FOREIGN KEY is a key used to link two tables together.
• A FOREIGN KEY is a field (or collection of fields) in one table that
refers to the PRIMARY KEY in another table.
• The table containing the foreign key is called the child table, and the
table containing the candidate key is called the referenced or parent
table.
• SQL FOREIGN KEY on CREATE TABLE
• Example
CREATE TABLE Orders (
OrderID int NOT NULL PRIMARY KEY,
OrderNumber int NOT NULL,
PersonID int FOREIGN KEY REFERENCES Persons(PersonID)
);
SQL FOREIGN KEY Constraint
• FOREIGN KEY constraint on multiple columns
• Example
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
CONSTRAINT FK_PersonOrder FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);
• SQL FOREIGN KEY on ALTER TABLE
• Example
ALTER TABLE Orders
ADD CONSTRAINT FK_PersonOrder
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);
• DROP a FOREIGN KEY Constraint
• Example
ALTER TABLE Orders
DROP CONSTRAINT FK_PersonOrder;
SQL FOREIGN KEY Constraint
• Behaviour of Foreign Key Column on Delete
• There are two ways to maintain the integrity of data in Child table, when a particular record is deleted in
main table. When two tables are connected with Foreign key, and certain data in the main table is
deleted, for which record exit in child table too, then we must have some mechanism to save the
integrity of data in child table.

• On Delete Cascade :
• This will remove the record from child table, if that value of foreign key is deleted from the main table.
• On Delete Null :
• This will set all the values in that record of child table as NULL, for which the value of foreign key is
seleted from the main table.
• If we don't use any of the above, then we cannot delete data from the main table for which
data in child table exists. We will get an error if we try to do so.
ERROR : Record in child table exist
SQL CHECK Constraint
• The CHECK constraint is used to limit the value range that can be placed in a column.
• If we define a CHECK constraint on a single column it allows only certain values for this column.
• If we define a CHECK constraint on a table it can limit the values in certain columns based on values in other columns
in the row.
• SQL CHECK on CREATE TABLE
• Example
• MySQL:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CHECK (Age>=18)
);
• SQL Server / Oracle / MS Access:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int CHECK (Age>=18)
);
SQL CHECK Constraint
• Defining a CHECK constraint on multiple columns
• Example
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255),
CONSTRAINT CHK_Person CHECK (Age>=18 AND City like'Kath%’)
);

• SQL CHECK on ALTER TABLE


• Example
ALTER TABLE Persons
ADD CHECK (Age>=18);
ALTER TABLE Persons
ADD CONSTRAINT CHK_PersonAge CHECK (Age>=18 or City in(‘Kathmandu’,’Lalitpur’);
ALTER TABLE Persons
ADD CONSTRAINT CHK_PersonAge CHECK (Age>=18 and City=’Lalitpur’);

• DROP a CHECK Constraint


• SQL Server / Oracle / MS Access:
ALTER TABLE Persons DROP CONSTRAINT CHK_PersonAge;
• MySQL:
ALTER TABLE Persons DROP CHECK CHK_PersonAge;
SQL DEFAULT Constraint
• The DEFAULT constraint is used to provide a default value for a column. The default value
will be added to all new records If no other value is specified.
• SQL DEFAULT on CREATE TABLE
• Example
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT ‘Kathmandu’ );
• Example
CREATE TABLE Orders (
ID int NOT NULL,
OrderNumber int NOT NULL,
OrderDate date DEFAULT GETDATE() );
SQL DEFAULT Constraint
• SQL DEFAULT on ALTER TABLE
• MySQL:
ALTER TABLE Persons
ALTER City SET DEFAULT ‘Kathmandu';
• SQL Server:
ALTER TABLE Persons
ADD CONSTRAINT df_City
DEFAULT ‘Kathmandu' FOR City;
• MS Access:
ALTER TABLE Persons
ALTER COLUMN City SET DEFAULT ‘Kathmandu';
• Oracle:
ALTER TABLE Persons
MODIFY City DEFAULT ‘Kathmandu’;
• DROP a DEFAULT Constraint
• MySQL:
ALTER TABLE Persons
ALTER City DROP DEFAULT;
• SQL Server / Oracle / MS Access:
ALTER TABLE Persons
ALTER COLUMN City DROP DEFAULT;
AUTO INCREMENT Field
• Auto-increment allows a unique number to be generated automatically
when a new record is inserted into a table.
• Example for MySQL
CREATE TABLE Persons (Personid int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL, FirstName varchar(255),Age int,
PRIMARY KEY (Personid) );
• Example for SQL Server
CREATE TABLE Persons ( Personid int IDENTITY(1,1) PRIMARY KEY, LastName
varchar(255) NOT NULL, FirstName varchar(255), Age int);
Note: To specify that the "Personid" column should start at value 10 and increment
by 5, change it to IDENTITY(10,5).
IN
• It allows to specify multiple values in where clause
Select column_name(s) from tablename where
column_name IN (value1,value2……);
Select * from student where s_address in(‘Ktm’,’Bkt’,’Ptn’);
Select * from student where s_address not
in(‘Ktm’,’Bkt’,’Ptn’);
Select column_name(s) from tablename where
column_name IN (select column from table name where
condition);
Between
• Between operator selects value within a given range.
• The value can be number, text or date.
• It is an inclusive this mean that it include starting and ending value.
Select column_name(s) from tablename where column_name between value1 and
value2;
Select * from student where age between 10 and 20;
Select * from student where age not between 10 and 20;
Select * from student where age between 10 and 20 and address in (‘KTM’,Bkt’,’Lalit’);
Select * from student where age not between 10 and 20 and address in
(‘KTM’,Bkt’,’Lalit’);
Select * from student where age not between 10 and 20 and address not in
(‘KTM’,Bkt’,’Lalit’);
Select * from student where name between “Anish” and “CACA”
Select * from student where name not between “Anish” and “CACA”
NULL Values
• A field with a NULL value is a field with no value.
• A NULL value is different from a zero value or a field that contains spaces. A field with a NULL
value is one that has been left blank during record creation.
• Test for NULL Values
• Not possible to test for NULL values with comparison operators, such as =, <, or <>.
• IS NULL and IS NOT NULL operators is used.
• IS NULL Syntax
SELECT column_names FROM table_name WHERE column_name IS NULL;
Example
SELECT CustomerName, ContactName, Address FROM Customers WHERE Address IS NULL;
• IS NOT NULL Syntax
SELECT column_names FROM table_name WHERE column_name IS NOT NULL;
Example
SELECT CustomerName, ContactName, Address FROM Customers WHERE Address IS NOT
NULL;
SELECT INTO Statement
• The SELECT INTO statement copies data from one table into a new
table.
• SELECT INTO Syntax to Copy all columns into a new table
SELECT * INTO newtable [IN externaldb] FROM oldtable WHERE condition;
• SELECT INTO Syntax to Copy only some columns into a new table
SELECT column1, column2, column3, ... INTO newtable [IN externaldb] FROM oldtable
WHERE condition;
• The new table will be created with the column-names and types as defined in the old
table.
• Can create new column names using the AS clause.
• Example
• SELECT * INTO Student_ktm FROM Students WHERE Address = ‘KTM';
• SELECT S_Name, ContactName INTO StudentBackup2021 FROM Student;
• SELECT * INTO StudentBackup2021 IN 'Backup.mdb’ FROM Student;
• SELECT * INTO StudentBackup2021 FROM Student;
INSERT INTO SELECT
• The INSERT INTO SELECT statement copies data from one table and inserts it into
another table.
• IT requires that data types in source and target tables match
• The existing records in the target table are unaffected
• INSERT INTO SELECT Syntax
• Copy all columns from one table to another table:
• INSERT INTO table2 SELECT * FROM table1 WHERE condition;
• Copy only some columns from one table into another table:
• INSERT INTO table2 (column1, column2, column3, ...) SELECT column1, column2, column3, ... FROM table1
WHERE condition;
• Example
• INSERT INTO Customers (CustomerName, City, Country) SELECT SupplierName, City, Country
FROM Suppliers;
• INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)
SELECT SupplierName, ContactName, Address, City, PostalCode, Country FROM Suppliers;
• INSERT INTO Customers (CustomerName, City, Country) SELECT SupplierName, City, Country
FROM Suppliers WHERE Country='Germany';
Comments
• Comments are used to explain sections of SQL statements, or to prevent execution of SQL
statements.
• Single Line Comments
• Single line comments start with --.
• Any text between -- and the end of the line will be ignored (will not be executed).
• Example
--Select all:
SELECT * FROM Customers;
SELECT * FROM Customers -- WHERE City='Berlin';
• Multi-line Comments
• Multi-line comments start with /* and end with */.
• Any text between /* and */ will be ignored.
• Example
/*Select all the columns
of all the records
in the Customers table:*/
SELECT * FROM Customers;
Set Operation
SET operators are mainly used to combine the same type of data from
two or more tables. Although more than one select statement will then
be present, only one result set is returned.
Rules of Set Operation
• The result sets of all queries must have the same number of columns.
• In every result set the data type of each column must match the data
type of its corresponding column in the first result set.
• In order to sort the result, an ORDER BY clause should be part of the
last statement.
• The records from the top query must match the positional ordering of
the records from the bottom query.
• The column names or aliases must be found out by the first select
statement.
SET Operation
Union: Retrieve all data from union table and eliminate duplicate itself.
Eg: select subject_id from class where sem=‘IV’ and
year=‘2014’ union select subject_id from class where
sem=‘V’ and year=‘2015’
Intersect: Retrieve only those data which are match in given tables.
Eg: select subject_id from class where sem=‘IV’ and
year=‘2014’ intersect select subject_id from class
where sem=‘V’ and year=‘2015’
Except: retrieve the data from table except second table under given
condition.
Eg: select subject_id from class where sem=‘IV’ and
year=‘2014’ except select subject_id from class where
sem=‘V’ and year=‘2015’
Nested Queries / Subqueries
Query within another queries

We can use nested subqueries in where clause as well as from clause.

Subqueries can be used with SELECT, INSERT, UPDATE, and DELETE


statement.

Operator like (>,<,+,>=,<=,IN, BETWEEN) can used in subqueries.


Rules for creating Subqueries
Subqueries must be enclosed within parentheses.

A subquery can have only one column in the SELECT clause, unless multiple
columns are in the main query for the subquery to compare its selected
columns.

An ORDER BY command cannot be used in a subquery, although the main


query can use an ORDER BY. The GROUP BY command can be used to
perform the same function as the ORDER BY in a subquery.

Subqueries that return more than one row can only be used with multiple
value operators such as the IN operator.
Cont…
The SELECT list cannot include any references to values that evaluate
to a ARRAY.

A subquery cannot be immediately enclosed in a set function.

The BETWEEN operator cannot be used with a subquery. However,


the BETWEEN operator can be used within the subquery.
Subqueries for SELECT Statement
• Question: Retrieve all records of products where product price is greater
than 200.
• select * from products where product_id in (select product_id from
products where product_price>200);
• Question: Display the name of person who purchase expensive products.
• select name from products where product_price =(select
MAX(product_price) from products);
• Question: List the product name having the price less than average price.
• select product_name from products where product_price<( select
avg(product_price) from products);
Subqueries for INSERT/Update/Delete
Statement:
• Subqueries for INSERT Statement:
• Question: Insert records of person into person1 if they purchase any product.
• insert into person1 select * from person where id in (select id from purchase);
• Subqueries for Update Statement:
• Question: Update the address of person to “Shantinagar” who purchase product 104.
• update person set address='Shantinagar' where id in(select id from purchase where
product_id=104);
• Subqueries for Delete Statement:
• Question: Delete the record of person1 whose address is ‘janakpur’ in person
• delete from person1 where id in(select id from person where address='janakpur');
• Question: Delete the record of product which price is expensive.
• delete from products where product_price=(select max(product_price) from
products);
JOIN
SQL Join is used to fetch data from two or more tables, which is joined to appear as
single set of data.
SQL Join is used for combining column from two or more tables by using values
common to both tables.
Join Keyword is used in SQL queries for joining two or more tables
SQL Joins is used to combine two or more table to retrieve data.
Join is the way of combining the field of two or more table by using value common
to each other.
There are different types of join which includes:
INNER Join
LEFT Join
RIGHT Join
FULL Join
SELF Join
CARTESIAN Join
JOIN Example
CARTESIAN/CROSS Join
• This type of JOIN returns the cartesian product of rows of from the
tables in Join.
• It will return a table which consists of records which combines each
row from the first table with each row of the second table.
• Syntax,
SELECT column-name-list from table-name1
CROSS JOIN table-name2;
Select column-name-list from table-name1, table-name2
• Example
SELECT * from class cross JOIN class_info;
Select * from teacher, student
class table class_info table
ID NAME ID Address
1 abhi 1 DELHI
2 adam 2 MUMBAI
4 alex 3 CHENNAI

Result
ID NAME ID Address
1 abhi 1 DELHI
2 adam 1 DELHI
SELECT *
from class, 4 alex 1 DELHI
cross JOIN class_info; 1 abhi 2 MUMBAI
Or 2 adam 2 MUMBAI
Select * from class, class_info; 4 alex 2 MUMBAI
1 abhi 3 CHENNAI
2 adam 3 CHENNAI
4 alex 3 CHENNAI
INNER Join or EQUI Join
Returns rows when there is a match in both tables.
This is a simple JOIN in which the result is based on matched data as per the equality condition
specified in the query.
Inner Join Syntax
SELECT column-name-list from table-name1
INNER JOIN
table-name2 WHERE table-name1.column-name = table-name2.column-name;
OR
Select table1.column1, table2.column3 from table1, table2
where table1.columnn = table2.columnn
Inner join example:
SELECT * from class, class_info where class.id = class_info.id;
OR
SELECT name, products.product_name FROM person INNER JOIN purchase
ON person.id = purchase.id inner join products on
purchase.product_id=products.product_id;
Example
Class table, Class_info table,
ID NAME ID Address
1 Abhi 1 DELHI
2 Adam 2 MUMBAI
3 Alex 3 CHENNAI
4 Anu

SELECT * from class, class_info where class.id = class_info.id;

Result
ID NAME ID Address
1 abhi 1 DELHI
2 adam 2 MUMBAI
3 alex 3 CHENNAI
Left Join
LEFT JOIN − returns all rows from the left table, even if there are no matches in the right
table. The join will still return a row in the result, but with NULL in each column from the
right table.
The left outer join returns a result table with the match data of two tables then remaining
rows of the left table and the null value for right table's column.
Left join Syntax:
SELECT column_list from table1 LEFT OUTER JOIN /LEFT JOIN table2 ON
table1.column_m = table2.column_p
Left join example:
SELECT name, products.product_name
from person LEFT JOIN purchase
on person.id=purchase.id
LEFT JOIN products on purchase.product_id=products.product_id;
OR
SELECT * FROM student LEFT JOIN address ON student.id = address.id;
Right Join
 Returns all rows from the right table, even if there are no matches in the right table. The join
will still return a row in the result, but with NULL in each column from the left table.
 The right outer join returns a result table with the match data of two tables then remaining
rows of the right table and the null value for left table's column.
Syntax:
SELECT column_list from table1 RIGHT OUTER JOIN /RIGHT JOIN table2 ON table1.column_m =
table2.column_p
Right join example:
SELECT name, products.product_name
from person RIGHT JOIN purchase
on person.id=purchase.id
RIGHT JOIN products on purchase.product_id=products.product_id;
OR
SELECT * FROM student RIGHT JOIN address ON student.id =
address.id;
Full Join/ FULL OUTER JOIN
Return row when there is a match in one of the tables.
The FULL OUTER JOIN returns a result table with the match data of two tables
then remaining rows of both left table and then the right table.
Syntax:
SELECT column_list from table1 FULL OUTER JOIN /FULL JOIN
table2 ON table1.column_m = table2.column_p
Full join example:
SELECT name, products.product_name
from person FULL JOIN purchase
on person.id=purchase.id
FULL JOIN products on purchase.product_id=products.product_id;
OR
SELECT * FROM student FULL JOIN address ON student.id =
address.id;
SELF JOIN
• A self join is a join in which a table is join with itself. Self join is used
for comparison within a table.
• Syntax:
• SELECT column_list FROM table_name A, table_name B WHERE condition.
• Example:
• SELECT a.fname AS FirstName1, b.fname AS FirstName2 FROM student as a,
student as b WHERE a.fname<>b.fname AND a.address=b.address
• SELECT a.fname AS FirstName1, b.fname AS FirstName2 FROM student as a,
student as b WHERE a.fname!=b.fname AND a.address=b.address

You might also like