SlideShare a Scribd company logo
INTRODUCTION TO
SQL
content
 Introduction to SQL
 Three types of SQL Statements
 DDL
 DML
 DCL
 Aggregate functions
 Other functions(Date, string,..)
 View
SQL
 SQL (Structured Query Language) is a nonprocedural
language, you specify what you want, not how to get it.
A block structured format of English key words is used
in this Query language.
 The process of requesting data from a Database and
receiving back the results is called a Database Query and
hence the name Structured Query Language.
 SQL is language that all commercial RDBMS
implementations understand.
SQL
 SQL developed at IBM by Donald D
Chamberlinand Raymand F Boyce in 1970’s
 Initially called SEQUEL(Structured English QUEry
Language)
 It is easy to learn, poratble in nature , and easy to
create multiple views.
 It has the following components.
 DDL (Data Definition Language)
 DML (DATA Manipulation Language)
 View definition
 Transaction Control
 Integrity
 Authorization
Structured Query Language (SQL)
Database
SQL Request
Data
01000101
11001010
01001011
Computer System
DBMS
General terms
 Table : collection of data in tabular format
 Tuples: row / record
 Attributes : column name
 Constrainst : conditions
Three types of Statements
 DDL is Data Definition Language
statements. Some examples:
 CREATE – to create objects in the database
 ALTER – to alter the structure of the database
 DROP – to delete objects from the database
 TRUNCATE – to remove all records from a table.
The space allocated for the records is also removed
DML
DML is Data Manipulation Language
statements. Some examples:
 SELECT – to retrieve data from the database
 INSERT – to insert data into a table
 UPDATE – to update existing data within a table
 DELETE – to delete all records from a table. The
space allocated for the records remains intact
DCL
 DCL is Data Control Language statements.
Some examples:
 GRANT – to give user access privileges to database
objects
 REVOKE – to withdraw access privileges given with
the GRANT command
 COMMIT – to save the work done
 ROLLBACK – to restore database to original since
the last COMMIT
Data Types
 The SQL standard supports a variety of built in
domain types, including-
 Char (n)- A fixed length character length string with
user specified length .
 Varchar (n)- A variable character length string with
user specified maximum length n.
 Number (p, d)-A Fixed point number with user
defined precision.
Data types
 Float (n)- A floating point number, with precision of
at least n digits.
 Date- A calendar date containing a (four digit) year,
month and day of the month. Standard format is DD-
MON-YYYY
 Time- The time of day, in hours, minutes and seconds
Eg. Time ’09:30:00’.
NULL
 Missing/ unknown/ inapplicable data represented as
a NULL value
 NULL is not a data value. It is just an indicator that
the value is unknown
Operators
 Arithmetic operators: +, -, *, /
 Logical operators: AND, OR, NOT
 Relational operators: =, <=, >=, < > , < , >
 <> or != not equal to.
Operators
 The Arithmetic operators are used to calculate
something like given in the example below:
 Select * from employee where sal * 1.1 > 1000 ;
 The logical operators are used to combine conditions
like:
 Select * from employee where (sal > 1000 AND age >
25);
 The above two examples also illustrate the use of
relational operators.
To Create Table command
 Create table command defines each column of the table
uniquely.
 Each column is described as a columnname, datatype
and size
 Each column is seperated by comma.
Syntax:
Create table tablename
(
Column1 datatype(size),
Column2 datatype(size),..
);
Data Constraints
 The constraints can either be placed at column level or
at the table level.
 Column Level Constraints: If the constraints are
defined along with the column definition, it is called a
column level constraint.
 Table Level Constraints: If the data constraint
attached to a specified column in a table reference the
contents of another column in the table then the user
will have to use table level constraints.
List of most used Constraint
 NOT NULL
 DEFAULT
 UNIQUE
 CHECK
 PRIMARY KEY
 FOREIGN KEY
 On delete cascade
 On delete set null
Null Value Concepts:
 . Column of any data types may contain null values
unless the column was defined as not null when the
table was created.
 Syntax:
 Create table tablename
(columnname data type (size) not
null,…)
Note: Not null constraint cannot be defined at table level.
Primary Key
 primary key is one or more columns is a table used to
uniquely identify each row in the table. Primary key values
must not be null and must be unique across the column.
 Syntax: primary key as a column constraint
 Create table tablename
(columnname datatype (size) primary key,….)
 Composite Primary key as a table constraint
 Create table tablename(columnname datatype (size),
columnname datatype( size),…,
Primary key (columnname1,columnname2));
Unique key concept
 A unique key is similar to a primary key except that
the purpose of a unique key is to ensure that
information in the column for each record is unique
as with telephone or devices license numbers.
 Syntax: Unique as a column constraint.
 Create table tablename
(columnname datatype (size) unique);
 Unique as table constraint:
 Create table tablename
(columnname datatype(size),
columnname datatype(size),
unique (columnname));
Default value concept
 At the time of column creation, a default value can be
assigned to it.
 Provides a default value for a column when none is
specified.
 Syntax:
 Create table tablename
(columnname datatype (size) default value,….);
 Note: The default value constraint cannot be
specified at table level.
Foreign Key Concept
 Foreign key represents relationship between tables. A
foreign key is column whose values are derived from
the primary key of the same attribute of some other
table.
 Foreign key as a column constraint
 Syntax :
 Create table tablename2
(columnname datatype(size) references another-
tablename1(columnname1));
Foreign Key Concept
 Foreign key as a table constraint:
 Syntax :
 Create table tablename2
(columnname2 datatype(size)….
foreign key(columnname2) references
tablename1(columnname1));
Check Integrity Constraints
 Use the check constraints when you need to enforce
integrity rules that can be evaluated based on a
logical expression.
 Unique key as a column constraint
 Syntax :
 Create table tablename
