0% found this document useful (0 votes)
0 views

SQL

Uploaded by

justice.chitra.v
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

SQL

Uploaded by

justice.chitra.v
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 11

SQL

Different types of commands in SQL:

 DDL commands: - To create a database objects.


 DML commands: - To manipulate data of a database objects.
 DQL command: - To retrieve the data from a database.
 DCL/DTL commands: - To control the data of a database.
 TCL Commands – To manage changes and save a database

Data Definition Language (DDL): To specify the database schema.


DDL Commands:
 Create
 Alter
 Rename
 Drop

1. Creation of Table: Creates a table with specified attributes and its data type along with
constraints.
Syntax:
Create table r (A1 D1 , A2 D2,………An Dn,
(integrity-constraint1),
….,
(integrity-constraintk));
where r – relation name(Table name),
Ai – Attribute name,
Di – Data type.
Data Types in SQL:

1. char(n) : Fixed-length character string (can contain letters, numbers, and special
characters). The fixed size is specified in parenthesis. Can store up to 255 characters
2. varchar(n) : Variable-length string (can contain letters, numbers, and special
characters). The maximum size is specified in parenthesis. Can store up to 255
characters. Note: If you put a greater value than 255 it will be converted to a TEXT
type
3. int : Integer -2147483648 to 2147483647 normal. 0 to 4294967295. The maximum
number of digits may be specified in parenthesis
4. smallint : Small Integer -32768 to 32767 normal. 0 to 65535 UNSIGNED*. The
maximum number of digits may be specified in parenthesis
5. numeric(p,d) : The number consists of p digits(plus a sign), d of the p digits are to
the right of the decimal point.
6. float(n,d) : Floating-point number. The maximum number of digits may be
specified in the size parameter. The maximum number of digits to the right of the
decimal point is specified in the d parameter
7. double (size,d): A large number with a floating decimal point. The maximum
number of digits may be specified in the size parameter. The maximum number of
digits to the right of the decimal point is specified in the d parameter.
8. date : The date containing a date, month and year. Used to store date value as
DD-MON-YY, data size is 9 byte
Format: YYYY-MM-DD
Note: The supported range is from '1000-01-01' to '9999-12-31'
9. time : The time in hours, minutes and seconds.
Format: HH:MM:SS
10. timestamp : The combination of date and time.
Format: YYYY-MM-DD HH:MM:SS
Eg: Create a customer table which consists of 4 columns:
i) custID - Customer ID – Integer – Primary Key
ii) custname – Customer Name – varchar2 (15)
iii) custstreet – Customer Street – varchar2 (20)
iv) custcity – Customer City – varchar2 (10)
create table customer (
custID int,
custname varchar2(15),
custstreet varchar2(20),
custcity varchar2(10),Primary key (CustID));

2. To view the table structure:


Syntax:
desc r;
Ex:
Desc customer;

3. Retrieval of Information by Select Command

Syntax-
(i) Select A1,A2.. ,An from r1;
(ii) Select * from r1;
(iii) Select A1,A2.. ,An from r1,r2,..,rn;
(iii) Select A1,A2.. ,An from r1,r2,..,rn where condition;
Example-
(i) Select CustID,Custname from customer ;
(ii) Select CustID,Custname from customer where Custname=’Arun’);

DDL Commands:
 Create
 Alter
 Rename
 Drop

Altering the Table Schema: Add or delete or change the attribute and data type.
It also can add or drop the integrity constraints.
Syntax:
1. Alter table r add (Ai Di);
2. Alter table r drop(Ai);
3. Alter table r modify(Ai Di);
4. Alter table r add primary key(Ai);
5. Alter table r enable primary key;
6. Alter table r disable primary key;
Eg:
Alter table customer add ( phoneno int(12));
Alter table customer drop( custcity);
Alter table customer modify( custname varchar2(20));
Alter table depositor add primary key(acctno);
Alter table depositor disable primary key;
Alter table depositor enable primary key;

Rename: Change the table name


Syntax:
Rename <tablename> to <newtablename>;
Eg:
Rename emp to employee;
Dropping the Table: Deletes all information and structure about that table(relation)
Syntax:
Drop table r;
Eg:
Drop table customer;

Data Manipulation Language (DML) – to express database queries and updates.

List of DML Commands:


