Database Systems Scse

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 75

Database systems

SCSE
INTRODUCTION
Structure Query Language(SQL) is a database query
language used for storing and managing data in
Relational DBMS.
SQL was the first commercial language introduced for
E.F Codd's Relational model of database.
 Today almost all RDBMS(MySql, Oracle, Infomix,
Sybase, MS Access) use SQL as the standard database
query language.
 SQL is used to perform all types of data operations in
RDBMS.
Datatypes
Oracle supplies the following built-in datatypes:
•character datatypes
CHAR
NCHAR
VARCHAR2 and VARCHAR
NVARCHAR2(
CLOB(character large object)
NCLOB
LONG

NUMBER datatype
DATE datatype

 

•binary datatypes
BLOB
BFILE(to represent the location of binary data)
RAW
LONG RAW
DDL: Data Definition Language

DDL is used for creating and modifying the database


objects like table s, indices, views and users.
All DDL commands are auto-committed. That means
it saves all the changes permanently in the database.
Create Table Statement
• Create statement is used to create database schema
and to define the type and structure of the data to be
stored in the database.
• The create table defines each column of table uniquely
• Each table column definition is separated from other
by comma
• SQL statement is terminated by semicolon

 Rules for creating a name of table:


• Can have up to maximum of 30 characters
• A-Z, a-z alphabets and 0-9 numbers are allowed
• Should begin with an alphabet
• Reserve words are not allowed
Syntax of Create Table
Statement
• CREATE TABLE table_name ( column1
datatype, column2 datatype, column3
datatype, .... );

• Example:
CREATE TABLE Person ( PersonID int,
LastName varchar(255), FirstName
varchar(255), Address varchar(255), City
varchar(255) );
Create table using another
table
• A copy of an existing table can be created
using a combination of the CREATE TABLE
statement and the SELECT statement.

Syntax:
CREATE TABLE new_table_name AS SELECT
column1, column2,...
FROM existing_table_name;
Example of creating table from another table:

• Create table Person2 as select PersonID,


FirstName From Persons;
Alter Table Statement
• A DBA can make changes to the table
structure or column definitions after the
table has been created in the database.
• The DDL command ALTER TABLE is used
to perform such actions.
• The ALTER TABLE statement is used to
add, drop, rename, and modify a column in
a table.
• To Add a column in an existing table:

Syntax:
ALTER TABLE table_name ADD
column_name datatype;

Example:
ALTER TABLE Person ADD weight_in_Kgs int;
• To delete a column in an existing table:

Syntax:

ALTER TABLE table_name DROP COLUMN


column_name;

Example:
ALTER TABLE Person DROP COLUMN
weight_in_Kgs;
• To rename a column in an existing table:

Syntax:

ALTER TABLE table_name RENAME COLUMN


existing_column_name
To new_column_name;

Example:
ALTER TABLE Person RENAME COLUMN
weight_in_Kgs To Wght_in_kgs;
• To modify a table by changing the data type
of a column in a table

Syntax:

ALTER TABLE table_name MODIFY


column_name datatype;

Example:
ALTER TABLE Person MODIFY Wght_in_kgs
varchar(90);
TRUNCATING TABLES
It empties a table completely.

Syntax:
TRUNCATE TABLE table_name;
Example:
Truncate table person;
DESTROYING TABLES
Drop table statement with table name can destroy
a specific table

Syntax:
DROP TABLE table_name;

Example:
DROP TABLE person;
RENAME TABLE COMMAND
Syntax-
ALTER TABLE table_name
RENAME to new_table_name;
DML: Data Manipulation
Language

DML commands are used for manipulating the data


stored in the table and not the table itself.
DML commands are not auto-committed. It means
changes are not permanent to database, they can be
rolled back.
INSERTING DATA INTO TABLE:
The insert operation on inserting a single row:
•Creates an empty row in database table
•Loads the value passed by insert command into the
specified columns
Syntax:
INSERT INTO table_name (Column_name1,
Column_name2…) values (expression1,
expression2);
Example:
INSERT INTO person (personID, firstname,
lastname, address) VALUES (23, ‘ravi’, ‘dubey’,
‘patiala’ );
•Inserting data into a table from another table
INSERT INTO <table_name> select
<columnname1>,<columnname2> from
<table_name>;
VIEWING DATA IN TABLES
The select command is used to retrieve rows
selected from one or more tables
To select all rows and all columns:
SELECT Column1,… , Column2 from table_name;
OR
SELECT * from table_name;

Example:
SELECT * FROM person;
Selected columns and all rows

• Select<columnname1>,<columnname2>, from
<tablename>;

 Example: Select Name, Roll_no from Student;


Selected Rows and All Columns

• Select * from <tablename> where <condition>;

 Example :select * from student where name=‘xyz’;


Selected columns and selected
rows
 Select <columnname1>,<columnname2> from
<tablename> where <condition>;
 Example: Select name, roll no from student where
roll no=1;
SQL ORDER BY Keyword
The ORDER BY keyword is used to sort the
result-set in ascending or descending
order.

The ORDER BY keyword sorts the records


in ascending order by default.

To sort the records in descending order,


use the DESC keyword.
ORDER BY Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;

CREATE TABLE Person_detail ( PersonID int, LastName


varchar(255), FirstName varchar(255), Address varchar(255),
City varchar(255) );

select * from Person_detail order by FirstName;


OR
select * from Person_detail order by DESC;
ORDER BY Several Columns
SELECT * FROM Person_detail ORDER BY FirstName,
LastName;
OR

SELECT * FROM Person_detail ORDER BY FirstName


ASC, LastName DESC;
Eliminating duplicate rows while
using select statement
 Select distinct <columnname1>,<columnname2>
from <tablename>;
 Select distinct * from student;
DELETE OPERATIONS
Delete command deletes rows from table that
satisfies given condition represented by where
clause
and returns number of records deleted.

•Removal of all rows


Syntax:
DELETE FROM tablename;

Example:
DELETE FROM person;
Removal of Specific Rows

Delete from <table_name> where<condition>;

Delete from student where name=‘xyz’;


Updating the Contents of a Table
• Update in Sql is used to either update:
1. All the rows from a table Or
2. A select set of rows from a table
• Updating All Rows
 Update <tablename> set
<columnName1>=<Expression1>,<ColumnName2=
<Expression2>;
 Update Student set roll_no=1;
Updating Records Conditionally
 Update <tablename>
set<columnName1>=<Expression1>,<ColumnName
2= <Expression2> where<condition>;
Renaming Tables
Syntax:
Rename <tablename> To <NewTablename>

Example:
Rename Person_detail To Detail_P;
Key Constraints
SQL PRIMARY KEY Constraint
Syntax:
CREATE TABLE table_name ( column1 datatype(size)
Primary Key, column2 datatype, column3
datatype, .... );
Example:
CREATE TABLE Persons ( ID int  PRIMARY KEY,
LastName varchar(255),FirstName varchar(255),Age
int);
OR
CREATE TABLE Persons (ID int ,LastName varchar(255) ,
    FirstName varchar(255), Age int,PRIMARY KEY (ID));
SQL PRIMARY KEY on ALTER TABLE
Syntax:
ALTER TABLE tablename
ADD PRIMARY KEY (columnname);
Example:
ALTER TABLE Persons ADD PRIMARY KEY (ID);
DROP a PRIMARY KEY Constraint

ALTER TABLE <tablename> DROP PRIMARY KEY;
SQL NOT NULL Constraint

Syntax:
CREATE TABLE table_name ( column1 datatype(size) Not null,
column2 datatype, column3 datatype, .... );

Example:
CREATE TABLE Persons (ID int NOT NULL, LastName
varchar(25) NOT NULL, FirstName varchar(25) NOT NULL,
    Age int);
SQL NOT NULL on ALTER TABLE
ALTER TABLE Table_name modify
column_name NOT NULL;
SQL UNIQUE Constraint
CREATE TABLE Persons (ID int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,FirstName varchar(255),
    Age int);
SQL UNIQUE Constraint on ALTER TABLE
ALTER TABLE Persons ADD UNIQUE (ID);
SQL NULL Values
How to Test for NULL Values?
It is not possible to test for NULL values with comparison
operators, such as =, <, or <>.
IS NULL Syntax
SELECT column_names FROM table_name
WHERE column_name IS NULL;
IS NOT NULL Syntax
SELECT column_names FROM table_name
WHERE column_name IS NOT NULL;
SQL UNIQUE Constraint
CREATE TABLE Table_name ( column1  UNIQUE, column2..);
Example:create table abc(id int, name varchar2(20) Unique,
subject varchar2(20));

SQL UNIQUE Constraint on ALTER TABLE


ALTER TABLE Table_name ADD UNIQUE (column_name);
Example:
ALTER TABLE Persons ADD UNIQUE (ID);
SQL CHECK Constraint

The CHECK constraint is used to limit the value


range that can be placed in a column.

Example:
CREATE TABLE Persons (ID int NOT NULL,LastName
varchar(255) NOT NULL, FirstName varchar(255), Age int,
    CHECK (Age>=18);
SQL CHECK on ALTER TABLE
ALTER TABLE Persons ADD CHECK (Age>=18);

SQL DEFAULT Constraint


CREATE TABLE Persons ( ID int NOT NULL,
LastName varchar(255) NOT NULL,FirstName varchar(255),
    Age int, City varchar(255) DEFAULT ‘chandigarh’);
SQL FOREIGN KEY Constraint

CREATE TABLE Orders (OrderID int PRIMARY KEY,


OrderNumber int  NOT NULL, PersonID
int FOREIGN KEY REFERENCES xyz(Id));
create table Persons(person_id int,LastName
varchar2(10),FirstName varchar2(20),age number);
insert into Persons values(1,'Hansen','Ola','30');
insert into Persons values(2,'Svendson','Tove',23);
insert into Persons values(3,'Pettersen','Kari',20);
select * from persons;
create table Orders(order_id int, order_number
int,person_id int);
insert into Orders values(1,77895,3);
insert into Orders values(2,44678,3);
insert into Orders values(3,22456,2);
insert into Orders values(4,24562,1);
select * from Orders;
ALTER TABLE Persons ADD PRIMARY KEY (person_id);
ALTER TABLE Orders ADD FOREIGN KEY (person_id)
REFERENCES Persons(person_id);
SQL LIKE Operator
The LIKE operator is used in a WHERE clause to
search for a specified pattern in a column.
There are two wildcards often used in conjunction
with the LIKE operator:
• The percent sign (%) represents zero, one, or
multiple characters
• The underscore sign (_) represents one, single
character
Note:The percent sign and the underscore can also be
used in combinations!
LIKE Operator Description
WHERE CustomerName LIKE 'a%' Finds any values that start with "a"
WHERE CustomerName LIKE '%a' Finds any values that end with "a"
WHERE CustomerName LIKE '%or%' Finds any values that have "or" in any
position
WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the
second position
WHERE CustomerName LIKE 'a_%' Finds any values that start with "a" and
are at least 2 characters in length
WHERE CustomerName LIKE 'a__%' Finds any values that start with "a" and
are at least 3 characters in length
WHERE ContactName LIKE 'a%o' Finds any values that start with "a" and
ends with "o"
Syntax:
SELECT column1, column2, ...FROM table_name
WHERE columnN LIKE pattern;

Example:
SELECT * FROM Customers WHERE CustomerName LIKE 'a%';
SELECT * FROM CustomersWHERE  CustomerName LIKE '%or
%';
SELECT * FROM CustomersWHERE CustomerName LIKE '_r%';
4.
SELECT * FROM CustomersWHERE ContactName LIK
E 'a%o';
5. SELECT * FROM Customers
WHERE CustomerName NOT LIKE 'a%';
SQL IN Operator

1. The IN operator allows you to specify multiple


values in a WHERE clause.
2. The IN operator is a shorthand for
multiple OR conditions.

Syntax:
SELECT column_name(s) FROM table_name
WHERE column_name IN (value1, value2, ...);
OR
SELECT column_name(s) FROM table_name
WHERE column_name IN (SELECT STATEMENT);
Example:
SELECT * FROM Customers
WHERE Country IN ('Germany', 'France', 'UK');

SELECT * FROM Customers
WHERE Country NOT IN ('Germany', 'France', 'UK');
SQL statement selects all customers that are from the same
countries as the suppliers:

SELECT * FROM Customers
WHERE Country IN (SELECT Country FROM Suppliers);
The SQL BETWEEN Operator

The BETWEEN operator selects values within a given


range. The values can be numbers, text, or dates.
The BETWEEN operator is inclusive: begin and end
values are included. 
Syntax:
SELECT column_name(s) FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Example:
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;

SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;
BETWEEN with IN Example

SELECT * FROM ProductsWHERE Price BETWEEN 10 AND 2
0 AND CategoryID NOT IN (1,2,3);

SELECT MIN(column_name) FROM table_name;

SELECT Max(column_name) FROM table_name;


SQL Aggregate Functions
SQL aggregation function is used to perform the
calculations on multiple rows of a single column of a
table. It returns a single value.
It is also used to summarize the data.

COUNT FUNCTION
COUNT function is used to Count the number of rows in
a database table. It can work on both numeric and non-
numeric data types
COUNT function uses the COUNT(*) that returns the
count of all the rows in a specified table. COUNT(*)
considers duplicate and Null.
SELECT COUNT(Column_name) from table_name;
Example:
SELECT COUNT(customer_name) from customer;
OR
SELECT COUNT(*) from customer;
AVG()
SELECT AVG(column_name)FROM table_name;

Example:
select avg(customer_id) from customer;

SUM()
SELECT SUM(column_name)FROM table_name;

Example:
select sum(customer_id) from customer;
GROUP BY
SQL GROUP BY statement is used to arrange identical
data into groups. The GROUP BY statement is used
with the SQL SELECT statement.
The GROUP BY statement follows the WHERE clause
in a SELECT statement and precedes the ORDER BY
clause.
The GROUP BY statement is used with aggregation
function.
Syntax: SELECT column  FROM table_name  
WHERE conditions   
GROUP BY column  
ORDER BY column  
Example:
SELECT COMPANY, COUNT(*)  FROM PRODUCT_MAST
   GROUP BY COMPANY;  
 HAVING
HAVING clause is used to specify a search condition
for a group or an aggregate.
Having is used in a GROUP BY clause. If you are not
using GROUP BY clause then you can use HAVING
function like a WHERE clause.
Syntax
SELECT column1, column2   FROM table_name  
WHERE conditions   GROUP BY column1, column2   
HAVING conditions  ORDER BY column1, column2;  
SELECT COMPANY, COUNT(*)  FROM PRODUCT_MAS
T GROUP BY COMPANY  HAVING COUNT(*)>2;  
TCL: Transaction Control Language

These commands are to keep a check on other


commands and their affect on the database.
 These commands can annul changes made by other
commands by rolling the data back to its original
state. It can also make any temporary change
permanent.
COMMIT command

COMMIT command is used to permanently save any


transaction into the database.
When we use any DML command
like INSERT, UPDATE or DELETE, the changes made by
these commands are not permanent, until the current
session is closed, the changes made by these commands
can be rolled back.
To avoid that, we use the COMMIT command to mark the
changes as permanent.
Following is commit command's syntax,
 COMMIT;
ROLLBACK command

This command restores the database to last committed


state. It is also used with SAVEPOINT command to
jump to a savepoint in an ongoing transaction.
If we have used the UPDATE command to make some
changes into the database, and realize that those
changes were not required, then we can use
the ROLLBACK command to rollback those changes, if
they were not commited using the COMMIT command.
Following is rollback command's syntax,
ROLLBACK TO savepoint_name;
SAVEPOINT command

SAVEPOINT command is used to temporarily save a


transaction so that you can rollback to that point
whenever required.
Following is savepoint command's syntax,
SAVEPOINT savepoint_name;
DCL: Data Control Language
Data Control Language(DCL) is used to control privileges
in Database.
To perform any operation in the database, such as for
creating tables, sequences or views, a user needs privileges.
Privileges are of two types,
 System: This includes permissions for creating session, table,
etc and all types of other system privileges.
 Object: This includes permissions for any command or query
to perform any operation on the database tables.
In DCL we have two commands,
 GRANT: Used to provide any user access privileges or other
privileges for the database.
 REVOKE: Used to take back permissions from any user.
Create a user
create user <username> identified by "<password>";
Allow a User to create session
When we create a user in SQL, it is not even allowed to
login and create a session until and unless proper
permissions/privileges are granted to the user.
Following command can be used to grant the session
creating privileges-
GRANT CREATE SESSION TO username;
Allow a User to create table
To allow a user to create tables in the database, we can
use the below command,
GRANT CREATE TABLE TO username;
Grant permission to drop any table
As the title suggests, if you want to allow user to drop
any table from the database, then grant this privilege to
the user,
GRANT DROP ANY TABLE TO username
To take back Permissions
And, if you want to take back the privileges from any
user, use the REVOKE command.
REVOKE CREATE TABLE FROM username

You might also like