You are on page 1of 15

DATA BASE MANAGEMANT SYSTEM

What is SQL?
 SQL (pronounced "ess-que-el") stands for Structured Query
Language.
 It is a Standard Language
 It is used to communicate with a database.
 According to ANSI (American National Standards Institute), it is
the standard language for relational database management systems.

USES OF SQL
 Creating and maintaining database objects.
 Manipulating data stored in the tables.
 Querying data stored in the tables.
 Controlling access to the database objects for security.
 Ensuring database consistency by enforcing business rules.
 Used by administrators, developers and end users alike for their
varying requirements.

CREATE TABLE STATEMENT


The command for creating empty table is:
CREATE TABLE < Table name >
(<column 1> <data type>,
<column 2> <data type>);

Example-
CREATE TABLE employee (
EMPNO NUMBER (2),
NAME CHAR (10));
To Display the structure of the table

desc employee

DATA TYPES IN SQL


 Character data types
 Number data types
 Binary data types
 Date Data type

 CHARACTER OR CHAR (length)


 CHAR data types specify the fixed length string. Default length
is 1 byte.
Max. Size 2000 byte
CREATE TABLE EMPLOYEE
(Empno Char (5));
 Values of this data type, must be enclosed in single quotes when
used in a WHERE clause of a query.

1
MITHIL MAKWANA
DATA BASE MANAGEMANT SYSTEM

 VARCHAR2 (length)
 The Varchar2 data type is used to store the variable-length
character strings having maximum length specified.
The maximum size is 4000 bytes.
CREATE TABLE EMPLOYEE
(Ename varchar2 (25),
Address varchar2 (50),
City varchar2 (20)
);
 If we insert data shorter than the length of the column then it
takes its actual size and it is not padded with trailing blanks.

 NUMBER(precision, scale)
 Used to specify a column which is a number with decimal places.
 The precision specifies the number of significant digits that the
number is to have.
 The scale indicates the number of digits to the right of the
decimal point. The maximum (4, 2) number would be 99.99.

EXAMPLE OF NUMBER:-
 CREATE TABLE EMPLOYEE
(Empno Char (5),
Salary Number (8, 2),
Deptno Number (4)
);
 Indicates that Salary will have a maximum of eight digits with
two decimal places.
 Defines deptno as an integer with 4 digits.
 Values of this data type should not be enclosed in quotes when
used in a WHERE clause of a query.
Select * from employee where Marks > 70;

 INTEGER OR INT
 Used to define a column which can take numeric values without
decimal points.
 Equivalent of Numeric or Decimal with scale being zero, except
that the number of digits cannot be specified and is
implementation dependant.
Example
CREATE TABLE EMPLOYEE
(Empno Char (5),
Salary Number (8, 2),
Deptno Integer);

2
MITHIL MAKWANA
DATA BASE MANAGEMANT SYSTEM

 DATE data type


 The Date data type stores date and time in a table for each date
value oracle stores the following information. Year, Month, Day,
Hours, Min & Secs.

The default format for a date is DD-MON-YY.


Example: 25-OCT-06 or 07-JAN-87

DROP TABLE
Removes object from a database. There is no method of recovery of an
object once it has been dropped.
DROP <object> <object-name>;

Example: Drop table employee;

ALTER TABLE
 Alter the structure of the object after the database is designed
and created.
 To alter the definition of a table in one of the following ways:
1. To add a column
2. To redefine a column(data type ,size, default value)
3. To add an integrity constraint
4. To enable, disable, or drop an integrity constraint.

ALTER TABLE<Add/Modify option>

 Allows the addition of a new column in a table using the add option.
o ALTER TABLE RECORD ADD(ADDRESS CHAR(18));

 The data type or width of a column can be changed within certain


limitations using MODIFY option.
o ALTER TABLE RECORD MODIFY(SR_NO NUMBER(6));

 The column can be dropped using alter command


o ALTER table record DROP column address.

SELECT STATEMENT
 The SELECT statement can be used to retrieve the data from a
database table. The SELECT statement is the most important SQL
statement.
 To view the list of all the tables in the database, including the
system tables, use the following command.
SELECT * FROM tab;
We use a system table called tab, which contains a list of
all the tables in the database.

3
MITHIL MAKWANA
DATA BASE MANAGEMANT SYSTEM

WHERE CLAUSE
 Used to apply search conditions for selecting rows which appear
in the result table.
 This clause is optional; if present, it follows the From clause.
Example:
SELECT empno, ename, job FROM emp WHERE empno = 7900;

