SlideShare a Scribd company logo
1 of 104
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’
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
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

What's hot

Structured query language(sql)ppt
Structured query language(sql)pptStructured query language(sql)ppt
Structured query language(sql)pptGowarthini
 
Nested Queries Lecture
Nested Queries LectureNested Queries Lecture
Nested Queries LectureFelipe Costa
 
Group By, Order By, and Aliases in SQL
Group By, Order By, and Aliases in SQLGroup By, Order By, and Aliases in SQL
Group By, Order By, and Aliases in SQLMSB Academy
 
Presentation slides of Sequence Query Language (SQL)
Presentation slides of Sequence Query Language (SQL)Presentation slides of Sequence Query Language (SQL)
Presentation slides of Sequence Query Language (SQL)Punjab University
 
Types Of Join In Sql Server - Join With Example In Sql Server
Types Of Join In Sql Server - Join With Example In Sql ServerTypes Of Join In Sql Server - Join With Example In Sql Server
Types Of Join In Sql Server - Join With Example In Sql Serverprogrammings guru
 
SQL Queries Information
SQL Queries InformationSQL Queries Information
SQL Queries InformationNishant Munjal
 
Including Constraints -Oracle Data base
Including Constraints -Oracle Data base Including Constraints -Oracle Data base
Including Constraints -Oracle Data base Salman Memon
 
Sql queries presentation
Sql queries presentationSql queries presentation
Sql queries presentationNITISH KUMAR
 

What's hot (20)

SQL Commands
SQL Commands SQL Commands
SQL Commands
 
Structured query language(sql)ppt
Structured query language(sql)pptStructured query language(sql)ppt
Structured query language(sql)ppt
 
Nested Queries Lecture
Nested Queries LectureNested Queries Lecture
Nested Queries Lecture
 
SQL subquery
SQL subquerySQL subquery
SQL subquery
 
Aggregate function
Aggregate functionAggregate function
Aggregate function
 
SQL Functions
SQL FunctionsSQL Functions
SQL Functions
 
Sql Constraints
Sql ConstraintsSql Constraints
Sql Constraints
 
SQL
SQLSQL
SQL
 
Joins in SQL
Joins in SQLJoins in SQL
Joins in SQL
 
Group By, Order By, and Aliases in SQL
Group By, Order By, and Aliases in SQLGroup By, Order By, and Aliases in SQL
Group By, Order By, and Aliases in SQL
 
Presentation slides of Sequence Query Language (SQL)
Presentation slides of Sequence Query Language (SQL)Presentation slides of Sequence Query Language (SQL)
Presentation slides of Sequence Query Language (SQL)
 
SQL Overview
SQL OverviewSQL Overview
SQL Overview
 
Types Of Join In Sql Server - Join With Example In Sql Server
Types Of Join In Sql Server - Join With Example In Sql ServerTypes Of Join In Sql Server - Join With Example In Sql Server
Types Of Join In Sql Server - Join With Example In Sql Server
 
SQL JOIN
SQL JOINSQL JOIN
SQL JOIN
 
SQL Queries Information
SQL Queries InformationSQL Queries Information
SQL Queries Information
 
Including Constraints -Oracle Data base
Including Constraints -Oracle Data base Including Constraints -Oracle Data base
Including Constraints -Oracle Data base
 
Sql joins
Sql joinsSql joins
Sql joins
 
Sql queries presentation
Sql queries presentationSql queries presentation
Sql queries presentation
 
Trigger
TriggerTrigger
Trigger
 
DATABASE CONSTRAINTS
DATABASE CONSTRAINTSDATABASE CONSTRAINTS
DATABASE CONSTRAINTS
 

Similar to Introduction to sql

Similar to Introduction to sql (20)

Les09 (using ddl statements to create and manage tables)
Les09 (using ddl statements to create and manage tables)Les09 (using ddl statements to create and manage tables)
Les09 (using ddl statements to create and manage tables)
 
Les09
Les09Les09
Les09
 
Rdbms day3
Rdbms day3Rdbms day3
Rdbms day3
 
Physical Design and Development
Physical Design and DevelopmentPhysical Design and Development
Physical Design and Development
 
Introduction to sql new
Introduction to sql newIntroduction to sql new
Introduction to sql new
 
PHP mysql Sql
PHP mysql  SqlPHP mysql  Sql
PHP mysql Sql
 
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
 
Module 3
Module 3Module 3
Module 3
 
Database
Database Database
Database
 
Session 6#
Session 6#Session 6#
Session 6#
 