(columnname datatype(size) check(logical
expression,….);
Check Integrity Constraints
 Unique key as a table constraint:
 Syntax :
 Create table tablename
(columnname datatype(size), ….Check(logical
expression));
CREATE TABLE EXAMPLE
Customer Table
Colum name Datatype Description Constraints
CustomerId Varchar2(6)
Unique id generated for each
customer
Primary Key, Should
start with ‘C’
CustomerName Varchar2(30) Name of the customer Not null
DateOfReg Date
Date on which the customer
registered
UserId Varchar2(15)
Decided at the time of
registration It should be unique
Password Varchar2(15)
Decided at the time of
registration Not Null
Implementing PRIMARY KEY ,NOT NULL and UNIQUE
CREATE TABLE EXAMPLE
EXAMPLE at column level :
Create table Customer
(CustomerId varchar2(6)
primary key check (CustomerId like 'C%') ,
CustomerName varchar2(30) NOT NULL,
DateofReg date ,
UserId varchar2(15) UNIQUE,
Password varchar2(15) NOT NULL
);
Or At table level
Create table Customer
(CustomerId varchar2(6) ,
CustomerName varchar2(30) NOT NULL,
DateofReg date ,
UserId varchar2(15),
Password varchar2(15) NOT NULL,
primary key(CustomerId),
Unique(userId),
check (CustomerId like 'C%')
);
Create Table (Contd…)
BankInfo Table
Colum name Datatype Description Constraints
AccountNo Number(10)
Account no of
customer
Composite
Primary key
CustomerId Varchar2(6)
Unique id provided to
each customer when
he/she is registered to
purchase items
Foreign key
referring to
customer
table
Implementation of Composite Primary Key and Foreign Key Constraints
EXAMPLE at column & table level:
Create table Bankinfo
(AccountNo number(10),
CustomerId varchar2(6)
references Customer(CustomerId),
Primary key(AccountNo, CustomerId));
Or
Create table Bankinfo
(AccountNo number(10),
CustomerId varchar2(6) ,
Foreign key (CustomerId) references Customer(CustomerId),
Primary key(AccountNo, CustomerId));
Modifying the Structure of Tables
 Alter table command is used to changing the structure of a
table.
 Adding new columns:
 Syntax:
 ALTER TABLE tablename
ADD newcolumnname newdatatype (size);
Alter command..
 Modifying existing table
 Syntax:
 ALTER TABLE tablename
MODIFY (columnname newdatatype (size)
constraint A constraint name);
 Deleting a column
 Syntax:
 ALTER TABLE tablename
DROP COLUMN columnname;
Examples of alter command
 ALTER TABLE Customer
ADD Contact_Phone Char(10);
 ALTER TABLE Customer
MODIFY Contact_Phone Char(12);
 ALTER TABLE Customer
DROP COLUMN Contact_Phone;
Add/ drop Constrainst using Alter
 To add constrainst:
 Syntax: ALTER TABLE tablename
ADD Constraintname (columnname);
Eg alter table Customer Add primary key(CustomerId);
 To drop constrainst:
 Syntax: ALTER TABLE tablename
DROP Constraintname;
Eg alter table Customer drop primary key;
Add/ drop Constrainst using Alter
 To add constrainst:
 Syntax: ALTER TABLE tablename
ADD constraint A Constraintname
(columnname);
Eg alter table Customer Add constraint A primary
key(CustomerId);
 To drop constrainst:
 Syntax: ALTER TABLE tablename
DROP constraint A;
Eg alter table Customer drop A;
To display the structure of the table
 Used to display the information about the columns
defined in a table
 Syntax: DESCRIBE Tablename;
Or
DESC tablename
Removing/Deleting Tables-
 DROP TABLE
 Deletes table structure
 Cannot be recovered
 Use with caution
 Syntax: DROP TABLE tablename;
 Truncate Table
 Deleting All Rows of a table
 faster than delete command(DML)
 Cannot be recovered
 Syntax: TRUNCATE TABLE tablename;
Renaming Tables
 Used to rename the table
 Syntax:
 RENAME tablename to Newtablename
 Eg RENAME Customer to Customer_DATA
DML INSERT :
 Used to insert a single row of data into the table.
 if columnname is not specified by default values will
be as same order of column names of the table
 Syntax:
 INSERT INTO tablename (Column1, column2,…)
VALUES(expression1,expression2,…)
 Eg Insert into Customer values(‘C1001’,’Amit’,’11-Jan-
2012’, ‘amit_12’,’amit’);
Insert example
Insert NULL value
VIEWING Data in table
 To display all columns and all rows
 Syntax: SELECT * FROM tablename;
 Or
 SELECT Column1, column2,..,columnN FROM tablename;
 To display selected columns and all row:
 Syntax:
 SELECT Column1, column2 FROM tablename;
 Eg
 select * from Customer;
 Select CustomerId, DateOfReg from Customer;
VIEWING Data in table
 To view selected column and filtered data
 Syntax:
 SELECT Column1, column2 FROM tablename
WHERE condition;
 To view all columns and filtered data
 Syntax:
 SELECT * FROM tablename WHERE condition;
 Eg.
 Select * from Customer where DateOfReg = ’11-
Jan-2011’
 Select UserId, password from Customer where
DateOfReg = ’11-Jan-2011’
Introduction to sql
Eliminating Duplicate rows using SELECT
command
 Distinct clause removes duplicate rows from the result-set
 Syntax:
 SELECT DISTINCT Column1,column2 FROM tablename
 SELECT DISTINCT * FROM tablename
 SELECT DISTINCT * FROM tablename where condition
Eg Select distinct * from Customer;
Select distinct UserId from Customer where DateOfReg = ’11-Jan-
2011’;
Select distinct CustomerName from Customer where DateOfReg =
’11-Jan-2011’;
UPDATING the Content of Table
 Updating all rows:
 Syntax:
 UPDATE tablename
SET column1=expression1 , column2 = expression2;
 Updating selected rows , where clause is used:
 Syntax:
 UPDATE tablename
SET column1=expression1 , column2 = expression2
Where condition;
Eg. Update Customer set UserId= ‘abca_12’, password = 123
where CustomerId = ‘C1002’;
DELETING Rows from Table
 Delete all rows
 Syntax : DELETE FROM tablename;
 Delete specific rows
 Syntax : DELETE FROM tablename WHERE
condition;
 Eg. Delete from Customer where UserId=
‘abcd_12’;
Differentiate between
DCL
 DCL is Data Control Language statements.
Some examples:
 GRANT – to give user access privileges to database
objects
 Syntax : GRANT permission to username;
 Eg GRANT CREATE TABLE TO amit;
 REVOKE – to withdraw access privileges given with
the GRANT command
 Syntax: REVOKE permission FROM username;
DCL…
 COMMIT – to save the work done
 Syntax: COMMIT;
 SAVEPOINT - to temporarily save a transaction so
that you can rollback to that point whenever
required.
 Syntax: SAVEPOINT savepoint_name;
 ROLLBACK – to restore database to original since
the last COMMIT
 Syntax: ROLLBACK TO savepoint_name;
Computation in expression lists used to
select data:-
 Renaming columns used with Expression Lists: - The
default output column names can be renamed by the user if
required
 Syntax:
 Select column1 as result_column1, column2 as
result_column2 From tablename;
 Logical Operators:
 The logical operators that can be used in SQL sentenced are
 AND all of must be included
 OR any of may be included
 NOT none of could be included
 Range Searching: Between operation is used for range
searching.
 Pattern Searching:
 The most commonly used operation on string is pattern
matching using the operation ‘like’ we describe patterns by
using two special characters.
 Percent (%): the % character matches any substring we
consider the following examples.
 ‘Perry %’ matches any string beginning with perry
 ‘% idge % matches any string containing’ idge as substring.
 ‘ - - - ‘ matches any string exactly three characters.
 ‘ - - - % matches any string of at least of three characters.
 Ordering tuples in a particular order:
 The ‘order by’ clause is used to sort the table
data according to one or more columns of the
table.
 By default sorted in ascending order.
 Syntax:
 select colname1, colname2,…
from tablename where condition
order by colname1 asc/desc, colname2
asc/desc,…;
Examples
 List all items whose unit price is > 100
 List the CustomerId and UserId of ‘Allan’
 List all items where discount is at least 10
percent.
Examples
 List all items whose unit price is > 100
 SELECT ItemId, ItemName
FROM Item WHERE UnitPrice > 100;
 List the CustomerId and UserId of ‘Allan’
 SELECT CustomerId, UderId
FROM Customer
WHERE CustomerName = ‘Allan’;
 List all items where discount is at least 10 percent.
 SELECT ItemId,ItemName
FROM Item
WHERE Discount >= 10;
Examples
 List all items where Unit Price is less than 100 and Unit
of measurement is ‘Dozen’.
 List all items where either the unit price is
less than 100 or Unit of measurement is
‘Dozen’
Examples
 List all items where Unit Price is less than 100 and Unit of
measurement is ‘Dozen’.
 SELECT ItemId, ItemName FROM Item
WHERE UnitPrice < 100
AND UnitOfMeasurement = ‘Dozen’;
 List all items where either the unit price is less
than 100 or Unit of measurement is ‘Dozen’
 SELECT ItemId, ItemName FROM Item
WHERE UnitPrice < 100
OR UnitOfMeasurement = ‘Dozen’;
NOT and BETWEEN
 List all items whose Unit Price is not less than
100 .
 The BETWEEN operator is used to test a range.
 List all items with Unit Price in the range 100 to
200 .
NOT and BETWEEN
 List all items whose Unit Price is not less than 100 .
 SELECT ItemId,ItemName FROM Item
WHERE NOT UnitPrice < 100;
 The BETWEEN operator is used to test a range.
 List all items with Unit Price in the range 100 to 200
.
 SELECT ItemId,ItemName FROM Item
WHERE UnitPrice BETWEEN 100 AND 200;
OR
 SELECT ItemId, ItemName FROM Item
WHERE UnitPrice >= 100 AND UnitPrice <= 200;
IN and NOT IN:
- used to test a membership condition
 List all items which have Unit of measurement as
‘Kilogram’ or ’Dozen’.
IN and NOT IN:
- used to test a membership condition
 List all items which have Unit of measurement as
‘Kilogram’ or ’Dozen’.
 SELECT ItemId,ItemName FROM Item
WHERE UnitOfMeasurement = ‘Kilogram’
OR UnitOfMeasurement = ‘Dozen’;
OR
 SELECT ItemId,ItemName FROM Item
WHERE UnitOfMeasurement
IN(‘Kilogram’,‘Dozen’);
LIKE
 The LIKE operator is used to perform pattern
matching.
 List all Customers whose name starts with ‘A’
and has ‘l’ as the second character
 List all Customer whoses name has ‘a’ as the
second character and has length five.
LIKE
 The LIKE operator is used to perform pattern
matching.
 List all Customers whose name starts with ‘A’
and has ‘l’ as the second character
 SELECT CustomerName FROM Customer
WHERE CustomerName LIKE ‘Al%’;
 List all Customer whoses name has ‘a’ as the
second character and has length five.
 SELECT CustomerName FROM Customer
WHERE CustomerName LIKE ‘_a___’;
IS NULL
 IS NULL evaluates to TRUE if the value is NULL.
 IS NOT NULL evaluates to TRUE is the value is
not NULL.
 List customers whose date of registration is not
available.
 List customers whose date of registration is known.
IS NULL
 IS NULL evaluates to TRUE if the value is NULL.
 IS NOT NULL evaluates to TRUE is the value is not
NULL.
 List customers whose date of registration is not
available.
 SELECT CustomerName FROM Customer
WHERE DateOfReg IS NULL;
 List customers whose date of registration is known.
 SELECT CustomerName FROM Customer
WHERE DateOfReg IS NOT NULL;
Order by
 List the Items of the retail application in the
increasing order of their unit price
 List the items in their decreasing order of quantity
on hand and increasing order of discount.
Order by
 List the Items of the retail application in the
increasing order of their unit price
 SELECT ItemName FROM Item
ORDER BY UnitPrice asc/desc;
 List the items in their decreasing order of quantity
on hand and increasing order of discount.
 SELECT ItemId ,ItemName ,QtyOnHand
,Discount FROM Item
ORDER BY 3 DESC, 4;
AGGREGATE/GROUP FUNCTION
 Group functions operate on set of rows, result is
based on group of rows rather than one result per
row as returned by single row functions.
1)Avg() : return average value of n
 Syntax: Avg ([distinct/all] n)