DISTINCT
 To get rid of duplicate records we can use the distinct clause.
 For example to view distinct jobs from the employee we would use
the following statement
SELECT distinct job from emp;

Note - Distinct is always applied collectively and not for individual


columns

ORDER BY CLAUSE
 Specifies the order in which the retrieved rows will appear in
the result table.
 The sort is in ascending or descending order.
 Default ascending
 The keyword DESC specifies the descending order.
 Ordering on multiple columns
Example:
 SELECT Empno, deptno, hiredate
 FROM emp
 ORDER BY deptno [asc], hiredate desc

SQL OPERATORS
 Used to manipulate individual data items and return a result.
 Used with the expressions specified with the where clause of the
select statement.
 Can be categorized as:
 Arithmetic Operators
 Comparison operators
 Logical operators
 Set operators

4
MITHIL MAKWANA
DATA BASE MANAGEMANT SYSTEM

 Arithmetic Operators
 To perform calculations based on number values, we include
arithmetic expressions is SQL command.
 The Arithmetic Operators are

Operator Description
* Multiplication
/ Division
- Subtraction
+ Addition
Example:
Select 100*2/100+ (2+3) from dual;
 Comparison operators
Operator Description
= equal to

> greater than

< less than

>= greater than or equal to

<= less than or equal to

<> Or! = not equal to

BETWEEN...AND. between lower and upper values

IN match any of a list of values


EXAMPLES

1. SELECT Empno, enameFROM EMP WHERE sal >=1000;

2. SELECT ename, mgr, sal FROM EMP WHERE job IN


('CLERK','MANAGER','PRESIDENT');

3. SELECT deptno, sal FROM EMP WHERE Empno between 1001 AND 2000;

PATTERN SEARCH [WILD CARD CHARACTERS]


 In such cases we can use the LIKE operator to specify a search
pattern, based on which, the records are retrieved.
 To specify the search pattern, we can make use of two wildcard
characters.
o Percent (%) represents zero or more characters.
o Underline (_) character is used to represent exactly one
character.

5
MITHIL MAKWANA
DATA BASE MANAGEMANT SYSTEM

 LIKE Operator
 Used for pattern searching. Pattern consists of characters to
be matched and “wildcard” characters.
Syntax: WHERE <column> LIKE | NOT LIKE <pattern>
Examples:
SELECT names from records where names like ‘S%’;
SELECT names from records where names like ‘_E%’;

 LOGICAL OPERATORS
Can be used in order of decreasing precedence as follows:-
NOT
AND
OR
Examples:
Select * from EMP where sal > 1000 AND job='MANAGER'
Select * from EMP where sal > 1000 OR job='MANAGER'
Select * from EMP where sal NOT BETWEEN 1000 and 4000

NULL values
 SQL provides the NULL clause for checking against NULL values.
Syntax: WHERE <column> IS / IS NOT NULL
Example using NULL clause
SELECT ename, sal, comm FROM EMP WHERE comm is NULL;

Manipulating NULL’s
 Use NVL expression (NULL value substitution).
 NULL can be replaced with any number or character or 0.
Example:
SELECT ename, sal, comm, (sal + NVL (comm, 0)) NET FROM EMP;
SELECT NVL (to_char (comm),'No commission') from EMP;

 INSERT VALUES

INSERT INTO <table-name> (<col 1>, <col 2>,….)VALUES


(<value1>,<value2>,….);
Example
INSERT INTO employee (empno, ename) VALUES (100, 'LAXMAN');
INSERT INTO employee VALUES (&EMPNO,'&NAME', &SAL,
&COMM,'&HIREDATE','&JOB', &DEPNO)

1. If the columns are not specified in the INSERT statement, then the
values for all columns should be given in the respective order i.e.,
the order used during the creation of table.
2. If particular columns are not specified then the DML-Insert
operation will create a new row by assigning NULL values to those
columns.

6
MITHIL MAKWANA
DATA BASE MANAGEMANT SYSTEM

 UPDATE Statement
 Used to change the existing rows. The changes can be made in
single rows, groups of rows, or all the rows in a table.
 The SET clause specifies the column(s) and the changed value(s).
Syntax:
UPDATE <table name>SET <column name>=expression (WHERE <conditions>);

Examples:
 UPDATE emp SET sal = 5000 WHERE Job=‘MANAGER’;
 UPDATE emp SET sal =1000, comm=100 WHERE job='SALESMAN'

 The DELETE Statement


 Allows removing rows from the table.
 Works for single-row operations as well as multiple-row
operations.
 The WHERE clause specifies which rows to remove.