Sql database object
Sql database objectSql database object
Sql database object
 
Sql database object
Sql database objectSql database object
Sql database object
 
Sql database object
Sql database objectSql database object
Sql database object
 
Sql database object
Sql database objectSql database object
Sql database object
 
Sql database object
Sql database objectSql database object
Sql database object
 
Sql database object
Sql database objectSql database object
Sql database object
 
Sql database object
Sql database objectSql database object
Sql database object
 
Ankit
AnkitAnkit
Ankit
 
12 SQL
12 SQL12 SQL
12 SQL
 
12 SQL
12 SQL12 SQL
12 SQL
 

More from VARSHAKUMARI49

More from VARSHAKUMARI49 (17)

28,29. procedures subprocedure,type checking functions in VBScript
28,29. procedures  subprocedure,type checking functions in VBScript28,29. procedures  subprocedure,type checking functions in VBScript
28,29. procedures subprocedure,type checking functions in VBScript
 
30,31,32,33. decision and loop statements in vbscript
30,31,32,33. decision and loop statements in vbscript30,31,32,33. decision and loop statements in vbscript
30,31,32,33. decision and loop statements in vbscript
 
27. mathematical, date and time functions in VB Script
27. mathematical, date and time  functions in VB Script27. mathematical, date and time  functions in VB Script
27. mathematical, date and time functions in VB Script
 
Cascading style sheet
Cascading style sheetCascading style sheet
Cascading style sheet
 
Html
HtmlHtml
Html
 
Introduction to web technology
Introduction to web technologyIntroduction to web technology
Introduction to web technology
 
Database normalization
Database normalizationDatabase normalization
Database normalization
 
Joins
JoinsJoins
Joins
 
Sub queries
Sub queriesSub queries
Sub queries
 
Vbscript
VbscriptVbscript
Vbscript
 
Css module1
Css module1Css module1
Css module1
 
Js mod1
Js mod1Js mod1
Js mod1
 
Css mod1
Css mod1Css mod1
Css mod1
 
Html mod1
Html mod1Html mod1
Html mod1
 
Register counters.readonly
Register counters.readonlyRegister counters.readonly
Register counters.readonly
 
Sorting.ppt read only
Sorting.ppt read onlySorting.ppt read only
Sorting.ppt read only
 
Hashing
HashingHashing
Hashing
 

Recently uploaded

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXssuser89054b
 
Max. shear stress theory-Maximum Shear Stress Theory ​ Maximum Distortional ...
Max. shear stress theory-Maximum Shear Stress Theory ​  Maximum Distortional ...Max. shear stress theory-Maximum Shear Stress Theory ​  Maximum Distortional ...
Max. shear stress theory-Maximum Shear Stress Theory ​ Maximum Distortional ...ronahami
 
Post office management system project ..pdf
Post office management system project ..pdfPost office management system project ..pdf
Post office management system project ..pdfKamal Acharya
 
Convergence of Robotics and Gen AI offers excellent opportunities for Entrepr...
Convergence of Robotics and Gen AI offers excellent opportunities for Entrepr...Convergence of Robotics and Gen AI offers excellent opportunities for Entrepr...
Convergence of Robotics and Gen AI offers excellent opportunities for Entrepr...ssuserdfc773
 
Digital Communication Essentials: DPCM, DM, and ADM .pptx
Digital Communication Essentials: DPCM, DM, and ADM .pptxDigital Communication Essentials: DPCM, DM, and ADM .pptx
Digital Communication Essentials: DPCM, DM, and ADM .pptxpritamlangde
 
Ground Improvement Technique: Earth Reinforcement
Ground Improvement Technique: Earth ReinforcementGround Improvement Technique: Earth Reinforcement
Ground Improvement Technique: Earth ReinforcementDr. Deepak Mudgal
 
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxS1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxSCMS School of Architecture
 
Computer Graphics Introduction To Curves
Computer Graphics Introduction To CurvesComputer Graphics Introduction To Curves
Computer Graphics Introduction To CurvesChandrakantDivate1
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdfAldoGarca30
 
👉 Yavatmal Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top Class Call Girl S...
👉 Yavatmal Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top Class Call Girl S...👉 Yavatmal Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top Class Call Girl S...
👉 Yavatmal Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top Class Call Girl S...manju garg
 