1. Insertion of information
2. Retrieval of information
3. Deleting information
4. Modifying information

Two types of DML –

1. Procedural DMLs – requires a user to specify what data are needed and how to get
those data.
2. Declarative DMLs ( nonprocedural language) - requires a user to specify what data are
needed without specifying how to get those data.

DML Component of SQL language is nonprocedural language.


Query is a statement requesting the retrieval of information.

1. Insertion of information can be done in two ways -


(i) Syntax-
Insert into r values(V1, V2,…,Vn); // where Vi – Attribute Values
r - relation name (Table name)

Example-
Insert into customer values(101,’Arun’, ‘Bharathi Street’,’Chennai’);

(ii) Syntax-
Insert into r values(‘&A1’,’&A2’,….,’&An’); // where Ai – Attribute
Example-
Insert into customer values (‘&CustID’, ’&Custname’, ’&Custstreet’,
’&Custcity’);
2. Retrieval of Information by Select Command
(i) Syntax-
Select A1,A2.. ,An from r1,r2,..,rn where condition;
Example-
Select CustID,Custname from customer where Custname=’Arun’);
3. Modifying information by Update

Syntax-
Update r set A1=values;

Example-
Update customer set Custname=’babu’ where CustID=101;
4. Deletion of information-
Syntax-
Delete from r where condition;
Example-
Delete from customer where Custname=’Arun’;
5. Truncating a Table: Deletes the records and not the structure of a table.
Syntax:
Truncate table r;
Ex:
Truncate table customer;
Adding Constraints to the table

Constraints in SQL:
 NULL
 NOT NULL
 UNIQUE
 PRIMARY KEY
 FOREIGN KEY
 CHECK
 DEFAULT

NOT NULL Constraints

 The NOT NULL constraint enforces a column to NOT accept NULL values.
 The NOT NULL constraint enforces a field to always contain a value. The following
SQL enforces the "P_Id" column and the "LastName" column to not accept NULL
values:
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(25)
)

UNIQUE Constraints

 The UNIQUE constraint uniquely identifies each record in a database table.


 The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness
for a column or set of columns.
 Note that you can have many UNIQUE constraints per table, but only one PRIMARY
KEY constraint per table.
Eg
CREATE TABLE Persons
(
P_Id int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)

To create a UNIQUE constraint on the "P_Id" column when the table is already created, use the
following SQL:

ALTER TABLE Persons


ADD UNIQUE (P_Id)

CHECK Constraints
 The CHECK constraint is used to limit the value range that can be placed in a column.
 If you define a CHECK constraint on a single column it allows only certain values for this
column.

 The following SQL creates a CHECK constraint on the "P_Id" column when the "Persons"
table is created. The CHECK constraint specifies that the column "P_Id" must only include
integers greater than 0.

CREATE TABLE Persons


(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CHECK (P_Id>0)
)

To add a CHECK constraint, use the following SQL:

ALTER TABLE Persons


ADD CHECK (P_Id>0)

DEFAULT Constraints

 The DEFAULT constraint is used to insert a default value into a column.


 The following SQL creates a DEFAULT constraint on the "City" column when the
"Persons" table is created:

CREATE TABLE Persons


(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255) DEFAULT 'chennai'
)

To create a DEFAULT constraint on the "City" column when the table is already created
without city column, use the following SQL:

ALTER TABLE Persons


add (City varchar(25) DEFAULT 'Chennai')

To drop a DEFAULT constraint, use the following SQL:


ALTER TABLE Persons
ALTER City DROP DEFAULT

PRIMARY KEY Constraints

 The PRIMARY KEY constraint uniquely identifies each record in a database table.
 Each table should have a primary key, and each table can have only one primary key.
 The following SQL creates a PRIMARY KEY on the "P_Id" column when the "Persons" table is
created:
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (P_Id)
);

To add a PRIMARY KEY constraint, use the following SQL:

ALTER TABLE Persons


ADD PRIMARY KEY (P_Id)

Note: If you use the ALTER TABLE statement to add a primary key, the primary key column(s)
must already have been declared to not contain NULL values (when the table was first created).

To drop a PRIMARY KEY constraint, use the following SQL:

ALTER TABLE Persons


DROP PRIMARY KEY