Syntax: DELETE <table-name> WHERE <condition>;
Examples: DELETE EMP where sal > 2000;
OR
DELETE from EMP where sal > 2300;

 REPLACE command
Syntax:
REPLACE char, search _string [, replacement _string])
Returns char with every occurrence of search _string replaced
with replacement string
Example
SELECT REPLACE (‘Rohan’,'Roh', 'Paw') FROM DUAL;

 COMMIT command
 Used to make changes permanent.
 Until the transaction is committed, the changes made are not
visible to the other users.
 The syntax for COMMIT is: COMMIT [WORK] or COMMIT;

 ROLLBACK command
 Restores data the complete transaction can be undone using
Rollback command.
 In case of any system failures, an implicit Rollback is
triggered.
 The syntax of Rollback command is: ROLLBACK;

7
MITHIL MAKWANA
DATA BASE MANAGEMANT SYSTEM

 SPOOL command
 Create one file that is stores the data of the working SQL
Queries.
 The syntax of SPOOL command is:
SPOOL Path for file location and file format.
Example:
SPOOL Z:\DBMS\sql.txt;
Close time: SPOOL OFF;

 The FOLD FUNCTIONS


 A pair of functions for converting all the lower case characters
in a given string to upper case or all the upper case ones to
lower case.
UPPER
LOWER
INITCAP
Example:
SELECT upper (ename) UCase, lower (ename) LCase, Initcap (ename)
ICase FROM EMP;

 LTRIM and RTRIM


 Removes characters from the left of char, with initial character
removed up to the first character not in set.
 Returns char ,with final characters removed after the last
character not in set Example
Example:
Select ename, ltrim (ename,'A') LT, rtrim (ename,'T') RT from EMP;

 LPAD and RPAD


 Lpad ([char1, n, char2])
 Returns char1, left padded to length n with the sequence of
characters in char2.
 Rpad ([char1, n, char2])
 Returns char1, right padded to length n with the sequence
of characters in char2.
Examples:
SELECT LPAD (ename, 10,'*') "LEFT NAMES", RPAD (ename, 10,'*') "RIGHT
NAMES", LPAD (ename, 10) "LEFT NAMES" FROM EMP;

 SUBSTRING function
Syntax: Substr (Column |Value, position, n)
 Returns a string of n characters from a column or a constant
value starting at the position number position.
Example:
SELECT ename, Substr (ename, 1, 2) FROM EMP;

8
MITHIL MAKWANA
DATA BASE MANAGEMANT SYSTEM

 NUMBER Functions
 Abs (n): Returns the absolute value of n where N is a constant.
Select Abs (-255) “Absolute” from Dual;

 Ceil (n): Returns integer value greater than or equal to n.


Select ceil (1.1) “ceiling” from Dual; 2

 Floor (n): Returns integer value smaller than or equal to n.


Intuitive opposite of CEIL.
Select Floor (1.9) “Floor” from Dual; 1

ROUND
Syntax ROUND (n, [m])
 Returns n rounded to m places right of the decimal point; if m is
omitted, to 0 places.
 m can be negative to round off digits left off the decimal point.
 m must be an integer .
Examples:
SELECT ROUND (15.193, 1) “Round” FROM DUAL;

SIGN
Syntax: SIGN (n)
 If n<0,the function returns -1;
 If n=0,the function returns 0;
 If n>0,the function returns 1;
SELECT SIGN (-15) “Sign” FROM DUAL;

EXP
Syntax: EXP (n)
Returns e raised to the nth power. E = 2.71828183.
SELECT EXP (4)”e to the 4th power” FROM DUAL;

MOD
Syntax: MOD (m,n)
Returns remainder of m divided by n.Returns m if n is 0.
SELECT MOD (9, 5) “Modulus” FROM DUAL; 2

POWER
Syntax: POWER (m, n)
Returns m raised to the nth power.
The base m and the exponent n can be any numbers, but if m is
negative, n must be an integer.
SELECT POWER (6, 2) “Raised” FROM DUAL; 36

SQRT
Syntax: SQRT (n)
Returns square root of n.
The value n cannot be negative.
SELECT SQRT (25) “Square” FROM DUAL; 5

9
MITHIL MAKWANA
DATA BASE MANAGEMANT SYSTEM

 Date and Time Functions


A date, plus or minus a number, yields a new Date.
SELECT SYSDATE - 1 YESTERDAY, SYSDATE TODAY, SYSDATE +1 TOMORROW FROM
DUAL
A date, minus a second date, yields an int number of days

SELECT ROUND (SYSDATE - to_date ('01-OCT-06')) FROM DUAL