8th International Conference on Soft Computing, Mathematics and Control (SMC ...
8th International Conference on Soft Computing, Mathematics and Control (SMC ...8th International Conference on Soft Computing, Mathematics and Control (SMC ...
8th International Conference on Soft Computing, Mathematics and Control (SMC ...josephjonse
 
fitting shop and tools used in fitting shop .ppt
fitting shop and tools used in fitting shop .pptfitting shop and tools used in fitting shop .ppt
fitting shop and tools used in fitting shop .pptAfnanAhmad53
 
Introduction to Robotics in Mechanical Engineering.pptx
Introduction to Robotics in Mechanical Engineering.pptxIntroduction to Robotics in Mechanical Engineering.pptx
Introduction to Robotics in Mechanical Engineering.pptxhublikarsn
 
Memory Interfacing of 8086 with DMA 8257
Memory Interfacing of 8086 with DMA 8257Memory Interfacing of 8086 with DMA 8257
Memory Interfacing of 8086 with DMA 8257subhasishdas79
 
Introduction to Geographic Information Systems
Introduction to Geographic Information SystemsIntroduction to Geographic Information Systems
Introduction to Geographic Information SystemsAnge Felix NSANZIYERA
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startQuintin Balsdon
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaOmar Fathy
 
8086 Microprocessor Architecture: 16-bit microprocessor
8086 Microprocessor Architecture: 16-bit microprocessor8086 Microprocessor Architecture: 16-bit microprocessor
8086 Microprocessor Architecture: 16-bit microprocessorAshwiniTodkar4
 
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwaitjaanualu31
 

Recently uploaded (20)

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
Max. shear stress theory-Maximum Shear Stress Theory ​ Maximum Distortional ...
Max. shear stress theory-Maximum Shear Stress Theory ​  Maximum Distortional ...Max. shear stress theory-Maximum Shear Stress Theory ​  Maximum Distortional ...
Max. shear stress theory-Maximum Shear Stress Theory ​ Maximum Distortional ...
 
Post office management system project ..pdf
Post office management system project ..pdfPost office management system project ..pdf
Post office management system project ..pdf
 
Convergence of Robotics and Gen AI offers excellent opportunities for Entrepr...
Convergence of Robotics and Gen AI offers excellent opportunities for Entrepr...Convergence of Robotics and Gen AI offers excellent opportunities for Entrepr...
Convergence of Robotics and Gen AI offers excellent opportunities for Entrepr...
 
Digital Communication Essentials: DPCM, DM, and ADM .pptx
Digital Communication Essentials: DPCM, DM, and ADM .pptxDigital Communication Essentials: DPCM, DM, and ADM .pptx
Digital Communication Essentials: DPCM, DM, and ADM .pptx
 
Ground Improvement Technique: Earth Reinforcement
Ground Improvement Technique: Earth ReinforcementGround Improvement Technique: Earth Reinforcement
Ground Improvement Technique: Earth Reinforcement
 
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxS1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
 
Computer Graphics Introduction To Curves
Computer Graphics Introduction To CurvesComputer Graphics Introduction To Curves
Computer Graphics Introduction To Curves
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
 
👉 Yavatmal Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top Class Call Girl S...
👉 Yavatmal Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top Class Call Girl S...👉 Yavatmal Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top Class Call Girl S...
👉 Yavatmal Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top Class Call Girl S...
 
8th International Conference on Soft Computing, Mathematics and Control (SMC ...
8th International Conference on Soft Computing, Mathematics and Control (SMC ...8th International Conference on Soft Computing, Mathematics and Control (SMC ...
8th International Conference on Soft Computing, Mathematics and Control (SMC ...
 
fitting shop and tools used in fitting shop .ppt
fitting shop and tools used in fitting shop .pptfitting shop and tools used in fitting shop .ppt
fitting shop and tools used in fitting shop .ppt
 
Introduction to Robotics in Mechanical Engineering.pptx
Introduction to Robotics in Mechanical Engineering.pptxIntroduction to Robotics in Mechanical Engineering.pptx
Introduction to Robotics in Mechanical Engineering.pptx
 
Memory Interfacing of 8086 with DMA 8257
Memory Interfacing of 8086 with DMA 8257Memory Interfacing of 8086 with DMA 8257
Memory Interfacing of 8086 with DMA 8257
 
Introduction to Geographic Information Systems
Introduction to Geographic Information SystemsIntroduction to Geographic Information Systems
Introduction to Geographic Information Systems
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 
8086 Microprocessor Architecture: 16-bit microprocessor
8086 Microprocessor Architecture: 16-bit microprocessor8086 Microprocessor Architecture: 16-bit microprocessor
8086 Microprocessor Architecture: 16-bit microprocessor
 
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
 

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’
  • 45.
  • 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
  • 77.
  • 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