1
STRUCTURED QUERY LANGUAGE
(SQL)
Prepared by:-
Shweta Wadhera
2
DBMS LAB-1
Learning Objectives
Introduction to SQL
Concept of Table and Relation
Classification of SQL
Table Creation
Data Insertion
Data Retrieval
Table Structure
Modification
Data Deletion
Table Deletion
3
In this session, you will learn …..
The basic commands and functions of SQL
How to use SQL for data administration (to create tables etc.)
How to use SQL for data manipulation (to add, modify, delete
data)
How to use SQL to query a database to extract useful
information
4
Structured Query Language(SQL)
SQL is a database computer language designed for the retrieval and
management of data in relational database.
SQL is structured Query Language which is a computer language for
storing, manipulating and retrieving data stored in relational database.
SQL is the standard language for Relation Database System. All relational
database management systems like MySQL, MS Access, Oracle, Sybase,
Informix, and SQL Server uses SQL as standard database language.
Why SQL ? 5
Allows users to access data in relational database
management Systems.
Allows users to describe the data.
Allows users to define data in database and manipulate that
data.
Allows users to create and drop databases and tables.
Allows users to create view, stored procedure, functions in a
database.
Allows users to set permissions on tables, procedures, and
views
Oracle has grouped the commands of SQL into the following five 6
sublanguages.
DDL (Data Definition Language):
Create,Alter,Drop,Rename
DML(Data Manipulation Language)
Insert,Update,Delete
DQL(Data Query Language)
Select
DCL(Data Control Language)
Grant,Revoke
Introduction to: 7
SQL Data Definition commands
Introduction to : 8
SQL Data Manipulation commands
9
Introduction to SQL DML (continued….)
10
Relation and Tables
In relational database systems (DBS) data are represented
using tables (relations). A query issued against the DBS also
results in a table. A table has the following structure:
11
A table is uniquely identified by its name and
consists of rows that contain the stored
information, each row containing exactly one tuple (or record).
A table can have one or more columns.
A column is made up of a column name and a
data type, and it describes an attribute of the
tuples. The structure of a table, also called
relation schema.
The type of information to be stored in a table is
defined by the data types of the attributes at table
creation time.
Data Types 12
char(n): Fixed-length character data (string), n characters long. The maximum
size for n is 255 bytes (2000 in Oracle8). Note that a string of type char is
always padded on right with blanks to full length of n.
Example: char(40)
varchar2(n): Variable-length character string. The maximum size for n is 2000
. Only the bytes used for a string require storage.
Example: varchar2(80)
number(o, d): Numeric data type for integers and reals. o = overall
number of digits, d = number of digits to the right of the decimal point.
Maximum values: o =38, d= -84 to +127.
Examples: number(8), number(5,2)
Note that, e.g., number(5,2) cannot contain anything larger than 999.99
without resulting in an error. Data types derived from number are
int[eger], dec[imal], smallint and real.
date: Date data type for storing date and time. The default format for a
date is: DD-MMM-YY. Examples: '13-OCT-94', '07-JAN-98'
13
Creating Table Structures
Primary key attributes contain both a NOT NULL and
a UNIQUE specification
RDBMS will automatically enforce referential integrity
for foreign keys
Command sequence ends with semicolon
Create Command 14
Create Command Syntax:
CREATE TABLE table-name
(
Column-name-1 data-type-1 [constraint],
Column-name-1 data-type-2 [constraint],
Column-name-1 data-type-3 [constraint]
);
Example :-
CREATE TABLE student (
Rno number(10),
student_name varchar2(30),
cgpa decimal(5,3),
branch varchar2(10),
mob_no number(10)
);
15
Describe Command
Describe Command will Display the column names and
corresponding data types present in the table.
Syntax :
describe table-name;
Desc table-name;
Example :-
desc student
16
Insert Command
It can be executed in the following three ways
Insert into table-name {(col1,col2,...,coln)} values
(value1,value2,...,valuen);
Insert into table-name values(value1,value2,....,valuen);
Example 1 :-
INSERT INTO Student
(Rno, student_name, address)
VALUES (1005, ‘Anisha Chopra’, ‘A-6/95 JP Towers
Dwarka’ ) ;
17
Example2 :--
INSERT INTO Employee
VALUES
(‘1006’, ‘J R Pradhaan’ ,’Manager’ ,’02-jul-1986’,20,50000) ;
INSERT INTO Employee
(Eno, Ename, Designation, Hire_dt, Dept_no, Salary )
VALUES (‘1006’, ‘J R Pradhaan’ ,’Manager’ ,’02-jul-
1986’,20,50000) ;
View the contents of table …… 18
SELECT Command
The SELECT Clause lists the columns to display.
The FROM clause lists the tables from which to obtain the
data.
The WHERE clause specifies the condition or conditions that
need to be satisfied by the rows of the tables indicated in the
FROM clause.
The ORDER BY clause indicates the criterion or criteria used
to sort rows that satisfy WHERE clause
19
Many faces of Select Command ……
SELECT STATEMENT Syntax:
SELECT col1,col2,col3,...,coln
FROM table-1,...,table-n
[WHERE condition]
[ORDER BY col1 [ASC|DESC] [, col2 [ASC|DESC] ...]];
Global Data Extract
Syntax : SELECT * FROM tablename ;
Example : SELECT * FROM Employee ;
Continued….. 20
The Retrieval of specific columns from a Table :
Syntax : SELECT “expression list”
FROM tablename ;
Examples:
SELECT vend_name, vend_code
FROM vendor_table ;
Elimination of duplicates from the SELECT statement :
Syntax : SELECT DISTINCT Colname, colname
FROM tablename ;
Examples :
SELECT DISTINCT vendor_no
FROM vendor_table ;
Continued …. 21
Sorting of Data in a Table :
Syntax : SELECT Colname, colname
FROM tablename
ORDER BY Colname , colname ;
Example : SELECT Rno, Student_name , address , city
FROM Student
ORDER BY Rno ;
Where Clause 22
The Conditions are of the following form
Column-name comparisonoperator single-value
Comparison Operators Description
= Equal to
<> Not equal to
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
SELECT continued ….. 23
USING WHERE clause , selecting a data set from
table data :
Syntax : SELECT colname , colname
FROM tablename
WHERE search condition ;
Example : SELECT vendor_no , vendor_name
FROM vendor_table
WHERE vendor_no = 1005 ;
24
Modifying the structure of the Table
Adding new column
Syntax : ALTER TABLE tablename
ADD (new_column_name data type (size), new_column_name
data type (size) ) ;
Eg 1:
ALTER TABLE department
ADD ( Mob_no number(10) ) ;
Eg 2:
ALTER TABLE vendor_table
ADD ( tel_no number(8), fax_no number(15) ) ;
25
Modifying the structure of the Table
Modifying Existing Column
Syntax : ALTER TABLE tabename
MODIFY (column_name newdatatype (size) ) ;
Eg :
ALTER TABLE vendor_table
MODIFY (fax_no varchar2(15) ) ;
26
Updating the contents of a Table
Syntax:
UPDATE tablename
SET columnname = expression [, columname = expression
[WHERE columname = expression ] ;
Example 1:
UPDATE Department
SET no_of_emp = 50
WHERE Dno = 10
Updating the contents of a Table 27
If more than one attribute is to be updated in row,
separate corrections with commas
Example 2:
UPDATE Department
SET no_of_emp = 200 , Dept = ‘IT’
WHERE Dno = 30 ;
Example 3:
UPDATE Vendor
SET vendor_ name = ‘Varsha Kapoor’ ,
address = ‘ A 8/97, J P Towers, Dwarka’
WHERE vendor_no = 1005 ;
Deleting Table Rows 28
Deletion of ALL Rows ……..
Syntax : DELETE FROM tablename ;
Example : DELETE FROM Student;
Deletion of specified Rows :-
Syntax : DELETE FROM tablename
[WHERE conditionlist ]
If WHERE condition is not specified, all rows from specified table
will be deleted
Example :
Delete From Department
where Dno = ‘ 20’ ;
29
DROP COMMAND
DROP command will permanently delete the table with all its data
DROP TABLE table-name [CASCADE CONSTRAINT];
Special Operators 30
BETWEEN
Used to check whether attribute value is within a range
IS NULL
Used to check whether attribute value is null
LIKE
Used to check whether attribute value matches given string
pattern
IN
Used to check whether attribute value matches any value within
a value list
EXISTS
Used to check if subquery returns any rows
31
ALTER COMMAND
One can add a new column,drop an existing column,modify the
datatype of a column,and drop the constraints using the following
commands respectively.
ALTER TABLE table_name ADD COLUMN_name datatype;
ALTER TABLE table_name DROP COLUMN column_name;
ALTER TABLE tablename MODIFY (column_name,datatype);
ALTER TABLE table_name DROP CONSTRAINT
constraint_name;
Lab Assignment-1 32
Create the follwing tables
branch(branch_name, branch_city, assets)
customer(customer_name, customer_street, customer_city)
loan(loan_number, branch_name, amount)
borrower(customer_name, loan_number)
account(account_number, branch_name, balance)
depositor(customer_name, account_number)
Assignment Continued….. 33
Populate the branch table with the following data
branch_name branch_city assets
Brighton Brooklyn 7100000
Downtown Brooklyn 9000000
Mianus Horseneck 400000
North Town Rye 3700000
Perryridge Horseneck 1700000
Pownal Bennington 300000
Redwood Palo Alto 2100000
Round Hill Horseneck 8000000
Assignment Continued….. 34
Populate the customer table with the following data
Customer_name Customer_street Customer_city
Adams Spring Pittsfield
Brooks Senator Brooklyn
Curry North Rye
Glenn Sand Hill Woodside
Green Walnut Stamford
Hayes Main Harrison
Johnson Alma Palo Alto
Jones Main Harrison
Lindsay Park Pittsfield
Smith North Rye
Turner Putnam Stamford
Williams Nassau Princeton
Assignment Continued.. 35
Populate the loan table with the following data
loan_number branch_name Amount
L-11 Round Hill 900
L-14 Downtown 1500
L-15 Perryridge 1500
L-16 Perryridge 1300
L-17 Downtown 1000
L-23 Redwood 2000
L-93 Mianus 500
36
Assignment Continued...
Populate the borrower realtion the following data
Customer_name loan_number
Adams L-16
Curry L-93
Hayes L-15
Jackson L-14
Jones L-17
Smith L-11
Smith L-23
Williams L-17
37
Assignment Continued...
Populate account relation with the following data
account_number branch_name balance
A-101 Downtown 500
A-215 Mianus 700
A-102 Perryridge 400
A-305 Round Hill 350
A-201 Brighton 900
A-222 Redwood 700
A-217 Brighton 750
38
Assignment Continued...
Populate the depositor relation with the following data
Customer_name account_number
Hayes A-102
Johnson A-101
Johnson A-201
Jones A-217
Lindsay A-222
Smith A-215
Turner A-305
Create the following table….. 39
Create a student table with the following data
Regdno Student_name Branch
1001 Surya CSE
1002 Binaya ETC
1003 Arup CSE
Add the CGPA Column, to the student table (the type
must be a floating point type)
Update the contents of CGPA column
Modify the existing type of regdno.
Update the student_name to Apoorv and Branch name
to ‘ETC’ where the Regdno= 1003
Now delete all the data present in the student table.
Drop the table
40
Create the following two tables to store the details of sales
made by its various salesmen in departmental store 41
Salesman( Sales man identification, Name ,Date of birth,
Address, Marital Status, Phone num )
Sale (Sales man identification, Product code, Units sold,
Value, The date of sale)
Create table salesman
(SID number(3) NOT NULL Primary Key, SNAME
varchar2(20), DOB DATE, address Varchar2(50), MSTATUS
Varchar2(1),PHONE number(10) );
Create table SALE
(SID number(3), PCODE number(3), UNITS_SOLD
number(5), VALUE number(6,2), DATE_SOLD DATE );
42
Create the table and add foreign key constraint
Create table SALE ( SID number(3), PCODE number(3) , UNITS_SOLD
number(5), VALUE number(6,2), DATE_SOLD DATE ,
CONSTRAINT sid_fkey
FOREIGN KEY (SID) REFERENCES SALESMAN (SID) ) ;
Alter the Table to add foreign key CONSTRAINT
ALTER TABLE SALE
ADD CONSTRAINT sid_fkey
FOREIGN KEY (SID) REFERENCES SALESMAN (SID) ;
INSERT INTO Salesman 43
VALUES (101, ‘ ATUL VERMA’ , ’30-NOV-1985’, ‘New Delhi’, ‘U’,
9818181232);
INSERT INTO Salesman
VALUES (102, ‘ ANU Soodi ’ , ’20-OCT-1982’, ‘New Delhi’, ‘U’,
9820202323);
INSERT INTO Sale
VALUES(101,111,100, 200, ‘20-JAN-17’ );
INSERT INTO Sale
VALUES(105, 111, 10,200, ’18-JAN-17’);
Create two tables , to computerize a library system of a delhi44
university college.
LibraryBooks ( AccNo , Title, Author, Department, Purchase Date,
Price )
IssuedBooks ( Accno , Borrower )
Enter atleast 5 records in each table .
45
ALTER TABLE IssuedBooks
ADD CONSTRAINT fk_acc_no
FOREIGN KEY (Acc_no) REFERENCES
LibraryBooks( Acc_no) ;
46
Create the following table to store the details of an Employee……
EMPLOYEE ( Empno , Ename , JOB, Mgr , Hire Date, Salary ,
Commission, Department no )
Create table emp2 (
emp_no varchar2(4) NOT NULL PRIMARY KEY,
e_name varchar2(25) NOT NULL,
job varchar2(15),
mgr varchar2(20),
hire_date DATE,
salary number(4),
commission number(4),
dept_no varchar2(10)
);
47
1) Write a query to display name, job,hire date and employee no
for each employee with empno appearing first.
SELECT empno, ename, job , hiredate
FROM emp ;
2) Write a query to display unique jobs from the employee
table.
SELECT DISTINCT job
FROM emp;
3 ) Write a query to display name concatenated by a job
48
separated by a comma .
SELECT ename || ‘,’ || job
As name_and_Job
FROM emp ;
4) Write a query to display all data from employee table.
Separate each column by a comma and name the column
THE_OUTPUT .
5) Write a query to display the name and salary of employees
earning more than $2850 .
6) Write a query to display the name and Department number
for emp no 7900.
7 ) Write a query to display the name and salary of all
49
employees whose salary is not in the range of $1500 and
$3000.
use of NOT BETWEEN ….
SELECT ename,sal
FROM emp
WHERE sal NOT BETWEEN 1500 AND 2850
8 ) Write a query to display employee name, job, hire date
of employees hired between FEB 20, 1981 and MAY 1,
1981. Order the query in ascending order of start date.
use of BETWEEN ….
SELECT ename,job,hiredate
FROM emp
WHERE hiredate BETWEEN '20-FEB-1981' AND '01-MAY-1981'
ORDER BY hiredate
9) Write a query to display the name and department number of All
employees in departments 10 and 30 in alphabetical order by name. 50
use of OR …..
SELECT ename,deptno
FROM emp
WHERE deptno=10 OR deptno=30
ORDER BY ename
10 ) Write a query to display the name and salary and Dept no of
employees who earnes more than $1500 and are in dept no 10 or
30 .
Use of AND ……
SELECT ename,sal
FROM emp
WHERE (sal>1500) AND (deptno=10 or deptno=30)
11 ) Write a query to display the name and hire date of
51
every employees who were hired in 1981.
Use of LIKE and ‘ %’…….
SELECT ename,hiredate
FROM emp
WHERE hiredate LIKE '%81'
12 ) Write a query to display the name and Job of all
employees who do not have a manager.
Use of IS NULL …….
SELECT ename,job
FROM emp
WHERE mgr IS NULL
52
13 ) Write a query to display the names of all
employees where the third letter of their name is A.
Use of Like and % and ‘_’
where name LIKE ‘__A%’
14 ) Write a query to display the names of all
employees that have two ‘R ‘s or A ‘s in their name and
are in department num 30 or their manager is 7788.
Select ename
From emp
Where (ename LIKE ‘ %R%R%’ OR ename LIKE
‘%A%A%’ ) AND ( ( deptno =30) OR (mgr=7788) ) ;
53
Functions …….
AVG AVG( [ DISTINCT | ALL] n )
Returns the avg value of n , ignoring NULL values.
Ex 1 :
SELECT AVG( sal ) as “Average salary “
FROM emp ;
Ex 2 :
SELECT AVG( DISTINCT sal ) as “ Average salary “
FROM emp ;
Duplicate values are eliminated when the function is used along
with DISTINCT .
54
COUNT (expr)
Syntax COUNT( [DISTINCT | ALL ] expr ) ;
Returns the number of rows where expr is NOT
NULL . So NULL values ignored .
EX 1:
SELECT COUNT (jobs) “Count is “
FROM emp;
Ex 2 :
SELECT COUNT ( DISTINCT jobs) “Count without duplicates “
FROM emp ;
55
COUNT ( * )
Returns the num of rows in the Table , Including Duplicates
and those with NULL values.
Ex : SELECT COUNT( * ) “Total no of rows”
FROM emp ;
MAX
Returns MAX value of expression .
Ex : SELECT MAX(sal) “Maximum “
FROM emp ;
56
MIN Syntax MIN ( [ DISTINCT | ALL ] expr )
Returns minimum value of expression.
Ex : SELECT MIN ( hiredate ) “ Minimum date”
FROM emp ;
57
Q J ) Query to display the no. of managers without
listing their names .
Q K ) Query to display the difference b/w the highest
and lowest salaries .
58
Q J)
SELECT COUNT ( DISTINCT mgr )
FROM emp ;
Q K)
SELECT ( MAX ( salary) – MIN (salary ) )
FROM emp ;
59
SUM
Syntax : SUM( [ DISTINCT | ALL ] n)
EX 1:
SELECT SUM( sal ) “ Sum of salaries”
FROM emp ;
Ex 2 : SELECT SUM ( DISTINCT sal ) “ sum of salaries”
FROM emp ;
ABS
Returns the absolute value of n .
Ex :
SELECT ABS (-15) as “ Absolute value”
FROM dual ;
60
ROUND
Syntax ROUND ( n[,m] )
Returns n rounded to m places, right of the decimal point;
to 0 places if m is omitted .
Ex :
SELECT ROUND(15.19 , 1) “ Rounded val “
FROM dual ;
SQRT
Syntax SQRT( n )
Returns square root of n; NULL if n<0 .
Ex :
SELECT SQRT (25) “ Square root”
FROM dual ;
61
LOWER
Syntax : LOWER ( char );
Returns char with all letters in lower case
Ex :
SELECT LOWER ( ‘ ABCDEF ‘ ) as “ Lower text “
FROM dual ;
UPPER
Syntax : UPPER ( char )
Returns char with all letters in Upper case
Ex :
SELECT UPPER (‘abcdef ‘ )
FROM dual ;
62
LENGTH
Syntax : LENGTH ( char )
Returns the length of char .
Ex :
SELECT LENGTH (‘ pretty’) as “ Length of str”
FROM dual ;
Length of str
------------------
6
63
LPAD
Syntax : LPAD (char1 , n , [ char2 ] )
Returns char1, left padded with the sequence of chars in
char2.
Total length with padding is n .
Default value of char2 is blank.
Ex :
SELECT LPAD( ‘Page1’ , 14, ‘ * ‘ ) “ Lpad output “
FROM dual ;
Lpad output
---------------------
********Page 1
64
RPAD
Syntax : RPAD (char1 , n , [ char2 ] )
Returns char1, right padded with the sequence of chars in
char2.
Total length with padding is n .
Default value of char2 is blank.
Ex :
SELECT RPAD( ename , 10, ‘ x ‘ ) “ ename as
Rightpadded output “
FROM emp
WHERE ename = ‘ PRIYA’ ;
ename as Rightpadded output
-----------------------------------------
PRIYAxxxxx
TO_CHAR ( DATE TO CHAR CONVERSION )
65
Syntax : TO_CHAR( d [ , fmt ] )
Converts a value of DATE datatype to CHAR datatype in
the format specified as fmt.
Also fmt must be a date format.
If fmt is skipped, the given date d is converted to a character
value having the default date format , which is
“ DD-MON-YY” .
Ex :
SELECT TO_CHAR(hiredate, ‘ Month DD,YYYY ‘) as
“New Date Format “
FROM emp
WHERE ename = ‘ SMITH ‘ ;
Output : New Date Format
-------------------------------
January 26, 2017
66
Usage of IN and NOT IN ……
Q ) Write a query to display Name, Job, and salary of all
employees whose Job is Clerical or Analyst & their salaries
are not equal to 1000, 3000 or 5000.
SELECT ename, job , salary
FROM emp
WHERE job IN ( ‘ Clerk’ , ‘ Analyst ‘ ) AND ( salary NOT IN
(1000, 3000, 5000 ) ) ;
67
Q ) Write a query to display Name , Salary , Commission for
all employees whose commission amount is greater than their
Salary increased by 5% .
SELECT ename, salary , commission
FROM emp
WHERE commission > ( salary * 1.05) ;
Q ) Write a query to display the current date .
SELECT SYSDATE
FROM dual ;
68
Q A ) Query to display Employee No. , Name , Salary and the
Salary increased by 15 % expressed as absolute whole
number .
Based on ROUND Fn ……….
69
QA)
SELECT eno , ename , salary , ROUND ( salary * 1.15 ) AS
“ NEW SALARY “
FROM emp ;
70
Q B ) Query to display name and calculate the number of
months between today and the date each employee was hired.
QB)
SELECT ename,
ROUND ( MONTHS_BETWEEN ( (Select SYSDATE from dual ) ,
hiredate ) ) as “ Num_of_Months “
FROM emp ; Imbedded Query
which returns Date
type value
Date type Value
71
Q C ) Query to display the following for each employee :--
< ename > earns < salary > monthly but wants < 3 * current
salary > .
Label the column as DREAM SALARY .
Q D ) Query to display name and salary for all employees .
Format the salary to be 15 character long , left padded with
$ sign .
72
QC)
SELECT ename || ‘ earns ‘ || salary || ‘ monthly but wants ‘ ||
3 * salary as “ Dream Salary “
FROM emp ;
Q D ) SELECT ename , LPAD (salary , 15 , ‘$ ‘) as “ FORMATTED
SALARY “
FROM emp ;
73
Q E ) Query to display Name with 1st letter capitalized and
all other letters lower case & length of the name of all the
employees whose names start with ‘ J’ , ‘ A” and ‘M’ .
74
QE)
SELECT INITCAP( ename ) as “ NAME “,
LENGTH ( ename ) as “ LENGTH “
FROM emp
WHERE ename LIKE ‘J % ‘
OR ename LIKE ‘ A % ‘
OR ename LIKE ‘ M %’ ;
75
Based on Subquery concept ………
Q G ) Query to display the Employee No , name and
salary for all employees who earn more than the
average salary .
Q H ) Query to display Name and Hiredate for all
employees in the same dept as BLAKE .
76
Subquery
QG)
SELECT eno , ename , salary
FROM emp
WHERE salary > ( SELECT AVG ( salary )
FROM emp ) ;
77
Q H ) Sub query concept
SELECT ename , hiredate
FROM emp
WHERE Dno = ( SELECT Dno
FROM emp
WHERE ename = ‘ BLAKE ‘ ) ;
78
Sub query concept …………..
Q I ) Query to display the employee name and salary of
all employees who report to king .
79
Q I ) sub query concept
SELECT ename , salary
FROM emp
WHERE mgr = ( SELECT eno
FROM emp
WHERE ename = ‘ KING ‘ ) ;
Thank You
80
**Q F ) Query to display name , hiredate and day of the week on
which the employee started .
81
82
**Q F )
SELECT ename , hiredate, TO_CHAR( hiredate , ‘ DAY’ ) as
“ Day Of Week “
FROM emp ;