SELECT MONTHS_BETWEEN (sysdate,'18-JAN-2006') from dual
SELECT ADD_MONTHS (sysdate, 1) from dual
SELECT LAST_DAY (SYSDATE) FROM dual
SELECT NEXT_DAY (SYSDATE, 1) FROM dual

 GROUP Functions / Aggregate Functions


Group functions operate on set of rows to give one result per group
Group functions may include either of the keywords DISTINCT or ALL.
ALL is default.

Example:
AVG (ALL 2, 2, 3, 3, 4) returns 2.8
AVG (DISTINCT 2, 2, 3, 3, 4) returns 3

Types of GROUP Functions:


Syntax: SELECT group_function (column) FROM table

SUM
Syntax: SUM (n)
Returns sum of values of n.
SELECT SUM (sal) “Total” FROM EMP;

AVERAGE
Syntax: AVG (n)
Returns average of value of n.
SELECT AVG (sal) “Average” FROM EMP;

COUNT
Syntax: COUNT ({*[DISTINCT |ALL] expr})
 Returns the number of rows in the query.
 If expr is specified, this function returns rows where expr is
not null.
 If the asterix (*) is specified, this function returns all rows
including duplicates and nulls.
Examples:
SELECT COUNT (*) FROM EMP; returns 14
SELECT COUNT (job) FROM EMP; returns 14
SELECT COUNT (distinct job) FROM EMP; returns 5

10
MITHIL MAKWANA
DATA BASE MANAGEMANT SYSTEM

MIN
Syntax: MAX ([DISTINCT | ALL] expr)
 Returns maximum value of expr.
SELECT MAX (sal) “Maximum” FROM EMP;

MAX
Syntax: MIN ([DISTINCT | ALL] expr)
 Returns minimum value of expr.
SELECT MIN (sal) “Minimum” FROM EMP;

 GROUP BY Clause
 Is the only way SQL is able to summarize data.
 The GROUP BY clause is used to logically group rows together
based on the common value of one or more columns.
 Will break the working table into groups which have identical
values for the grouping columns.
 If the GROUP BY clause is used, you have to use at least one
aggregate function in the SELECT clause of the query.
 GROUP BY clause breaks the table into a set of rows and the
aggregate functions returns one value for that group.

Syntax:
SELECT column, group_function (column)FROM table GROUP BY column;
All columns in the SELECT list that are not in group functions
must be in the GROUP BY clause.
The GROUP BY column does not have to be in the SELECT list.

Example:
Display department wise total salary.
SELECT deptno, SUM (sal) "Total Salary" FROM EMP GROUP BY deptno;

Group functions and NULL values


 Group functions ignore NULL values.
SELECT AVG (comm) FROM EMP; return 550.
The NVL function forces GROUP functions to include NULL values.
SELECT AVG (NVL (comm, 0)) FROM EMP; return 157.14286

Grouping More than ONE column


 Sum of salaries in the EMP table for each job grouped by
department.

SELECT deptno, job, sum (sal) FROM EMP GROUP BY deptno, job;

 Display the total number of employees with the same job.

11
MITHIL MAKWANA
DATA BASE MANAGEMANT SYSTEM

Excluding Group Results: HAVING clause


Use the HAVING clause to restrict groups.
 Rows are grouped.
 Group function is applied
 Groups matching having clause is displayed.
SELECT deptno, sum (sal) FROM EMP GROUP BY deptno
HAVING sum (sal) > 9000 ORDER BY sum (sal) desc;

JOINS
 The process of forming rows from two or more tables by comparing
the contents of related columns in called joining tables.

SELECT ename, dname FROM EMP, dept WHERE EMP.deptno=dept.deptno;

The above query works as follows:


1. The Cartesian product of two tables is formed.
2. The rows not satisfying the WHERE condition are dropped.
3. The columns specified in the select list are picked up.

Types of JOINS
 Cartesian product.
 Equi-join.
 Non-equijoin.
 Outer-join.
 Self-join.
Equi-join:
A join that is formed as a result of equality condition between the
two columns is called an Equi-join or a simple join. The comparison
Operator used in the join condition is ‘=’ (equal).
Example:
SELECT empno, ename, job, dname, loc FROM EMP, dept WHERE
EMP.deptno=dept.deptno

Non Equi-join:
The joins which use comparison operators other than = while
defining the joining criteria are called non-equi joins.
Example:
SELECT empno, ename, grade FROM EMP, salgrade WHERE sal between
losal and hisal;

12
MITHIL MAKWANA
DATA BASE MANAGEMANT SYSTEM