2)Min() : return minimum value of expr.
 Syntax: MIN([distinct/all] expr)
3)Max () : Return max value of expr
 Syntax: Max ([distinct/all]expr)
AGGREGATE/GROUP FUNCTION
4) Count() : Returns the no of rows where expr
is not null
 Syntax: Count ([distinct/all] expr)
 Count (*) Returns the no rows in the table,
including duplicates and those with nulls.
5) Sum() : Returns sum of values of n
 Syntax: Sum ([distinct/all]n)
Examples:
 Select AVG(GPA) as ‘Average GPA’ from
student;
 Select AVG(DISTINCT GPA) as “Distinct GPA”
from student
 Select MIN(GPA) as “Minimum GPA” from
student
 Select COUNT(*) from student
 Select MAX(GPA) from student
 Select SUM(GPA) from student
Aggregate functions
 List the minimum unit price from item table.
 List the maximum Unit price in the item table.
 List the average Unit price of Class A items in the
item table.
Aggregate functions
 List the minimum unit price from item table.
 SELECT MIN (UnitPrice) FROM Item;
 List the maximum Unit price in the item table.
 SELECT MAX(Total_Dollars)
FROM Customer_Transaction;
 List the average Unit price of Class A items in the
item table.
 SELECT AVG (UnitPrice)
FROM Item where Class=‘A’;
 List the minimum and Sum of all the Unit price
of items in the item table.
 List total number of items in the item table.
 List the total number of customer who have
their date of registration information in the
customer table.
 total number of unique Dates on which Bill has
been generated.
 List the minimum and Sum of all the Unit price of
items in the item table.
 SELECT MIN(UnitePrice),SUM (UnitPrice)
FROM Item;
 List total number of items in the item table.
 SELECT COUNT (*) FROM Item;
 List the total number of customer who have their
date of registration information in the customer
table.
 SELECT COUNT (DateOfReg)
FROM Costomer;
 total number of unique Dates on which Bill has
been generated.
 SELECT COUNT (*) FROM Item;
Grouping Data From Tables:
 Related rows can be grouped together by GROUP BY clause by
specifying a column as a grouping column.
 Tuples with the same value on all attributes in the group by clause
are placed in one group.
 Syntax:
 SELECT columnname, columnname FROM tablename
GROUP BY columnname;
 Eg. select state, count(cname) from college GROUP BY state;
STATE COUNT(CNAME)
CA 2
MA 1
NY 1
Introduction to sql
HAVING CLAUSE
 HAVING imposes a condition on the GROUP BY clause
 find unique values in the situations where DISTINCT
cannot apply.
 Syntax:
 SELECT columnname, columnname FROM tablename
GROUP BY columnname HAVING condition;
Eg. select state, count(cname) from college GROUP BY state
having count(cname)>1;
STATE COUNT(CNAME)
CA 2
 To retrieve the average unit price of all class of
items available in the item table.
 List all the classes of item whose average unit
price is greater than 500
 To retrieve the average unit price of all class of
items available in the item table.
 SELECT Class, AVG(UnitPrice)
FROM Item GROUP BY Class;
 List all the classes of item whose average unit
price is greater than 500
 SELECT Class, AVG( UnitPrice)
FROM Item
GROUP BY Class HAVING AVG(UnitPrice)
> 400;
DUAL table
 Dual: Dual table is owned by SYS. SYS owns the
data dictionary;
 Besides arithmetic calculations, it also supports
date retrieval and its formatting.
 Select 3.14*3*3 from DUAL;
 28.26
 Select 4/2 from DUAL;
 2
 Select sysdate from DUAL
 SYSDATE
 17-FEB-14
String functions
 accept character data as input and can return both
character and number values.
 LOWER (col/value)
 UPPER (col/value)
 INITCAP (col/value)
 SUBSTR (col/value, position, n)
 INSTR (col/value, ‘string’)
 ASCII (character)
 CHR (number)
 Lower: Returns char, with letters in lower case.
 Select LOWER(‘RAJeEv’) from dual ; // rajeev
 Upper: Returns char, with letters in upper case.
 Select UPPER(‘RAJeEv’) from dual ; // RAJEEV
 LENGTH
 Select length(‘Pratyush Mehrotra’) as Length from
dual ; //17
 SUBSTR(string, start_pos, length)
 Select SUBSTR(‘Prateek’, 4, 3) from dual ;
// Tee
 INSTR(string, string2, start_position, nth
appearance)
 Select instr(‘GLA University’, ‘i’, 1, 2) from dual;
// 12
 TRANSLATE
 Select translate(‘HTC launch a new phone on net’,
‘net’, ‘web’)as Translate from dual;
Number Functions:
 ROUND (col/val, n)
 TRUNC (col/val, n)
 CEIL (col/val)
 FLOOR (col/val)
 POWER (col/val, n)
 SQRT (col/val)
 EXP (n)
 ABS (col/val)
 MOD (value1, value2)
 ROUND(n, m) return rounded to m places to the
right of a decimal point. If m is omitted then n is
rounded to 0 places.
 Select ROUND(SUM(GPA)/COUNT(GPA)) as
“Round Average” from student ;
 Select round(15.81,1) from DUAL; //15.8
 ABSOLUTE: This function return absolute value
of numbers
 Select ABS(-15) from DUAL ; //15
 POWER: Return m raise to n where n must be an
integer.
 Select POWER(7,3) from DUAL ; // 343
 SQUARE ROOT: Return the square root of n. If
n<0 then NULL
 Select SQRT(25) from DUAL ; // 5
 EXPONENTIAL
 Select EXP(5) from DUAL ; //148.413159
 EXTRACT: Returns a value extracted from a date or
an interval.
 Select extract(month from sysdate)
from DUAL ;
 MOD: Return the remainder of first number divided
by second number passed as a parameter
 Select MOD(15,7) from DUAL ; //1
 TRUNCATE: Returns a truncated number to a certain
number of decimal places
 Select TRUNC(125.815,1) from dual ; // 125.8
 FLOOR: Returns the largest value that is equal to
or less than the number.
 Select floor(24.92 ) from dual ; //24
 CEILING: Return the largest value that is equal to
or greater than the number.
 Select ceil(24.92) from dual ; //25
Date Functions
 Date functions are used to manipulate and extract
values from the date column of a table.
 SYSDATE
 ADD_MONTHS (date, count)
 LAST_DAY (date)
 MONTHS_BETWEEN (date2, date1)
 NEXT_DAY (date, ‘day’)
 SYSDATE: returns the current date of the system
 Select SYSDATE from DUAL;
 ADD_MONTHS:
 Select add_months(date '1994-09-20',4) from dual ;
20-JAN-95
 LAST_DAY
 Select sysdate, last_day(sysdate) from dual ;