FOREIGN KEY Constraints

 The "P_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.
 The FOREIGN KEY constraint is used to prevent actions that would destroy link
between tables.

 The FOREIGN KEY constraint also prevents that invalid data is inserted into the foreign
key column, because it has to be one of the values contained in the table it points to

 A FOREIGN KEY in one table points to a PRIMARY KEY in another table.

 Let's illustrate the foreign key with an example. Look at the following two tables:

The "Persons" table:


P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

The "Orders" table:

O_Id OrderNo P_Id


1 77895 3
2 44678 3
3 22456 2
4 24562 1

Note that the "P_Id" column in the "Orders" table points to the "P_Id" column in the "Persons"
table. The "P_Id" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.

To create a FOREIGN KEY constraint on the "P_Id" column when the "Orders" table is already
created, use the following SQL:

ALTER TABLE Orders


ADD FOREIGN KEY
REFERENCES Persons(P_Id)

Adding & Deleting the Constraints to the Table using constraint Names:

This example demonstrates how to specify constraints with constraint name during table
creation
create table salary_table (
fiscal_year varchar2(4) constraint nn_sal_year not null,
salary number constraint chk_sal_sal check (salary > 0 ),
fullname varchar2(64) constraint unq_sal_fullname unique,
emp_id varchar2(12) constraint fk_sal_emp_id references emp1(eno));

To disable a constraint, use the alter table command. To enable a disabled constraint, again
use the alter table command. The following examples disables and then re-enables the salary
check condition

alter table salary_table disable constraint chk_salary_salary;


alter table salary_table enable constraint chk_salary_salary;

The following example demonstrates how to drop the constraints using constraint name,
alter table salary_table drop constraint unq_sal_fullname;
alter table salary_table drop constraint chk_sal_sal;
alter table salary_table drop constraint nn_sal_year;
alter table salary_table drop constraint fk_sal_emp_id;

Transaction Control Language(TCL) commands


Transaction Control Language(TCL) commands are used to manage transactions in the
database. These are used to manage the changes made to the data in a table by DML
statements. It also allows statements to be grouped together into logical transactions.

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 commited 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
realise 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;

In short, using this command we can name the different states of our data in any table and
then rollback to that state using the ROLLBACK command whenever required.

EXAMPLE :
SQL> select * from person;
PID LASTNAME FIRSTNAME ADDRESS AGE
------- ---------- ---------- ------------ --------
1 Prettina Anne BAngalore 14
2 Benitto Anish Trichy 24
3 Raj Anita Chennai 27
4 Kumar Ashok Coimbatore 30
5 Hinn Benny Britain 55
6 Prakash Bhaskar Assam 40
7 Kumar Chander Coimbatore 45
7 rows selected.
SQL> commit;
Commit complete.

DELETE COMMAND
SQL> delete from person where lastname='Kumar';
2 rows deleted.
SQL> select * from person;
PID LASTNAME FIRSTNAME ADDRESS AGE
------ ---------- ---------- ------------ --------
1 Prettina Anne BAngalore 14
2 Benitto Anish Trichy 24
3 Raj Anita Chennai 27
4 Hinn Benny Britain 55
5 Prakash Bhaskar Assam 40

SQL> rollback;
Rollback complete.

SQL> select * from person;


PID LASTNAME FIRSTNAME ADDRESS AGE
------- ---------- ---------- ------------ -------
1 Prettina Anne BAngalore 14
2 Benitto Anish Trichy 24
3 Raj Anita Chennai 27
4 Kumar Ashok Coimbatore 30
5 Hinn Benny Britain 55
6 Prakash Bhaskar Assam 40
7 Kumar Chander Coimbatore 45
7 rows selected.
SQL> savepoint s1;
Savepoint created.
SQL> delete from person;
7 rows deleted.
SQL> select * from person;
no rows selected
SQL> rollback to savepoint s1;
Rollback complete.
SQL> select * from person;
PID LASTNAME FIRSTNAME ADDRESS AGE
------ ---------- ---------- ------------- -------
1 Prettina Anne BAngalore 14
2 Benitto Anish Trichy 24
3 Raj Anita Chennai 27
4 Kumar Ashok Coimbatore 30
5 Hinn Benny Britain 55
6 Prakash Bhaskar Assam 40
7 Kumar Chander Coimbatore 45
7 rows selected.

You might also like