Constraints:
 Restrictions or rules imposed on a table.
 Provides important data integrity protection unlike file systems
where validations are done through application programs.
TYPES OF CONSTRAINTS
 Not Null
 Default
 Check
 Primary Key
 Unique
 Foreign key

Not Null:
 Will not allow NULL values but will allow duplicate values.
 Cannot be specified compositely as NOT NULL is always a column
level constraint.
 Can have any number of NOT NULL constraints per table.
Syntax: Create table Customer
(Code Number (4),
Name Char (3),
Address Char (20) NOT NULL);

Alter table <modify option>


Alter table Customer modify (Name NOT NULL);

DEFAULT Constraint:
 Defines a value that the system automatically supplies when the
user does not enter data explicitly.
Syntax:
Create table Marks
(Roll_no Number (2),
City Char (12) default ‘MUMBAI’,
Marks Number (3));
Note:
Defaults columns should always be in the last.

CHECK constraint
 Used for enforcing rules and performing validations on the data.
 Check constraints that involve more than one column are defined
on the table level.
Create table EMP
(Empno number (4),
Sal number (4) constraint MYCK CHECK (sal between 1000 and 6000),
Estate char (1) CHECK (estate IN (‘T’,’P’,’R’)),
Comm number (4), constraint mycomp CHECK (sal + comm <= 15000));

13
MITHIL MAKWANA
DATA BASE MANAGEMANT SYSTEM

Primary Key Constraint


 Primary key is a field or a set of fields which uniquely identify
each row (tuple) in a table (Entity or Relation).”
 Will not allow null values and so it is NOT NULL.
 Will not allow duplicate values and so it is UNIQUE.
CREATE TABLE EMP
(Empno number (4) constraint pk_empno primary key,
ename varchar2(10),
Job varchar2 (10));
Specification of a Composite Key
Create table Orders
(ord_no number(3),
prod_no number(3),
Qty number (4),
Constraint PK_OP primary key (ord_no, prod_no));
ALTER Option to Add & Drop constraints
 Can be used to add constraints to an existing table.
 Alter table Products
Add constraint PK_PRODNO primary key (Prod_no);
 Alter table Products
Drop constraint PK_PRODNO;
OR
 Alter table Products
Drop constraint Primary Key;

UNIQUE Constraint
 Will not allow duplicate values of specified column or columns.
 Allows NULL values since every NULL values is unique.
 Combination of UNIQUE and NOT NULL is like indirect primary key.
Create table EMP
(Empno Number (3),
Job char (12) NOT NULL,
Pass_no Number (4) UNIQUE,
Pr_code Number (3) constraint MY_UNI UNIQUE
Constraint MY_NUL NOT NULL,
Div_cd Number (2),
Deptno Number (2),
Constraint COMP_CON UNIQUE (Div_cd,Deptno));

FOREIGN KEY constraint


CREATE TABLE EMP
(Empno NUMBER (4) Primary Key,
Ename VARCHAR2 (10),
Mgr NUMBER (4) CONSTRAINT fk_mgr REFERENCES EMP (empno),
Sal NUMBER (7, 2),
Comm NUMBER (7, 2),
Deptno NUMBER (2) CONSTRAINT fk_deptno REFERENCES dept (deptno) ON
DELETE CASCADE);

14
MITHIL MAKWANA
DATA BASE MANAGEMANT SYSTEM

VIEWS
 Logical representation of another table or combination of tables.
 Derives its data from the tables on which it is based i.e. base
tables. Views are called virtual tables.
Syntax:
Create VIEW <view-name> {column1, column2…}
As {SELECT statement}
[WITH CHECK OPTION];
Example:
Create view v_emp as
Select empno, ename, sal, deptno from EMP where deptno = 10 With check
option;
Need of Views:
 Security: Hiding Sensitive and irrelevant data.
 Query Simplicity: A view can draw data from several different
tables and present it as a single table.
 Facilitates Logical Independence

Sequence
 A Sequence is an object, which is used for automatically
generating unique integer values,normally for primary key values.

CREATE SEQUENCE seq_name


[INCREMENT BY 1]
[START WITH 1]
[MAXVALUE 100]
[MINVALUE 1]
[CYCLE|NOCYCLE];

 The increment by clause is optional. Default is one. Zero is not


allowed. A negative value means that the sequence will be
descending.
 NOCYCLE is Default.
 We make use of two pseudo columns for this purpose.
NEXTVAL and CURRVAL
Insert into test values (sq_no.nextval,’ABC’);
Select sq_no.currval from dual;

15
MITHIL MAKWANA

You might also like