// 17-FEB-14 28-FEB-14
 MONTHS_BETWEEN (date2, date1)
 Select months_between(’12-jan-2014’,’12-mar-2014’)
from dual; // 2
 NEXT_DAY (date, ‘day’)
 Select next_day(’11-mar-2020’,monday) from dual; //
16-mar-20
Conversion Functions
 Converts one data type into another.
 TO_CHAR (input, format): Converts date or number
into character string.
 TO_DATE (date, format): Converts any date format to
default format (dd-mon-yy).
 TO_NUMBER (col/value): Converts a string into a
number.
 TO_CHAR(n,fmt): Converts a number to a
character or in different format from default
format(default date format : DD-MON-YY)
 Select TO_CHAR(sysdate, ‘Month DD, YYYY’) from
dual; // February 17, 2014
 Select TO_CHAR(sysdate, ‘DD-MM-YY’) from dual;
// 17-02-14
 TO_DATE: converts a character value into a
date value
 Select to_date(‘23/02/1988’, ‘DD/MM/YY’) from
DUAL ; // 23-FEB-88
View
 how we want to see the current data in our database
is Logical data. how this data is actually placed in
our database is Physical data.
 Views may be created for the following reasons:
 The DBA stores the views as a definition only. Hence
there is no duplication of data.
 Simplifies Questionnaires.
 Can be queried as a base table itself.
 Provides data security.
 Avoids data redundancy.
Creation of Views:-
 Syntax:-
CREATE VIEW viewname AS
SELECT columnname,columnname
FROM tablename
WHERE columnname=expression_list;
 create view lib_view as
select subject, author from library;
Renaming the columns of a view:-
 Syntax:-
 CREATE VIEW viewname (newcolumnname, … )
AS
SELECT columnname….
FROM tablename
WHERE columnname=expression_list;
create view lib_view1(A1, A2, A3) as select name,
docid,cellno from docdet where docid=12 ;
 Column names will be replaced as A1, A2, A3
Selecting a data set from a view-
 Syntax:-
SELECT columnname, columnname
FROM viewname
WHERE condition;
 select * from lib_view;
 Desc lib_view;
 select author from lib_view where subject='computer
science';
 Destroying a view-
 Syntax:- DROP VIEW viewname;
Update view
 Update viewname SET column1=value1,..
Where condition;
 update lib_view3 set libno=116 where name=’main’;
example
 Create a view of library having subject and author
attributes with the name as lib_view.
 create view lib_view as select subject, author from
library;
 Display all the information of lib_view.
 select * from lib_view;
 Display the structure of lib_view.
 Desc lib_view;
 Display the record having subject name computer
science in lib_view.
 select author from lib_view where subject='computer
science';
 Create a view (lib_view1) from table docdet having
name ,dob and cellno attributes (renamed) of doctor
whose id is 12.
 create view lib_view1(name, dob,cellno) as select
docname, docid,cellno from docdet where docid=12 ;
 Display the structure of lib_view1;
 desc lib_view1;
 Create a view (lib_view3) from table docdet having
name, addr and wardno attributes of doctor whose
id is 112.
 create view lib_view3(name,address,wardno) as select
name,docid,cellno from docdet where docid=112 with
check option;
 Update the lib_view3 view ;
 update lib_view3 SET libno=116 where name=’main’;
 Drop the lib_view.
 drop view lib_view;
Order of execution of query
SELECT
DISTINCT column,
AGG_FUNC(column_or_expression), … FROM
mytable
WHERE constraint_expression
GROUP BY column
HAVING constraint_expression
ORDER BY column ASC/DESC

More Related Content

PPTX
Introduction to SQL
Ehsan Hamzei
 
PPTX
introdution to SQL and SQL functions
farwa waqar
 
PPTX
Visual studio
AvinashChunduri2
 
PPTX
Excel training
Alexandru Gologan
 
PPTX
Introduction to databases
Bryan Corpuz
 
PPTX
OSI Model
Shubham Pendharkar
 
PPT
Marketing research
Arian Hadi
 
PPTX
SQL - Structured query language introduction
Smriti Jain
 
Introduction to SQL
Ehsan Hamzei
 
introdution to SQL and SQL functions
farwa waqar
 
Visual studio
AvinashChunduri2
 
Excel training
Alexandru Gologan
 
Introduction to databases
Bryan Corpuz
 
Marketing research
Arian Hadi
 
SQL - Structured query language introduction
Smriti Jain
 

What's hot (20)

PPTX
SQL Commands
Sachidananda M H
 
PPTX
SQL Basics
Hammad Rasheed
 
PPT
Mysql
TSUBHASHRI
 
PPTX
Sql commands
Pooja Dixit
 
PPTX
Basic sql Commands
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
PPTX
Sql queries presentation
NITISH KUMAR
 
PPTX
Basic SQL and History
SomeshwarMoholkar
 
PDF
SQL Overview
Stewart Rogers
 
PPT
Aggregate functions
sinhacp
 
PPTX
What is SQL Server?
CPD INDIA
 
PPT
SQL Tutorial - Basic Commands
1keydata
 
PPTX
SQL Queries Information
Nishant Munjal
 
ODP
Sql commands
Balakumaran Arunachalam
 
PPTX
SQL Joins.pptx
Ankit Rai
 
PPTX
SQL for interview
Aditya Kumar Tripathy
 
PPTX
SQL commands
GirdharRatne
 
PPTX
Group By, Having Clause and Order By clause
Deepam Aggarwal
 
PPT
Sql Server Basics
rainynovember12
 
PPT
Joins in SQL
Vigneshwaran Sankaran
 
SQL Commands
Sachidananda M H
 
SQL Basics
Hammad Rasheed
 
Mysql
TSUBHASHRI
 
Sql commands
Pooja Dixit
 
Basic sql Commands
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
Sql queries presentation
NITISH KUMAR
 
Basic SQL and History
SomeshwarMoholkar
 
SQL Overview
Stewart Rogers
 
Aggregate functions
sinhacp
 
What is SQL Server?
CPD INDIA
 
SQL Tutorial - Basic Commands
1keydata
 
SQL Queries Information
Nishant Munjal
 
SQL Joins.pptx
Ankit Rai
 
SQL for interview
Aditya Kumar Tripathy
 
SQL commands
GirdharRatne
 
Group By, Having Clause and Order By clause
Deepam Aggarwal
 
Sql Server Basics
rainynovember12
 
Joins in SQL
Vigneshwaran Sankaran
 
Ad

Similar to Introduction to sql (20)

PPT
Les09 (using ddl statements to create and manage tables)
Achmad Solichin
 
PPT
Les09
Sudharsan S
 
PDF
Rdbms day3
Nitesh Singh
 
PPTX
Physical Design and Development
Er. Nawaraj Bhandari
 
PPTX
Introduction to sql new
SANTOSH RATH
 
PPTX
SQL: Data Definition Language(DDL) command
sonali sonavane
 
PPT
PHP mysql Sql
Mudasir Syed
 
DOCX
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
SakkaravarthiS1
 
DOC
Module 3
cs19club
 
PPTX
Database
NoorullahZamindar
 
PPTX
Session 6#
Mohamed Samir
 
PPT
Sql database object
Luis Goldster
 
PPT
Sql database object
David Hoen
 
PPT
Sql database object
Harry Potter
 
PPT
Sql database object
Fraboni Ec
 
PPT
Sql database object
Young Alista
 
PPT
Sql database object
James Wong
 
PPT
Sql database object
Tony Nguyen
 
PDF
Ankit
Ankit Dubey
 
PPTX
SQL commands powerpoint presentation. Ppt
umadevikakarlapudi
 
Les09 (using ddl statements to create and manage tables)
Achmad Solichin
 
Rdbms day3
Nitesh Singh
 
Physical Design and Development
Er. Nawaraj Bhandari
 
Introduction to sql new
SANTOSH RATH
 
SQL: Data Definition Language(DDL) command
sonali sonavane
 
PHP mysql Sql
Mudasir Syed
 
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
SakkaravarthiS1
 
Module 3
cs19club
 
Session 6#
Mohamed Samir
 
Sql database object
Luis Goldster
 
Sql database object
David Hoen
 
Sql database object
Harry Potter
 
Sql database object
Fraboni Ec
 
Sql database object
Young Alista
 
Sql database object
James Wong
 
Sql database object
Tony Nguyen
 
SQL commands powerpoint presentation. Ppt
umadevikakarlapudi
 
Ad

