DBMS Unit 3
DBMS Unit 3
SQL:
• SQL stands for Structured Query Language
• SQL is used to communicate with a database.
• According to ANSI (American National Standards Institute), it is the standard language
for relational database management systems.
• SQL statements are used to perform tasks such as update data on a database or retrieve
data from a database.
• Some common relational database management systems that use SQL are: Oracle,
MYSQL, Mongo DB, Sybase, Microsoft SQL Server, Access, Ingres, etc.
What Can SQL do:
1) SQL can execute queries against a database
2) SQL can retrieve data from a database
3) SQL can insert records in a database
4) SQL can update records in a database
5) SQL can delete records from a database
6) SQL can create new databases
7) SQL can create new tables in a database
8) SQL can create stored procedures in a database
9) SQL can create views in a database
10) SQL can set permissions on tables, procedures, and views
HISTORY OF SQL:
• In 1970 Dr. E. F. Codd developed the relational database model.
• In 1978 IBM developed the language called Structured English Query Language
(SEQUEL). This language was used on a database system called System/R, but neither the
system nor the query language was ever released.
• In 1979 Relational Software Inc. (later renamed Oracle) released the first relational
DBMS, Oracle.
• In 1982 IBM released their first relational database system, SQL/DS (SQL/Data
System).
• In 1985 IBM released DB2 (Database 2).
• In 1987 Microsoft released SQL Server.
• In 1989 The American National Standards Institute (ANSI) published the first set of
standards for a database query language, called ANSIISO SQL-89, or SQL 1.
• In 1992 ANSI published revised standards (ANSIIISO SQL-92, or SQL2) incorporated
many new features.
51
• In 1999 ANSI published SQL3 (ANSIISO SQL-99). These standards incorporated
new features, including support for objects.
• In 2003 ANSI published SQL:2003. These standards introduced XML-related
features, standardized sequences, and identity columns.
• In 2006 ANSI published SQL:2006, which defined how SQL can be used with XML.
• In 2008 ANSI published SQL:2008. These standards introduced INSTEAD OF
triggers and the TRUNCATE statement.
Characteristics of SQL:
• SQL is easy to learn.
• SQL is used to access data from relational database management systems.
• SQL can execute queries against the database.
• SQL is used to describe the data.
• SQL is used to define the data in the database and manipulate it when needed.
• SQL is used to create and drop the database and table.
• SQL is used to create a view, stored procedure, function in a database.
• SQL allows users to set permissions on tables, procedures, and views.
Advantages of SQL:
The following are various advantages of SQL
• Portable: SQL can run in mainframes, PCs, laptops, servers and even mobile phones. It
runs in local systems, intranet and internet. Databases using SQL can be moved from one
device to another without any problems.
• Used with any DBMS system with any vendor: SQL is used by all the vendors who
develop DBMS.
• Used for relational databases: SQL is widely used for relational databases.
• Easy to learn and understand: SQL mainly consists of English statements and it is
very easy to learn and understand a SQL query.
• Interactive language: SQL can be used to communicate with the databases and get
answers to complex questions in seconds.
• Both as programming language and interactive language: SQL can do both the jobs
of being a programming as well as an interactive language at the same time.
• Complete language for a database: SQL is used to create databases, manage security
of a database. It can also be used for updating, retrieving and sharing data with users.
• Multiple data views: By using SQL, different views of structure and content of a
database can be provided for different users.
• Client/Server language: SQL is used for linking front end computers and back end
databases. Thus, providing client server architecture.
52
• Dynamic database language: By the use of SQL database structure can be changed in
a dynamic fashion even when the contents of the database are accessed by users at the
same time.
• Supports object-based programming: SQL supports the latest object-based
programming and is highly flexible.
• Supports enterprise applications: SQL is the database language which is used by
businesses and enterprises throughout the globe. For an enterprise application it is a
perfect language for a database.
• Integrates with Java: SQL integrates with Java by using an API known as JDBC (Java
Database Connectivity).
• Used in internet: SQL is used in three-tiered Internet architecture. The architecture
includes a client, application server and a database.
• Used by IBM and Microsoft: SQL is used by major players like IBM and Microsoft.
IBM used SQL in DB2; and Microsoft in ODBC (Open Database Connectivity), SQL
server and ADO (ActiveX Data Objects).
54
2. VARBINARY(n): Variable-length binary data with a maximum length of n.
o Example: 0x123456 (with n=3)
o Usage: image VARBINARY (255)
3. BLOB: Binary Large Object for large binary data.
o Example: Binary data of an image or file.
o Usage: document BLOB
55
Q) Explain SQL Commands in detail? or
Explain DDL, DML, TCL and DCL and DQL Commands in SQL?
• SQL commands are instructions used to communicate with the database to perform
specific task that work with data.
• SQL commands used to create tables, add data to tables, or modify data, drop the table,
set permissions for users etc.
• SQL commands are grouped into five major categories depending on their
functionality.
• DDL (Data Definition Language).
• DML (Data Manipulation Language).
• DCL (Data Control Language).
• TCL (Transaction Control Language)
• DDL commands are used to create, modify, and drop the structure of database objects like
table, view, procedure, indexes etc.
• All the command of DDL are auto-committed that means it permanently save all the
changes in the database.
• In this category we have CREATE, ALTER, DROP, TRUNCATE and RENAME
commands.
CREATE: This command is used to create the database or its objects (like table, index,
function, views, store procedure, and triggers).
ALTER: This is used to alter the structure of the database.
DROP: This command is used to delete objects from the database.
56
TRUNCATE: This is used to remove all records from a table, including all spaces
allocated for the records are removed.
RENAME: This is used to rename an object existing in the database
• DML commands are used to store, modify, and delete data from database tables.
• The commands of DML is not auto-committed that means it can't permanently save all
the changes in the database. They can be rollback.
SELECT: It is used to access the data from a database table.
INSERT: It is used to insert data into a table.
UPDATE: It is used to update existing data within a table.
DELETE: It is used to delete records from a database table.
57
Q) Explain DDL commands in detail?
• DDL is a Data Definition Language, which deals with database schemas and
descriptions.
• DDL statements are used to alter/modify a database or table structure and schema.
• All the commands of DDL is auto-committed that means it permanently save all the
changes in the database.
DDL Commands:
• CREATE
• ALTER
• DROP
• TRUNCATE
• RENAME
Q) Explain about tables in SQL?
OR
How to create Tables in SQL?
CREATE TABLE Command:
In Oracle, CREATE TABLE statement is used to create a new table in the database. Each
column has minimum of three attributes.
• Name
• Data type
• Size (column width)
Syntax: CREATE TABLE Tablename(column1 datatype, column2 datatype, column3
datatype, ...... columnN datatype, PRIMARY KEY (one or more columns));
Parameters:
Tablename: It specifies the name of the table which you want to create.
column1, column2, ... column n: It specifies the columns which you want to add in the
table. Every column must have a datatype. Every column should either be defined as
"NULL" or "NOT NULL". In the case, the value is left blank; it is treated as "NULL" as
default.
58
Primary key: A primary key is a column or set of columns in a table that uniquely
identifies rows in a table. It cannot accept null, duplicate values.
Example: If you want to create the Student table, the statement would be like,
SQL>CREATE TABLE Student (Sid number(5),
sname varchar(20),
class varchar(10),
age number(2),
fee number(10),
address varchar(10));
Table Created
Table created.
59
Create Table copying selected columns of another table:
Syntax: CREATE TABLE new table AS (SELECT column1, column2...columnN FROM
old table);
Ex: SQL> CREATE TABLE student2 AS (SELECT Sid, sname FROM Student);
• The SQL ALTER TABLE command is used to add, delete or modify columns in an
existing table.
• The ALTER TABLE statement is also used to add and drop various constraints on an
existing table.
ALTER command is used to perform the following functions:
• To add a column to existing table
• To rename any existing column
• To change datatype of any column or to modify its size.
• To drop a column from the table.
ALTER Command: Add a new Column
Using ALTER command, we can even add multiple new columns to any existing table.
Syntax: ALTER TABLE table name ADD(column-name1 datatype1, column-name2
datatype2);
60
Ex: ALTER TABLE student ADD(fathername VARCHAR(60), mothername
VARCHAR(60), dob DATE);
The above command will add three new columns to the student table
DROP Command:
• The DROP TABLE statement is used to drop an existing table in a database.
• Once a table is dropped we cannot get it back, so be careful while using DROP
command.
Syntax: DROP TABLE tablename;
Ex: Drop Table Students;
61
TRUNCATE Command:
The TRUNCATE command is used to delete the data inside a table, but not the table
Structure.
Syntax: TRUNCATE TABLE tablename;
Ex: TRUNCATE TABLE student;
The above query will delete all the records from the table student.
RENAME Command:
RENAME command is used to set a new name for any existing table. Following is the
syntax,
Syntax: RENAME TABLE old_tablename to new_tablename;
Ex: RENAME TABLE student to studentinfo;
62
The DML Commands are
• Select
• Insert
• Update
• Delete
SELECT Command:
• The ‘Select’ command is used to retrieve the data from a Table or a View.
• A select query may retrieve information from specified columns or from all of the
columns in the table.
Student Table:
63
Syntax2: Inserting Multiple rows
SQL>insert into <table name> values (&value1, &value2, &value3…);
SQL>insert into student values(&rollno,’&studname’, &marks’);
After giving this command the following output will come,
Enter value for rollno:101
Enter value for name: xyz
Enter value for marks: 80
1 row created.
The statement ‘1 row created’ assures that the record has been inserted into the table.
To run the same command just press ‘/ ‘on SQL prompt as follows.
SQL> /
Syntax3: Insert value into only specific columns
• We can use the INSERT command to insert values for only some specific columns of a
row.
• We can specify the column names along with the values to be inserted like this,
Syntax: SQL> Insert into table(column1, column2) values(value1,value2);
EX: SQL>INSERT INTO student(id, name) values(102, 'mahesh');
The above SQL query will only insert id and name values in the newly inserted record.
Update Command:
• UPDATE command is used to update any record of data in a table.
• UPDATE can update one or more records in a table.
• In the Update statement, WHERE clause identifies the rows that get affected. If you do
not include the WHERE clause, column values for all the rows get affected
DCL Commands:
• DCL stands for Data Control Language.
• DCL commands are used to control user access in a database.
• Using DCL command, it allows or restricts the user from accessing data in database
schema.
Grant Command:
Syntax: GRANT <privilege list> ON<table name or view name> TO <user >;
EX: For example, if you wanted to grant SELECT, INSERT, UPDATE, and DELETE
privileges on a table called employees to a user name smith, you would run the following
GRANT statement:
65
REVOKE COMMAND:
• REVOKE command is used to cancel previously granted or denied permissions.
• This command withdraws access privileges given with the GRANT command.
• It takes back permissions from user.
Syntax: REVOKE <privilege list>ON <table name or view name>FROM <user name>;
Ex: if we want to revoke DELETE privileges on a table called employees from a user
name mahesh, we would run the following REVOKE statement:
Ex: REVOKE DELETE ON employees FROM mahesh;
If you want to revoke ALL permissions from mahesh
Ex: REVOKE ALL ON employees FROM mahesh;
Q) 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.
Syntax: SQL>COMMIT;
ROLLBACK command
• This command restores the database to last committed state.
• This command can only be used to undo transactions since the last COMMIT or
ROLLBACK command was issued
Syntax: SQL: ROLLBACK;
Syntax1:SQL>Rollback to savepoint-name;
66
SAVEPOINT Command:
• A SAVEPOINT is a point in a transaction in which you can roll the transaction back to
a certain point without rolling back the entire transaction.
• SAVEPOINT command is used to temporarily save a transaction so that you can roll
back to that point whenever required.
• Syntax: SAVEPOINT savepointname;
• ROLLBACK TO SAVEPOINT_NAME;
EX: SAVEPOINT SP1;
//Savepoint created.
DELETE FROM Student WHERE AGE = 20;
//deleted SAVEPOINT SP2;
//Savepoint created. ROLLBACK TO SP1;
//Rollback completed.
Distinct Command:
• Distinct removes all the duplicate records while retrieving records from any table in the
database.
Syntax: SELECT DISTINCT column-name FROM table-name;
EX: SQL> SELECT DISTINCT SAL FROM STUDENT;
Let's assume two variables "a" and "b". Here "a" is valued 50 and "b" valued 100.
67
Example:
Comparison operators are used to compare the column data with specific values in a
condition. Let us take two variables "a" and "b" that are valued 50 and 100.
= Examine both operands value that are equal or not, (a=b) is not true
if yes condition become true.
> Examine the left operand value is greater than (a>b) is not true
right Operand, if yes condition becomes true
< Examines the left operand value is less than right (a<b)is true
Operand, if yes condition becomes true
68
>= Examines that the value of left operand is greater (a>=b) is not true
than or equal to the value of right operand or not,
if yes condition become true
<= Examines that the value of left operand is less (a<=b) is true
than or equal to the value of right operand or not,
if yes condition becomes true
!< Examines that the left operand value is not less (a!<b> is not true
than the right operand value
!> Examines that the value of left operand is not (a!>b) is true
greater than the value of right operand
Logical operators in SQL are used to perform logical operations on the given expressions
in SQL statements. There are many operators in SQL which are used in SQL statements in
the WHERE clause.
Operator Description
AND Returns TRUE if all conditions are true.
69
Q) Where clause:
• SQLWHERE clause is used to filter the records from the table based on the given
condition.
• A WHERE clause in SQL is a data manipulation language statement.
The WHERE clause can be used with the following types of SQL statements:
• SELECT
• UPDATE
• DELETE
A WHERE clause with a SELECT statement:
SELECT column-names FROM table-name WHERE condition;
A WHERE clause with an UPDATE statement:
UPDATE table-name SET column-name = value WHERE condition;
A WHERE clause with a DELETE statement:
DELETE table-name WHERE condition;
WHERE clause uses some conditional selection: <, >, <=, >=, !=, =
Ex: EMP TABLE
70
Ex: SQL>select *from emp where sal=3000;
SQL> select *from emp where SAL>1000;
SQL>select *from emp where sal>=1000;
SQL>select *from emp where sal<3000;
SQL>select *from emp where sal<=3000;
SQL>select *from emp where sal!=3000;
SQL>select *from emp where sal<>3000;
SQL>update emp set sal=sal+2000 where sal=1100;
SQL>Delete emp where empno=1234;
AND operator:
• SQL ‘ AND’ operator is used when we want to combine multiple conditions as part
of the WHERE clause. The result set will be filtered based on the condition.
• if both the conditions are true then only the result will be filtered.
• To combine multiple conditions, we can use more than one AND as part of the WHERE
clause.
syntax: SELECT column(s) FROM table_name WHERE condition1 AND condition2;
NOT Operator
• SQL NOT operator is used when we want to filter result set when the condition
is not satisfied in the WHERE clause.
Syntax: SELECT column(s) FROM table_name WHERE NOT condition;
71
BETWEEN Operator:
• The BETWEEN operator selects values within a given range. The values can be
numbers, text, or dates.
Syntax: SELECT column_name(s) FROM table_name WHERE column_name BETWEEN
value1 AND value2;
Ex: SQL> SELECT *FROM EMP WHERE SAL BETWEEN 1000 AND 3000;
EX: SELECT Fname, Lname FROM Employee where DOB BETWEEN '1985-01-01'
AND '1990-12-30';
IN operator:
• The IN operator checks a value within a set of values separated by commas and retrieve
the rows from the table which are matching.
• The IN returns 1 when the search value present within the range otherwise returns 0.
Like Operator:
• The LIKE operator is used to list all rows in a table whose column values match a
specified pattern.
• It is useful when you want to search rows to match a specific pattern, or when you do
not know the entire value.
• For this purpose, we use a wildcard character '%'
o The percent sign (%)
o The underscore (_)
• The percent sign represents zero, one or multiple characters. The underscore represents
a single number or character. These symbols can be used in combinations.
Syntax: SELECT * FROM table_name WHERE column LIKE 'XXXX%'
Ex: SQL> select * from emp where ename like ‘J%’;
SQL> select * from emp where ename like ‘J_O%’;
SQL> select * from emp where ename like ‘_L_%’;
72
ORDER BY Clause:
• The SQL ORDER BY clause is used for sorting data in ascending and descending order
based on one or more columns.
• Some databases sort query results in ascending order by default
Sort according to one column: To sort in ascending or descending order we can use the
keywords ASC or DESC respectively.
Syntax: SELECT * FROM table_name ORDER BY column_name ASC/DESC.;
Sort according to multiple columns: To sort in ascending or descending order we can
use the keywords ASC or DESC respectively. To sort according to multiple columns,
separate the names of columns by (,) operator.
GROUP BY Clause:
The Group By statement is used for organizing similar data into groups Using some
functions.
Important Points:
GROUP BY clause is used with the SELECT statement.
In the query, GROUP BY clause is placed after the WHERE clause.
In the query, GROUP BY clause is placed before ORDER BY clause if used any.
EX: CUSTOMERS
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
|1 |Ramesh |32 |Ahmedabad |2000.00|
|2 |Khilan |25 |Delhi |1500.00|
|3 |Kaushik |23 |Kota |2000.00|
|4 |Chaitali |25 |Mumbai |6500.00|
|5 |Hardik |27 |Bhopal |8500.00|
|6 |Komal |22 | MP |4500.00|
|7 |Muffy |24 |Indore |10000.00
73
Q)Aggregate Functions in SQL:
• SQL aggregation functions are 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.
1. Avg ():
• The Avg function is used to calculate the average value of the numeric type.
• Avg function returns the average of all non-Null values.
Syntax: SQL>SELECT Avg (column_name) FROM table_name WHERE condition;
Example: SQL> Select Avg(salary)from emp;
2. COUNT ()
• 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.
Syntax: SQL>SELECT COUNT(column_name) FROM table_name WHERE condition;
Ex: emp table
Id Name salary
1 A 80
2 B 40
3 C 60
4 D 70
5 E 60
6 F NULL
74
Example: SQL> select count(id)from emp;
SQL> Select count(id)from emp where sal>60;
3. count (*):
The COUNT (*) function returns the number of rows in a table including the rows that
contain the NULL values.
Syntax: SQL>SELECT COUNT (*) FROM table_name WHERE condition;
Example: SQL> Select count(*)from emp;
4. FIRST ():
The FIRST () function returns the first value of the selected column.
Syntax:
SELECT FIRST(Column_name) FROM table_name;
Ex: SELECT FIRST(sal) FROM emp;
5. LAST ()
The LAST () function returns the last value of the selected column.
Syntax
SELECT LAST(column_name) FROM table_name;
Ex: SELECT LAST(sal) FROM emp;
6. max ():
• MAX function is used to find the maximum value of a certain column.
• This function determines the largest value of all selected values of a column
Syntax: SQL>SELECT MAX (column_name) FROM table_name WHERE condition;
Example: SQL> Select MAX(salary)from emp;
7. MIN ():
• MIN function is used to find the minimum value of a certain column.
• This function determines the smallest value of all selected values of a column.
Syntax: SQL>SELECT min(column_name) FROM table_name WHERE condition;
Example: SQL> Select min(salary)from emp;
8. SUM ():
• Sum function is used to calculate the sum of all selected columns. It works on numeric
fields only.
• Null values are excluded from the result returned.
Syntax: SQL>SELECT sum(column_name) FROM table_name WHERE condition;
Example: SQL>Select sum(salary)from emp;
9. SQRT(): SQRT function is used to find out the square root of any number. You can
Use SELECT statement to find out square root of any number as follows.
Syntax: SQL>SELECT SQRT(Value) FROM DUAL;
Example: SQL>SELECT SQRT(16) FROM DUAL;
75