Professional Documents
Culture Documents
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.
Example-
CREATE TABLE employee (
EMPNO NUMBER (2),
NAME CHAR (10));
To Display the structure of the table
desc employee
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
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>;
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.
Allows the addition of a new column in a table using the add option.
o ALTER TABLE RECORD ADD(ADDRESS CHAR(18));
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;
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
3. SELECT deptno, sal FROM EMP WHERE Empno between 1001 AND 2000;
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
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'
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;
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;
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
Example:
AVG (ALL 2, 2, 3, 3, 4) returns 2.8
AVG (DISTINCT 2, 2, 3, 3, 4) returns 3
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;
SELECT deptno, job, sum (sal) FROM EMP GROUP BY deptno, job;
11
MITHIL MAKWANA
DATA BASE MANAGEMANT SYSTEM
JOINS
The process of forming rows from two or more tables by comparing
the contents of related columns in called joining tables.
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);
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
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));
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.
15
MITHIL MAKWANA