More from VARSHAKUMARI49 (17)

PPT
28,29. procedures subprocedure,type checking functions in VBScript
VARSHAKUMARI49
 
PPT
30,31,32,33. decision and loop statements in vbscript
VARSHAKUMARI49
 
PPT
27. mathematical, date and time functions in VB Script
VARSHAKUMARI49
 
PPT
Cascading style sheet
VARSHAKUMARI49
 
PPT
Introduction to web technology
VARSHAKUMARI49
 
PPT
Database normalization
VARSHAKUMARI49
 
PPT
Joins
VARSHAKUMARI49
 
PPT
Sub queries
VARSHAKUMARI49
 
PPT
Vbscript
VARSHAKUMARI49
 
PPTX
Css module1
VARSHAKUMARI49
 
PPT
Js mod1
VARSHAKUMARI49
 
PPTX
Css mod1
VARSHAKUMARI49
 
PPT
Html mod1
VARSHAKUMARI49
 
PPT
Register counters.readonly
VARSHAKUMARI49
 
PPT
Sorting.ppt read only
VARSHAKUMARI49
 
PPT
Hashing
VARSHAKUMARI49
 
28,29. procedures subprocedure,type checking functions in VBScript
VARSHAKUMARI49
 
30,31,32,33. decision and loop statements in vbscript
VARSHAKUMARI49
 
27. mathematical, date and time functions in VB Script
VARSHAKUMARI49
 
Cascading style sheet
VARSHAKUMARI49
 
Introduction to web technology
VARSHAKUMARI49
 
Database normalization
VARSHAKUMARI49
 
Sub queries
VARSHAKUMARI49
 
Vbscript
VARSHAKUMARI49
 
Css module1
VARSHAKUMARI49
 
Css mod1
VARSHAKUMARI49
 
Html mod1
VARSHAKUMARI49
 
Register counters.readonly
VARSHAKUMARI49
 
Sorting.ppt read only
VARSHAKUMARI49
 

Recently uploaded (20)

PPT
Understanding the Key Components and Parts of a Drone System.ppt
Siva Reddy
 
PDF
Packaging Tips for Stainless Steel Tubes and Pipes
heavymetalsandtubes
 
PDF
CAD-CAM U-1 Combined Notes_57761226_2025_04_22_14_40.pdf
shailendrapratap2002
 
PPT
1. SYSTEMS, ROLES, AND DEVELOPMENT METHODOLOGIES.ppt
zilow058
 
PDF
2025 Laurence Sigler - Advancing Decision Support. Content Management Ecommer...
Francisco Javier Mora Serrano
 
PDF
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
PDF
Zero Carbon Building Performance standard
BassemOsman1
 
PDF
The Effect of Artifact Removal from EEG Signals on the Detection of Epileptic...
Partho Prosad
 
PPTX
Victory Precisions_Supplier Profile.pptx
victoryprecisions199
 
PPTX
Tunnel Ventilation System in Kanpur Metro
220105053
 
PDF
Chad Ayach - A Versatile Aerospace Professional
Chad Ayach
 
PPTX
22PCOAM21 Session 1 Data Management.pptx
Guru Nanak Technical Institutions
 
PPTX
Civil Engineering Practices_BY Sh.JP Mishra 23.09.pptx
bineetmishra1990
 
PPTX
database slide on modern techniques for optimizing database queries.pptx
aky52024
 
PPTX
IoT_Smart_Agriculture_Presentations.pptx
poojakumari696707
 
PDF
LEAP-1B presedntation xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
hatem173148
 
PDF
Biodegradable Plastics: Innovations and Market Potential (www.kiu.ac.ug)
publication11
 
PDF
Construction of a Thermal Vacuum Chamber for Environment Test of Triple CubeS...
2208441
 
PDF
20ME702-Mechatronics-UNIT-1,UNIT-2,UNIT-3,UNIT-4,UNIT-5, 2025-2026
Mohanumar S
 
PPTX
business incubation centre aaaaaaaaaaaaaa
hodeeesite4
 
Understanding the Key Components and Parts of a Drone System.ppt
Siva Reddy
 
Packaging Tips for Stainless Steel Tubes and Pipes
heavymetalsandtubes
 
CAD-CAM U-1 Combined Notes_57761226_2025_04_22_14_40.pdf
shailendrapratap2002
 
1. SYSTEMS, ROLES, AND DEVELOPMENT METHODOLOGIES.ppt
zilow058
 
2025 Laurence Sigler - Advancing Decision Support. Content Management Ecommer...
Francisco Javier Mora Serrano
 
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
Zero Carbon Building Performance standard
BassemOsman1
 
The Effect of Artifact Removal from EEG Signals on the Detection of Epileptic...
Partho Prosad
 
Victory Precisions_Supplier Profile.pptx
victoryprecisions199
 
Tunnel Ventilation System in Kanpur Metro
220105053
 
Chad Ayach - A Versatile Aerospace Professional
Chad Ayach
 
22PCOAM21 Session 1 Data Management.pptx
Guru Nanak Technical Institutions
 
Civil Engineering Practices_BY Sh.JP Mishra 23.09.pptx
bineetmishra1990
 
database slide on modern techniques for optimizing database queries.pptx
aky52024
 
IoT_Smart_Agriculture_Presentations.pptx
poojakumari696707
 
LEAP-1B presedntation xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
hatem173148
 
Biodegradable Plastics: Innovations and Market Potential (www.kiu.ac.ug)
publication11
 
Construction of a Thermal Vacuum Chamber for Environment Test of Triple CubeS...
2208441
 
20ME702-Mechatronics-UNIT-1,UNIT-2,UNIT-3,UNIT-4,UNIT-5, 2025-2026
Mohanumar S
 
business incubation centre aaaaaaaaaaaaaa
hodeeesite4
 

