Professional Documents
Culture Documents
1
SQL-Structured Query Language
•SQL (Structured Query Language):-
It is a computer language aimed to store, manipulate
data stored in relational databases.
Some of the basic functions of SQL are inputting,
modifying, and dropping data from databases.
2
Data types in SQL
Data type Description
CHARACTER(n) Character string, fixed length n.
CHARACTER VARYING(n)
Variable length character string, maximum length
or
n.
VARCHAR(n)
BINARY(n) Fixed length binary string, maximum length n.
BINARY VARYING(n) or
Variable length binary string, maximum length n.
VARBINARY(n)
INTEGER(p) Integer numerical, precision p.
SMALLINT Integer numerical precision 5.
NTEGER Integer numerical, precision 10.
BIGINT Integer numerical, precision 19.
DECIMAL(p, s) Exact numerical, precision p, scale s.
3
FLOAT(p) Approximate numerical,mantissa precision p.
TIMESTAMP Stores year, month, day, hour, minute, and second values
4
Data Type Abbreviations
Abbreviation Character
CHAR(n) CHARACTER(n)
CHAR CHARACTER
CHAR VARYING(n) CHARACTER VARYING(n)
VARCHAR(n) CHARACTER VARYING(n)
VARBINARY(n) BINARY VARYING(n)
INT(p) INTEGER(p)
INT INTEGER
DEC(p, s) DECIMAL(p, s)
DEC DECIMAL
NUM(p, s) NUMERIC(p, s)
NUM NUMERIC
5
Operators in SQL
SQL support 3 types of operators
Arithmetic Operator:
Used for basic calculations like +,-,* & /. It can be used
in the expression.
6
SQL Operators
7
Comparison Operators
8
Operators in SQL
Logical Operator:
Used to evaluate the expression depending on combination of
conditions.
Logical operators are,
9
The ALL operator is used to compare a value to all values in
ALL
another value set.
10
The NOT operator reverses the meaning of the logical
NOT operator with which it is used. Eg: NOT EXISTS, NOT
BETWEEN, NOT IN, etc. This is a negate operator.
11
SQL Comparison Keywords
13
• The previous select statement searches for all the rows where
the first letter of the column first_name is ‘A' and rest of the
letters in the name can be any character.
14
SQL BETWEEN ... AND Operator
15
SQL set operators
• SQL set operators combine results from two or more
SELECT statements.
• SQL set operators combine rows from different
queries with strong preconditions - all involved
SELECTS must.
• They retrieve the same number of columns and the
data types of corresponding columns.
16
• According to SQL Standard there are following Set
operator types:
UNION [DISTINCT];
UNION ALL;
EXCEPT [DISTINCT];
EXCEPT ALL;
INTERSECT [DISTINCT];
INTERSECT ALL.
17
Union and UNION ALL
18
person amount person amount
A 1000 A 2000
B 2000 B 2000
C 5000 D 35000
Sales2006
Sales2005
person amount
A 1000
B 2000
C 5000
A 2000
D 35000
19
• SELECT * FROM sales2005 UNION ALL SELECT * FROM
sales2006;
person amount
A 1000
A 2000
B 2000
B 2000
C 5000
D 35000
20
INTERSECT operator
21
Minus operator
22
EXCEPT operator
• The SQL EXCEPT operator takes the distinct rows of
one query and returns the rows that do not appear in a
second result set.
• The EXCEPT ALL operator does not remove
duplicates.
• For purposes of row elimination and duplicate
removal, the EXCEPT operator does not distinguish
between NULLs.
23
The query returns all rows where the Quantity is between 1 and
100, apart from rows where the quantity is between 50 and 75.
24
Statement
• DML
DML is abbreviation of Data Manipulation Language. It is used to
retrieve, store, modify, delete, insert and update data in database.
Examples: SELECT, UPDATE, INSERT statements
• DDL
DDL is abbreviation of Data Definition Language. It is used to create and
modify the structure of database objects in database.
Examples: CREATE, ALTER, DROP statements
• DCL
DCL is abbreviation of Data Control Language. It is used to create roles,
permissions. It is also used to control access to database by securing it.
Examples: GRANT, REVOKE statements
• TCL
TCL is abbreviation of Transactional Control Language. It is used to
manage different transactions occurring within a database.
Examples: COMMIT, ROLLBACK statements 25
What are the difference between DDL, DML and DCL commands
26
DML:-Data Manipulation Language (DML)
statements are used for managing data within
schema objects. Some examples:
• SELECT - retrieve data from the database
• INSERT - insert data into a table
• UPDATE - updates existing data within a table
• DELETE - deletes all records from a table, the
space for the records remain
• MERGE - UPSERT operation (insert or update)
27
DCL:-Data Control Language (DCL) statements.
GRANT - gives user's access privileges to database
REVOKE - withdraw access privileges given with the
GRANT command.
29
SELECT
• The most commonly used SQL command is SELECT
statement. The SQL SELECT statement is used to retrieve data
from a table in the database. A query may retrieve information
from specified columns or from all of the columns in the table.
To create a simple SQL SELECT Statement, you must specify
the column(s) name and the table name. The whole query is
called SQL SELECT Statement.
• Select queries require two essential parts. The first part is the
"WHAT", which determines what we want SQL to go and
fetch. The second part of any SELECT command is the
"FROM WHERE". It identifies where to fetch the data from,
which may be from a SQL table.
30
Where Clause
• SQL offers a feature called WHERE clause, which we
can use to restrict the data that is retrieved.
• While inserting a row, if you are adding value for all the columns
of the table you need not specify the column(s) name in the sql
query. But you need to make sure the order of the values is in the
same order as the columns in the table 35
• The sql insert query will be as follows :
• INSERT INTO TABLE_NAME
VALUES (value1, value2, value3,...valueN);
• For Example: If you want to insert a row to the employee table,
the query would be like,
• INSERT INTO employee (id, name, dept, age, salary) VALUES
(105, ‘ABC', ‘computer', 27, 33000,);
• When adding a row, only the characters or date values should be
enclosed with single quotes.
• If you are inserting data to all the columns, the column names
can be omitted. The above insert statement can also be written
as,
• INSERT INTO employee
VALUES (105, ‘ABC', ‘computer', 27, 33000);
36
Inserting data to a table through a select statement.
38
SQL UPDATE-DML Statement
40
SQL Delete-DML Statement
41
SQL TRUNCATE Statement
42
Difference between DELETE and TRUNCATE Statements
45
SQL ALTER TABLE-DDL Statement
46
Continue….
• Syntax :
REVOKE privilege_name
ON object_name
FROM {user_name |PUBLIC |role_name}
52
Example
54
CREATE system privileges
55
Object privileges
Object Privileges Description
allows users to insert rows into a
INSERT
table.
allows users to select data from a
SELECT
database object.
UPDATE allows user to update data in a table.
allows user to execute a stored
EXECUTE
procedure or a function.
56
• Roles:
1) Roles are a collection of privileges or access
rights. When there are many users in a database it
becomes difficult to grant or revoke privileges to
users.
2) Therefore, if you define roles, you can grant or
revoke privileges to users, thereby automatically
granting or revoking privileges. You can either create
Roles or use the system roles pre-defined by oracle.
57
Some of the privileges granted
58
Creating Roles
• Syntax :
CREATE ROLE role_name
[IDENTIFIED BY password];
59
• It's easier to GRANT or REVOKE privileges to the users
through a role rather than assigning a privilege directly to
every user.
• If a role is identified by a password, then, when you
GRANT or REVOKE privileges to the role, you definitely
have to identify it with the password.
• We can GRANT or REVOKE privilege to a role as below:
• For example: To grant CREATE TABLE privilege to a
user by creating a testing role:
• First, create a testing Role
CREATE ROLE testing
• Second, grant a CREATE TABLE privilege to the ROLE
testing. You can add more privileges to the ROLE.
GRANT CREATE TABLE TO testing; 60
Continue….
61
Commit-TCL Statement
Commit:
Used to end the transaction & also make its effect
permanent to the database.
62
Rollback-TCL Statement
Rollback:
Used to undo work done in current transaction.
63
Save Point-TCL Statement
Savepoint:
Like marker which marks the lengthy transactions
It is used with rollback to cancel effect till particular
savepoint
Syntax: savepoint savepointname;
64
Database Objects
Object Description
Table Basic unit of storage; composed of rows and columns
View Logically represents subsets of data from one or more
tables
Sequence Generates primary key value
Index Improves the performance of some queries
Synonym Alternative name for an object
65
SQL Views
• A VIEW is a virtual table, through which a selective portion of
the data from one or more tables can be seen.
• Views do not contain data of their own. They are used to
restrict access to the database or to hide data complexity.
• A view is stored as a SELECT statement in the database. DML
operations on a view like INSERT, UPDATE, DELETE affects
the data in the original table upon which the view is based.
66
Continue….
69
Syntax for MySQL
• The following SQL statement defines the "ID" column to be
an auto-increment primary key field in the “Employee" table:
70
• MySQL uses the AUTO_INCREMENT keyword to perform an
auto-increment feature.
72
• Syntax to create SQL unique Index:
CREATE UNIQUE INDEX index_name
ON table_name(column_name1);
index_name is the name of the INDEX.
• table_name is the name of the table to which
the indexed column belongs.
• column_name1 name of the column on which
index is created.
• In Oracle there are two types of SQL index
namely, implicit and explicit.
73
Example
74
• Implicit Indexes:
Implicit indexes are indexes that are automatically
created by the database server when an object is
created.
75
• Single-Column Indexes:
• A single-column index is one that is created based on only one table
column.
CREATE INDEX index_name ON table_name (column_name);
• Unique Indexes:
• Unique indexes are used not only for performance, but also for data
integrity. A unique index does not allow any duplicate values to be
inserted into the table.
CREATE UNIQUE INDEX index_name ON table_name
(column_name);
• Composite Indexes:
• A composite index is an index on two or more columns of a table.
CREATE INDEX index_name ON table_name (column1, column2);
76
• Explicit Indexes:
They are created using the "create index.. " syntax.
1) Even though sql indexes are created to access the rows
in the table quickly, they slow down DML operations like
INSERT, UPDATE, DELETE on the table, because the
indexes and tables both are updated along when a DML
operation is performed. So use indexes only on columns
which are used to search the table frequently.
79
DROP INDEX
• An index can be dropped using SQL DROP
command.
• Care should be taken when dropping an index
because performance may be slowed or
improved.
• The basic syntax is as follows:
DROP INDEX index_name;
80
Synonyms
• We can simplify access to objects by creating a synonym(another
name for an object).
• Syntax:
CREATE [PUBLIC] SYNONYM synonym
FOR object;
Where,
PUBLIC: creates synonym accessible to all users
SYNONYM: It is the synonym to be created
object: identifies the object for which the synonym is created.
82
Removing Synonym
• To drop a synonym use the DROP
SYNONYM statement. Only the database
administrator can drop a public synonym.
83
• Suppose the schemas hr and sh both contain
tables named customers.
84
Group Functions
• SQL COUNT (): This function returns the number of rows in the table that satisfies
the condition specified in the WHERE condition. If the WHERE condition is not
specified, then the query returns the total number of rows in the table.
• For Example: If you want the number of employees in a particular department, the
query would be:
SELECT COUNT (*) FROM employee
WHERE dept = 'Electronics';
• For Example: If you want to select all distinct department names from
employee table, the query would be:
SELECT DISTINCT dept FROM employee;
• To get the count of employees with unique name, the query would be:
SELECT COUNT (DISTINCT name) FROM employee;
• SQL MAX(): This function is used to get the maximum value from a
column.
• To get the maximum salary drawn by an employee, the query would be:
SELECT MAX (salary) FROM employee;
86
Continue…
• SQL MIN(): This function is used to get the minimum value from a
column.
• To get the minimum salary drawn by an employee, the query would be:
• SQL AVG(): This function is used to get the average value of a numeric
column.
• To get the average salary, the query would be
• SQL SUM(): This function is used to get the sum of a numeric column
• To get the total salary given out to the employees,
90
Query
• If you want to know the total amount
of salary spent on each department,
the query would be:
91
Example
• SELECT Department_id, SUM (salary)
FROM employee
GROUP BY Department_id;
Deparment_id SUM(salary)
90 40000
60 50000
70 30000
10 80000
92
• The group by clause should contain all the
columns in the select list except those used
along with the group functions.
93
Having Clause
94
Having clause
96
Query
• If you want to select the department
that has total salary paid for its
employees more than 35000.
97
Example1
• SELECT Department_id, SUM (salary)
FROM employee
GROUP BY Department_id
HAVING SUM (salary) > 35000
Deparment_id SUM(salary)
90 40000
60 50000
10 80000
98
Query
• Display the department id and
average salaries for those
departments whose maximum salary
is greater than 35000
99
Example 2
100
Output
60 50000 60 50000
10 80000 10 40000
101
Nesting Group functions
60 50000
102
SQL ORDER BY
• Syntax
• SELECT column-list
FROM table_name [WHERE condition]
[ORDER BY column1 [, column2, .. columnN]
[ASC|DESC]];
103
Example
• If you want to sort the employee table by salary of the
employee, the sql query would be.
• SELECT Employee_id, salary FROM employee
ORDER BY salary;
Employee_id Salary
100 20000
105 20000
103 30000
104 40000
106 40000
102 50000
104
END
105
106
107
Sequence
• A sequence-
-Automatically generates unique numbers
-Is typically used to create a primary key value
-Speeds up the efficiency of accessing sequence values
when cached in memory.
108
• They are mainly used to create a primary key value
which must be unique for each row.
109
Creating Sequence
• A sequence is a database item that generates a sequence of
integers.
• Syntax of CREATE SEQUENCE statement:
CREATE SEQUENCE sequence_name
[START WITH start_n
[INCREMENT BY n]
[ { MAXVALUE maximum_n | NOMAXVALUE } ]
[ { MINVALUE minimum_n | NOMINVALUE } ]
[ { CYCLE | NOCYCLE } ]
[ { CACHE cache_n | NOCACHE } ]
[ { ORDER | NOORDER } ];
110
The minimum information required for getting
numbers using a sequence is:
• The starting number
• The maximum number that can be generated by a
sequence
• The increment value for generating the next number.
• This information is provided to oracle at the time of
sequence creation.
111
where
• The default start_n is 1.
• The default increment number is 1.
• The absolute value of n must be less than the difference
between maximum_n and minimum_n
• minimum_n must be less than or equal to start_n, and
minimum_n must be less than maximum_n.
• NOMINVALUE specifies the maximum is 1 for an ascending
sequence or -10^26 for a descending sequence.
NOMINVALUE is the default.
• maximum_n must be greater than or equal to start_n, and
maximum_n must be greater than minimum_n.
• NOMAXVALUE specifies the maximum is 10^27 for an
ascending sequence or -1 for a descending sequence.
NOMAXVALUE is the default.
112
• CYCLE specifies the sequence generates integers
even after reaching its maximum or minimum value.
• When an ascending sequence reaches its maximum
value, the next value generated is the minimum.
• When a descending sequence reaches its minimum
value, the next value generated is the maximum.
113
• CACHE cache_n specifies the number of integers to
keep in memory.
115
Creating a sequence and then get the next value
• SQL> CREATE SEQUENCE test_seq;
Sequence created.
SQL> SELECT test_seq.nextval FROM DUAL;
NEXTVAL
----------
1
SQL> SELECT test_seq.nextval FROM DUAL;
NEXTVAL
----------
2
SQL> SELECT test_seq.nextval FROM DUAL;
NEXTVAL
----------
3
• SQL> DROP SEQUENCE test_seq;
Sequence dropped.
116
Test sequence step
•
SQL> CREATE SEQUENCE test_seq
START WITH 10 INCREMENT BY 5
MINVALUE 10 MAXVALUE 20
CYCLE CACHE 2 ORDER;
Sequence created.
•SQL> SELECT test_seq.nextval FROM dual;
NEXTVAL
----------
10
SQL> SELECT test_seq.nextval FROM dual;
NEXTVAL
----------
15
SQL> SELECT test_seq.nextval FROM dual;
NEXTVAL
----------
20
SQL> SELECT test_seq.nextval FROM dual;
NEXTVAL
----------
10
117
Referencing a sequence
119
Example
120
Dropping a sequence
121
Query
• Display the job_id and total monthly salary for
each job with a total payroll exceeding 25000.
122
Example 3
• SELECT Job_id, SUM (salary) PAYROLL
FROM employee
WHERE Job_id NOT LIKE ‘%tant%’
GROUP BY Job_id
HAVING SUM(salary) > 25000 ;
Job_id Payroll
ST_Clerk 40000
Manager 50000
123