Introduction to sql

  • 2. content  Introduction to SQL  Three types of SQL Statements  DDL  DML  DCL  Aggregate functions  Other functions(Date, string,..)  View
  • 3. SQL  SQL (Structured Query Language) is a nonprocedural language, you specify what you want, not how to get it. A block structured format of English key words is used in this Query language.  The process of requesting data from a Database and receiving back the results is called a Database Query and hence the name Structured Query Language.  SQL is language that all commercial RDBMS implementations understand.
  • 4. SQL  SQL developed at IBM by Donald D Chamberlinand Raymand F Boyce in 1970’s  Initially called SEQUEL(Structured English QUEry Language)  It is easy to learn, poratble in nature , and easy to create multiple views.
  • 5.  It has the following components.  DDL (Data Definition Language)  DML (DATA Manipulation Language)  View definition  Transaction Control  Integrity  Authorization
  • 6. Structured Query Language (SQL) Database SQL Request Data 01000101 11001010 01001011 Computer System DBMS
  • 7. General terms  Table : collection of data in tabular format  Tuples: row / record  Attributes : column name  Constrainst : conditions
  • 8. Three types of Statements  DDL is Data Definition Language statements. Some examples:  CREATE – to create objects in the database  ALTER – to alter the structure of the database  DROP – to delete objects from the database  TRUNCATE – to remove all records from a table. The space allocated for the records is also removed
  • 9. DML DML is Data Manipulation Language statements. Some examples:  SELECT – to retrieve data from the database  INSERT – to insert data into a table  UPDATE – to update existing data within a table  DELETE – to delete all records from a table. The space allocated for the records remains intact
  • 10. DCL  DCL is Data Control Language statements. Some examples:  GRANT – to give user access privileges to database objects  REVOKE – to withdraw access privileges given with the GRANT command  COMMIT – to save the work done  ROLLBACK – to restore database to original since the last COMMIT
  • 11. Data Types  The SQL standard supports a variety of built in domain types, including-  Char (n)- A fixed length character length string with user specified length .  Varchar (n)- A variable character length string with user specified maximum length n.  Number (p, d)-A Fixed point number with user defined precision.
  • 12. Data types  Float (n)- A floating point number, with precision of at least n digits.  Date- A calendar date containing a (four digit) year, month and day of the month. Standard format is DD- MON-YYYY  Time- The time of day, in hours, minutes and seconds Eg. Time ’09:30:00’.
  • 13. NULL  Missing/ unknown/ inapplicable data represented as a NULL value  NULL is not a data value. It is just an indicator that the value is unknown
  • 14. Operators  Arithmetic operators: +, -, *, /  Logical operators: AND, OR, NOT  Relational operators: =, <=, >=, < > , < , >  <> or != not equal to.
  • 15. Operators  The Arithmetic operators are used to calculate something like given in the example below:  Select * from employee where sal * 1.1 > 1000 ;  The logical operators are used to combine conditions like:  Select * from employee where (sal > 1000 AND age > 25);  The above two examples also illustrate the use of relational operators.
  • 16. To Create Table command  Create table command defines each column of the table uniquely.  Each column is described as a columnname, datatype and size  Each column is seperated by comma. Syntax: Create table tablename ( Column1 datatype(size), Column2 datatype(size),.. );
  • 17. Data Constraints  The constraints can either be placed at column level or at the table level.  Column Level Constraints: If the constraints are defined along with the column definition, it is called a column level constraint.  Table Level Constraints: If the data constraint attached to a specified column in a table reference the contents of another column in the table then the user will have to use table level constraints.
  • 18. List of most used Constraint  NOT NULL  DEFAULT  UNIQUE  CHECK  PRIMARY KEY  FOREIGN KEY  On delete cascade  On delete set null
  • 19. Null Value Concepts:  . Column of any data types may contain null values unless the column was defined as not null when the table was created.  Syntax:  Create table tablename (columnname data type (size) not null,…) Note: Not null constraint cannot be defined at table level.
  • 20. Primary Key  primary key is one or more columns is a table used to uniquely identify each row in the table. Primary key values must not be null and must be unique across the column.  Syntax: primary key as a column constraint  Create table tablename (columnname datatype (size) primary key,….)  Composite Primary key as a table constraint  Create table tablename(columnname datatype (size), columnname datatype( size),…, Primary key (columnname1,columnname2));
  • 21. Unique key concept  A unique key is similar to a primary key except that the purpose of a unique key is to ensure that information in the column for each record is unique as with telephone or devices license numbers.  Syntax: Unique as a column constraint.  Create table tablename (columnname datatype (size) unique);  Unique as table constraint:  Create table tablename (columnname datatype(size), columnname datatype(size), unique (columnname));
  • 22. Default value concept  At the time of column creation, a default value can be assigned to it.  Provides a default value for a column when none is specified.  Syntax:  Create table tablename (columnname datatype (size) default value,….);  Note: The default value constraint cannot be specified at table level.
  • 23. Foreign Key Concept  Foreign key represents relationship between tables. A foreign key is column whose values are derived from the primary key of the same attribute of some other table.  Foreign key as a column constraint  Syntax :  Create table tablename2 (columnname datatype(size) references another- tablename1(columnname1));
  • 24. Foreign Key Concept  Foreign key as a table constraint:  Syntax :  Create table tablename2 (columnname2 datatype(size)…. foreign key(columnname2) references tablename1(columnname1));
  • 25. Check Integrity Constraints  Use the check constraints when you need to enforce integrity rules that can be evaluated based on a logical expression.  Unique key as a column constraint  Syntax :  Create table tablename (columnname datatype(size) check(logical expression,….);
  • 26. Check Integrity Constraints  Unique key as a table constraint:  Syntax :  Create table tablename (columnname datatype(size), ….Check(logical expression));
  • 27. CREATE TABLE EXAMPLE Customer Table Colum name Datatype Description Constraints CustomerId Varchar2(6) Unique id generated for each customer Primary Key, Should start with ‘C’ CustomerName Varchar2(30) Name of the customer Not null DateOfReg Date Date on which the customer registered UserId Varchar2(15) Decided at the time of registration It should be unique Password Varchar2(15) Decided at the time of registration Not Null Implementing PRIMARY KEY ,NOT NULL and UNIQUE
  • 28. CREATE TABLE EXAMPLE EXAMPLE at column level : Create table Customer (CustomerId varchar2(6) primary key check (CustomerId like 'C%') , CustomerName varchar2(30) NOT NULL, DateofReg date , UserId varchar2(15) UNIQUE, Password varchar2(15) NOT NULL );
  • 29. Or At table level Create table Customer (CustomerId varchar2(6) , CustomerName varchar2(30) NOT NULL, DateofReg date , UserId varchar2(15), Password varchar2(15) NOT NULL, primary key(CustomerId), Unique(userId), check (CustomerId like 'C%') );
  • 30. Create Table (Contd…) BankInfo Table Colum name Datatype Description Constraints AccountNo Number(10) Account no of customer Composite Primary key CustomerId Varchar2(6) Unique id provided to each customer when he/she is registered to purchase items Foreign key referring to customer table Implementation of Composite Primary Key and Foreign Key Constraints
  • 31. EXAMPLE at column & table level: Create table Bankinfo (AccountNo number(10), CustomerId varchar2(6) references Customer(CustomerId), Primary key(AccountNo, CustomerId)); Or Create table Bankinfo (AccountNo number(10), CustomerId varchar2(6) , Foreign key (CustomerId) references Customer(CustomerId), Primary key(AccountNo, CustomerId));
  • 32. Modifying the Structure of Tables  Alter table command is used to changing the structure of a table.  Adding new columns:  Syntax:  ALTER TABLE tablename ADD newcolumnname newdatatype (size);
  • 33. Alter command..  Modifying existing table  Syntax:  ALTER TABLE tablename MODIFY (columnname newdatatype (size) constraint A constraint name);  Deleting a column  Syntax:  ALTER TABLE tablename DROP COLUMN columnname;
  • 34. Examples of alter command  ALTER TABLE Customer ADD Contact_Phone Char(10);  ALTER TABLE Customer MODIFY Contact_Phone Char(12);  ALTER TABLE Customer DROP COLUMN Contact_Phone;
  • 35. Add/ drop Constrainst using Alter  To add constrainst:  Syntax: ALTER TABLE tablename ADD Constraintname (columnname); Eg alter table Customer Add primary key(CustomerId);  To drop constrainst:  Syntax: ALTER TABLE tablename DROP Constraintname; Eg alter table Customer drop primary key;
  • 36. Add/ drop Constrainst using Alter  To add constrainst:  Syntax: ALTER TABLE tablename ADD constraint A Constraintname (columnname); Eg alter table Customer Add constraint A primary key(CustomerId);  To drop constrainst:  Syntax: ALTER TABLE tablename DROP constraint A; Eg alter table Customer drop A;
  • 37. To display the structure of the table  Used to display the information about the columns defined in a table  Syntax: DESCRIBE Tablename; Or DESC tablename
  • 38. Removing/Deleting Tables-  DROP TABLE  Deletes table structure  Cannot be recovered  Use with caution  Syntax: DROP TABLE tablename;  Truncate Table  Deleting All Rows of a table  faster than delete command(DML)  Cannot be recovered  Syntax: TRUNCATE TABLE tablename;
  • 39. Renaming Tables  Used to rename the table  Syntax:  RENAME tablename to Newtablename  Eg RENAME Customer to Customer_DATA
  • 40. DML INSERT :  Used to insert a single row of data into the table.  if columnname is not specified by default values will be as same order of column names of the table  Syntax:  INSERT INTO tablename (Column1, column2,…) VALUES(expression1,expression2,…)  Eg Insert into Customer values(‘C1001’,’Amit’,’11-Jan- 2012’, ‘amit_12’,’amit’);
  • 43. VIEWING Data in table  To display all columns and all rows  Syntax: SELECT * FROM tablename;  Or  SELECT Column1, column2,..,columnN FROM tablename;  To display selected columns and all row:  Syntax:  SELECT Column1, column2 FROM tablename;  Eg  select * from Customer;  Select CustomerId, DateOfReg from Customer;
  • 44. VIEWING Data in table  To view selected column and filtered data  Syntax:  SELECT Column1, column2 FROM tablename WHERE condition;  To view all columns and filtered data  Syntax:  SELECT * FROM tablename WHERE condition;  Eg.  Select * from Customer where DateOfReg = ’11- Jan-2011’  Select UserId, password from Customer where DateOfReg = ’11-Jan-2011’
  • 46. Eliminating Duplicate rows using SELECT command  Distinct clause removes duplicate rows from the result-set  Syntax:  SELECT DISTINCT Column1,column2 FROM tablename  SELECT DISTINCT * FROM tablename  SELECT DISTINCT * FROM tablename where condition Eg Select distinct * from Customer; Select distinct UserId from Customer where DateOfReg = ’11-Jan- 2011’; Select distinct CustomerName from Customer where DateOfReg = ’11-Jan-2011’;
  • 47. UPDATING the Content of Table  Updating all rows:  Syntax:  UPDATE tablename SET column1=expression1 , column2 = expression2;  Updating selected rows , where clause is used:  Syntax:  UPDATE tablename SET column1=expression1 , column2 = expression2 Where condition; Eg. Update Customer set UserId= ‘abca_12’, password = 123 where CustomerId = ‘C1002’;
  • 48. DELETING Rows from Table  Delete all rows  Syntax : DELETE FROM tablename;  Delete specific rows  Syntax : DELETE FROM tablename WHERE condition;  Eg. Delete from Customer where UserId= ‘abcd_12’;
  • 50. DCL  DCL is Data Control Language statements. Some examples:  GRANT – to give user access privileges to database objects  Syntax : GRANT permission to username;  Eg GRANT CREATE TABLE TO amit;  REVOKE – to withdraw access privileges given with the GRANT command  Syntax: REVOKE permission FROM username;
  • 51. DCL…  COMMIT – to save the work done  Syntax: COMMIT;  SAVEPOINT - to temporarily save a transaction so that you can rollback to that point whenever required.  Syntax: SAVEPOINT savepoint_name;  ROLLBACK – to restore database to original since the last COMMIT  Syntax: ROLLBACK TO savepoint_name;
  • 52. Computation in expression lists used to select data:-  Renaming columns used with Expression Lists: - The default output column names can be renamed by the user if required  Syntax:  Select column1 as result_column1, column2 as result_column2 From tablename;  Logical Operators:  The logical operators that can be used in SQL sentenced are  AND all of must be included  OR any of may be included  NOT none of could be included
  • 53.  Range Searching: Between operation is used for range searching.  Pattern Searching:  The most commonly used operation on string is pattern matching using the operation ‘like’ we describe patterns by using two special characters.  Percent (%): the % character matches any substring we consider the following examples.  ‘Perry %’ matches any string beginning with perry  ‘% idge % matches any string containing’ idge as substring.  ‘ - - - ‘ matches any string exactly three characters.  ‘ - - - % matches any string of at least of three characters.
  • 54.  Ordering tuples in a particular order:  The ‘order by’ clause is used to sort the table data according to one or more columns of the table.  By default sorted in ascending order.  Syntax:  select colname1, colname2,… from tablename where condition order by colname1 asc/desc, colname2 asc/desc,…;
  • 55. Examples  List all items whose unit price is > 100  List the CustomerId and UserId of ‘Allan’  List all items where discount is at least 10 percent.
  • 56. Examples  List all items whose unit price is > 100  SELECT ItemId, ItemName FROM Item WHERE UnitPrice > 100;  List the CustomerId and UserId of ‘Allan’  SELECT CustomerId, UderId FROM Customer WHERE CustomerName = ‘Allan’;  List all items where discount is at least 10 percent.  SELECT ItemId,ItemName FROM Item WHERE Discount >= 10;
  • 57. Examples  List all items where Unit Price is less than 100 and Unit of measurement is ‘Dozen’.  List all items where either the unit price is less than 100 or Unit of measurement is ‘Dozen’
  • 58. Examples  List all items where Unit Price is less than 100 and Unit of measurement is ‘Dozen’.  SELECT ItemId, ItemName FROM Item WHERE UnitPrice < 100 AND UnitOfMeasurement = ‘Dozen’;  List all items where either the unit price is less than 100 or Unit of measurement is ‘Dozen’  SELECT ItemId, ItemName FROM Item WHERE UnitPrice < 100 OR UnitOfMeasurement = ‘Dozen’;
  • 59. NOT and BETWEEN  List all items whose Unit Price is not less than 100 .  The BETWEEN operator is used to test a range.  List all items with Unit Price in the range 100 to 200 .
  • 60. NOT and BETWEEN  List all items whose Unit Price is not less than 100 .  SELECT ItemId,ItemName FROM Item WHERE NOT UnitPrice < 100;  The BETWEEN operator is used to test a range.  List all items with Unit Price in the range 100 to 200 .  SELECT ItemId,ItemName FROM Item WHERE UnitPrice BETWEEN 100 AND 200; OR  SELECT ItemId, ItemName FROM Item WHERE UnitPrice >= 100 AND UnitPrice <= 200;
  • 61. IN and NOT IN: - used to test a membership condition  List all items which have Unit of measurement as ‘Kilogram’ or ’Dozen’.
  • 62. IN and NOT IN: - used to test a membership condition  List all items which have Unit of measurement as ‘Kilogram’ or ’Dozen’.  SELECT ItemId,ItemName FROM Item WHERE UnitOfMeasurement = ‘Kilogram’ OR UnitOfMeasurement = ‘Dozen’; OR  SELECT ItemId,ItemName FROM Item WHERE UnitOfMeasurement IN(‘Kilogram’,‘Dozen’);
  • 63. LIKE  The LIKE operator is used to perform pattern matching.  List all Customers whose name starts with ‘A’ and has ‘l’ as the second character  List all Customer whoses name has ‘a’ as the second character and has length five.
  • 64. LIKE  The LIKE operator is used to perform pattern matching.  List all Customers whose name starts with ‘A’ and has ‘l’ as the second character  SELECT CustomerName FROM Customer WHERE CustomerName LIKE ‘Al%’;  List all Customer whoses name has ‘a’ as the second character and has length five.  SELECT CustomerName FROM Customer WHERE CustomerName LIKE ‘_a___’;
  • 65. IS NULL  IS NULL evaluates to TRUE if the value is NULL.  IS NOT NULL evaluates to TRUE is the value is not NULL.  List customers whose date of registration is not available.  List customers whose date of registration is known.
  • 66. IS NULL  IS NULL evaluates to TRUE if the value is NULL.  IS NOT NULL evaluates to TRUE is the value is not NULL.  List customers whose date of registration is not available.  SELECT CustomerName FROM Customer WHERE DateOfReg IS NULL;  List customers whose date of registration is known.  SELECT CustomerName FROM Customer WHERE DateOfReg IS NOT NULL;
  • 67. Order by  List the Items of the retail application in the increasing order of their unit price  List the items in their decreasing order of quantity on hand and increasing order of discount.
  • 68. Order by  List the Items of the retail application in the increasing order of their unit price  SELECT ItemName FROM Item ORDER BY UnitPrice asc/desc;  List the items in their decreasing order of quantity on hand and increasing order of discount.  SELECT ItemId ,ItemName ,QtyOnHand ,Discount FROM Item ORDER BY 3 DESC, 4;
  • 69. AGGREGATE/GROUP FUNCTION  Group functions operate on set of rows, result is based on group of rows rather than one result per row as returned by single row functions. 1)Avg() : return average value of n  Syntax: Avg ([distinct/all] n) 2)Min() : return minimum value of expr.  Syntax: MIN([distinct/all] expr) 3)Max () : Return max value of expr  Syntax: Max ([distinct/all]expr)
  • 70. AGGREGATE/GROUP FUNCTION 4) Count() : Returns the no of rows where expr is not null  Syntax: Count ([distinct/all] expr)  Count (*) Returns the no rows in the table, including duplicates and those with nulls. 5) Sum() : Returns sum of values of n  Syntax: Sum ([distinct/all]n)
  • 71. Examples:  Select AVG(GPA) as ‘Average GPA’ from student;  Select AVG(DISTINCT GPA) as “Distinct GPA” from student  Select MIN(GPA) as “Minimum GPA” from student  Select COUNT(*) from student  Select MAX(GPA) from student  Select SUM(GPA) from student
  • 72. Aggregate functions  List the minimum unit price from item table.  List the maximum Unit price in the item table.  List the average Unit price of Class A items in the item table.
  • 73. Aggregate functions  List the minimum unit price from item table.  SELECT MIN (UnitPrice) FROM Item;  List the maximum Unit price in the item table.  SELECT MAX(Total_Dollars) FROM Customer_Transaction;  List the average Unit price of Class A items in the item table.  SELECT AVG (UnitPrice) FROM Item where Class=‘A’;
  • 74.  List the minimum and Sum of all the Unit price of items in the item table.  List total number of items in the item table.  List the total number of customer who have their date of registration information in the customer table.  total number of unique Dates on which Bill has been generated.
  • 75.  List the minimum and Sum of all the Unit price of items in the item table.  SELECT MIN(UnitePrice),SUM (UnitPrice) FROM Item;  List total number of items in the item table.  SELECT COUNT (*) FROM Item;  List the total number of customer who have their date of registration information in the customer table.  SELECT COUNT (DateOfReg) FROM Costomer;  total number of unique Dates on which Bill has been generated.  SELECT COUNT (*) FROM Item;
  • 76. Grouping Data From Tables:  Related rows can be grouped together by GROUP BY clause by specifying a column as a grouping column.  Tuples with the same value on all attributes in the group by clause are placed in one group.  Syntax:  SELECT columnname, columnname FROM tablename GROUP BY columnname;  Eg. select state, count(cname) from college GROUP BY state; STATE COUNT(CNAME) CA 2 MA 1 NY 1
  • 78. HAVING CLAUSE  HAVING imposes a condition on the GROUP BY clause  find unique values in the situations where DISTINCT cannot apply.  Syntax:  SELECT columnname, columnname FROM tablename GROUP BY columnname HAVING condition; Eg. select state, count(cname) from college GROUP BY state having count(cname)>1; STATE COUNT(CNAME) CA 2
  • 79.  To retrieve the average unit price of all class of items available in the item table.  List all the classes of item whose average unit price is greater than 500
  • 80.  To retrieve the average unit price of all class of items available in the item table.  SELECT Class, AVG(UnitPrice) FROM Item GROUP BY Class;  List all the classes of item whose average unit price is greater than 500  SELECT Class, AVG( UnitPrice) FROM Item GROUP BY Class HAVING AVG(UnitPrice) > 400;
  • 81. DUAL table  Dual: Dual table is owned by SYS. SYS owns the data dictionary;  Besides arithmetic calculations, it also supports date retrieval and its formatting.  Select 3.14*3*3 from DUAL;  28.26  Select 4/2 from DUAL;  2  Select sysdate from DUAL  SYSDATE  17-FEB-14
  • 82. String functions  accept character data as input and can return both character and number values.  LOWER (col/value)  UPPER (col/value)  INITCAP (col/value)  SUBSTR (col/value, position, n)  INSTR (col/value, ‘string’)  ASCII (character)  CHR (number)
  • 83.  Lower: Returns char, with letters in lower case.  Select LOWER(‘RAJeEv’) from dual ; // rajeev  Upper: Returns char, with letters in upper case.  Select UPPER(‘RAJeEv’) from dual ; // RAJEEV  LENGTH  Select length(‘Pratyush Mehrotra’) as Length from dual ; //17
  • 84.  SUBSTR(string, start_pos, length)  Select SUBSTR(‘Prateek’, 4, 3) from dual ; // Tee  INSTR(string, string2, start_position, nth appearance)  Select instr(‘GLA University’, ‘i’, 1, 2) from dual; // 12  TRANSLATE  Select translate(‘HTC launch a new phone on net’, ‘net’, ‘web’)as Translate from dual;
  • 85. Number Functions:  ROUND (col/val, n)  TRUNC (col/val, n)  CEIL (col/val)  FLOOR (col/val)  POWER (col/val, n)  SQRT (col/val)  EXP (n)  ABS (col/val)  MOD (value1, value2)
  • 86.  ROUND(n, m) return rounded to m places to the right of a decimal point. If m is omitted then n is rounded to 0 places.  Select ROUND(SUM(GPA)/COUNT(GPA)) as “Round Average” from student ;  Select round(15.81,1) from DUAL; //15.8  ABSOLUTE: This function return absolute value of numbers  Select ABS(-15) from DUAL ; //15
  • 87.  POWER: Return m raise to n where n must be an integer.  Select POWER(7,3) from DUAL ; // 343  SQUARE ROOT: Return the square root of n. If n<0 then NULL  Select SQRT(25) from DUAL ; // 5  EXPONENTIAL  Select EXP(5) from DUAL ; //148.413159
  • 88.  EXTRACT: Returns a value extracted from a date or an interval.  Select extract(month from sysdate) from DUAL ;  MOD: Return the remainder of first number divided by second number passed as a parameter  Select MOD(15,7) from DUAL ; //1  TRUNCATE: Returns a truncated number to a certain number of decimal places  Select TRUNC(125.815,1) from dual ; // 125.8
  • 89.  FLOOR: Returns the largest value that is equal to or less than the number.  Select floor(24.92 ) from dual ; //24  CEILING: Return the largest value that is equal to or greater than the number.  Select ceil(24.92) from dual ; //25
  • 90. Date Functions  Date functions are used to manipulate and extract values from the date column of a table.  SYSDATE  ADD_MONTHS (date, count)  LAST_DAY (date)  MONTHS_BETWEEN (date2, date1)  NEXT_DAY (date, ‘day’)
  • 91.  SYSDATE: returns the current date of the system  Select SYSDATE from DUAL;  ADD_MONTHS:  Select add_months(date '1994-09-20',4) from dual ; 20-JAN-95  LAST_DAY  Select sysdate, last_day(sysdate) from dual ; // 17-FEB-14 28-FEB-14
  • 92.  MONTHS_BETWEEN (date2, date1)  Select months_between(’12-jan-2014’,’12-mar-2014’) from dual; // 2  NEXT_DAY (date, ‘day’)  Select next_day(’11-mar-2020’,monday) from dual; // 16-mar-20
  • 93. Conversion Functions  Converts one data type into another.  TO_CHAR (input, format): Converts date or number into character string.  TO_DATE (date, format): Converts any date format to default format (dd-mon-yy).  TO_NUMBER (col/value): Converts a string into a number.
  • 94.  TO_CHAR(n,fmt): Converts a number to a character or in different format from default format(default date format : DD-MON-YY)  Select TO_CHAR(sysdate, ‘Month DD, YYYY’) from dual; // February 17, 2014  Select TO_CHAR(sysdate, ‘DD-MM-YY’) from dual; // 17-02-14  TO_DATE: converts a character value into a date value  Select to_date(‘23/02/1988’, ‘DD/MM/YY’) from DUAL ; // 23-FEB-88
  • 95. View  how we want to see the current data in our database is Logical data. how this data is actually placed in our database is Physical data.  Views may be created for the following reasons:  The DBA stores the views as a definition only. Hence there is no duplication of data.  Simplifies Questionnaires.  Can be queried as a base table itself.  Provides data security.  Avoids data redundancy.
  • 96. Creation of Views:-  Syntax:- CREATE VIEW viewname AS SELECT columnname,columnname FROM tablename WHERE columnname=expression_list;  create view lib_view as select subject, author from library;
  • 97. Renaming the columns of a view:-  Syntax:-  CREATE VIEW viewname (newcolumnname, … ) AS SELECT columnname…. FROM tablename WHERE columnname=expression_list; create view lib_view1(A1, A2, A3) as select name, docid,cellno from docdet where docid=12 ;  Column names will be replaced as A1, A2, A3
  • 98. Selecting a data set from a view-  Syntax:- SELECT columnname, columnname FROM viewname WHERE condition;  select * from lib_view;  Desc lib_view;  select author from lib_view where subject='computer science';  Destroying a view-  Syntax:- DROP VIEW viewname;
  • 99. Update view  Update viewname SET column1=value1,.. Where condition;  update lib_view3 set libno=116 where name=’main’;
  • 101.  Create a view of library having subject and author attributes with the name as lib_view.  create view lib_view as select subject, author from library;  Display all the information of lib_view.  select * from lib_view;  Display the structure of lib_view.  Desc lib_view;  Display the record having subject name computer science in lib_view.  select author from lib_view where subject='computer science';
  • 102.  Create a view (lib_view1) from table docdet having name ,dob and cellno attributes (renamed) of doctor whose id is 12.  create view lib_view1(name, dob,cellno) as select docname, docid,cellno from docdet where docid=12 ;  Display the structure of lib_view1;  desc lib_view1;
  • 103.  Create a view (lib_view3) from table docdet having name, addr and wardno attributes of doctor whose id is 112.  create view lib_view3(name,address,wardno) as select name,docid,cellno from docdet where docid=112 with check option;  Update the lib_view3 view ;  update lib_view3 SET libno=116 where name=’main’;  Drop the lib_view.  drop view lib_view;
  • 104. Order of execution of query SELECT DISTINCT column, AGG_FUNC(column_or_expression), … FROM mytable WHERE constraint_expression GROUP BY column HAVING constraint_expression ORDER BY column ASC/DESC