0% found this document useful (0 votes)
4 views54 pages

DBMS Unit-3

The document provides an introduction to SQL, detailing its history, structure, and various components including data definition, data manipulation, integrity constraints, and types of SQL commands. It explains the basic structure of SQL queries and the use of clauses such as SELECT, FROM, and WHERE, along with the different types of SQL commands like DDL, DML, DCL, and TCL. Additionally, it covers integrity constraints, SQL data types, and examples of SQL commands for creating, modifying, and querying databases.

Uploaded by

Prachi Nilekar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views54 pages

DBMS Unit-3

The document provides an introduction to SQL, detailing its history, structure, and various components including data definition, data manipulation, integrity constraints, and types of SQL commands. It explains the basic structure of SQL queries and the use of clauses such as SELECT, FROM, and WHERE, along with the different types of SQL commands like DDL, DML, DCL, and TCL. Additionally, it covers integrity constraints, SQL data types, and examples of SQL commands for creating, modifying, and querying databases.

Uploaded by

Prachi Nilekar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 54

Introduction to SQL

› Overview,
› SQL data definition,
› SQL data types,
› Integrity constraints,
› Basic structure of SQL Queries,
› Types of SQL Commands: DDL, DML, DCL and TCL
statements,
› Basic SQL clauses [select, from, where, group by, having,
order by etc.].
Overview
› IBM developed the original version of SQL, originally called
Sequel, as part of the System R project in the early 1970s.
› The Sequel language has evolved since then, and its name
has changed to SQL (Structured Query Language).
› Many products now support the SQL language. SQL has
clearly established itself as the standard relational database
language.
› In 1986, the American National Standards Institute (ANSI)
and the International Organization for Standardization (ISO)
published an SQL standard, called SQL-86.
› ANSI published an extended standard for SQL, SQL-89, in
1989. The next version of the standard was SQL-92
standard, followed by SQL:1999, SQL:2003, SQL:2006, and
most recently SQL:2008.
The SQL language has several parts:
• Data-definition language (DDL). The SQL DDL provides
commands for defining relation schemas, deleting relations,
and modifying relation schemas.
• Data-manipulation language (DML). The SQL DML
provides the ability to query information from the database
and to insert tuples into, delete tuples from, and modify
tuples in the database.
• Integrity. The SQL DDL includes commands for specifying
integrity constraints that the data stored in the database must
satisfy. Updates that violate integrity constraints are
disallowed.
• View definition. The SQL DDL includes commands for
defining views.
• Transaction control. SQL includes commands for specifying
the beginning and ending of transactions.
• Embedded SQL and dynamic SQL. Embedded and
dynamic SQL define how SQL statements can be embedded
within general-purpose programming languages, such as C,
C++, and Java.
• Authorization. The SQL DDL includes commands for
specifying access rights to relations and views.
SQL Data Definition
⮚ The SQL data-definition language is used to create relations with
specified schemas. In addition to specifying the names and types of
relation attributes, SQL also allows the specification of integrity
constraints such as primary-key constraints and foreign-key constraints.
⮚ The set of relations in a database must be specified to the system by
means of a data-definition language (DDL). The SQL DDL allows
specification of not only a set of relations, but also information about
each relation, including:
› The schema for each relation.
› The types of values associated with each attribute.
› The integrity constraints.
› The set of indices to be maintained for each relation.
› The security and authorization information for each relation.
› The physical storage structure of each relation on disk.
SQL Data Types
Integrity Constraints
› Integrity constraints are a set of rules. It is used to maintain the quality
of information.
› Integrity constraints ensure that the data insertion, updating, and other
processes have to be performed in such a way that data integrity is
not affected.
› Thus, integrity constraint is used to guard against accidental damage
to the database.
Types of Integrity Constraint
1. Domain constraints
› Domain constraints can be defined as the definition of a
valid set of values for an attribute.
› The data type of domain includes string, character, integer,
time, date, currency, etc. The value of the attribute must be
available in the corresponding domain.
› Example:
2. Entity Integrity Constraints
› The entity integrity constraint states that primary key value
can't be null.
› This is because the primary key value is used to identify
individual rows in relation and if the primary key has a null
value, then we can't identify those rows.
› A table can contain a null value other than the primary key
field.
3. Referential Integrity Constraints
› A referential integrity constraint is specified between two tables.
› In the Referential integrity constraints, if a foreign key in Table 1 refers to
the Primary Key of Table 2, then every value of the Foreign Key in Table 1
must be null or be available in Table 2.
4. Key constraints

› Keys are the entity set that is used to identify an entity


within its entity set uniquely.
› An entity set can have multiple keys, but out of which one
key will be the primary key. A primary key can contain a
unique and null value in the relational table.
Basic structure of SQL Queries
SQL queries are the questions or requests imposed on the set of data to retrieve the desired
information.
The fundamental structure of SQL queries includes three clauses:
Select- What we want in the final result relation is specified in the select clause.
From-Which relations we need to access to get the result is specified in from clause.
Where- How the relation must be operated to get the result is specified in the where clause.
select A1, A2, . . . , An
from r1, r2, . . . , rm
where P;
› In the select clause, you have to specify the attributes that you want to see in the result
relation
› In the from clause, you have to specify the list of relations that has to be accessed for
evaluating the query.
› In the where clause involves a predicate that includes attributes of the relations that we have
listed in the from clause.
› This query is equivalent to the relational algebra expression:
› ΠA1, A2, ..., An(σP (r1 × r2 × ... × rm))
The Select Clause:
Select Clause(cont…)
Select Clause(cont…)
Where Clause
Where Clause(cont…)
The From Clause
The Rename Operation
Types of SQL Commands: DDL, DML, DCL and TCL
statements
› SQL commands are instructions. It is used to communicate with the database. It
is also used to perform specific tasks, functions, and queries of data.
› SQL can perform various tasks like create a table, add data to tables, drop the
table, modify the table, set permission for users.
› Types of SQL Commands
› There are four types of SQL commands: DDL, DML, DCL, TCL.
› Data Definition Language(DDL) – Consists of commands which are used to
define the database.
› Data Manipulation Language(DML) – Consists of commands which are used
to manipulate the data present in the database.
› Data Control Language(DCL) – Consists of commands which deal with the
user permissions and controls of the database system.
› Transaction Control Language(TCL) – Consist of commands which deal with
the transaction of the database.
› consider the below database as an example, to show you
how to write commands.
Comments in SQL
› There are two ways in which you can comment in SQL.
› Single-Line Comments
› The single line comment starts with two hyphens (–). So, any text mentioned
after (–), till the end of a single line will be ignored by the compiler.
Example:
1. --Select all--
2. SELECT * FROM Employee_Info;
› Multi-Line Comments
› The Multi-line comments start with /* and end with */. So, any text mentioned
between /* and */ will be ignored by the compiler.
› Example:
1. /*Select all the columns
2. of all the records
3. from the Employee_Info table:*/
4. SELECT * FROM Students;
SQL Commands: Data Definition Language (DDL)
1. CREATE
› This statement is used to create a table or a database.
› The ‘CREATE DATABASE’ Statement
› As the name suggests, this statement is used to create a
database.
› Syntax:
› CREATE DATABASE DatabaseName;
› Example
1. CREATE DATABASE Employee;
DDL(Cont…)
› The ‘CREATE TABLE’ Statement
› This statement is used to create a table.
› Syntax
› CREATE TABLE TableName (
› Column1 datatype,
› Column2 datatype,
› .... ColumnN datatype );
Example
1. CREATE TABLE Employee_Info
2. (
3. EmployeeID int,
4. EmployeeName varchar(255),
5. Emergency ContactName varchar(255),
6. PhoneNumber int,
7. Address varchar(255),
8. City varchar(255),
9. Country varchar(255)
10. );
‘CREATE TABLE AS’ Statements:
› You can also create a table using another table. Refer the below
syntax and example:
› The ‘CREATE TABLE AS’ Statement
› Syntax
› CREATE TABLE NewTableName AS SELECT Column1, column2,...,
ColumnN FROM ExistingTableName WHERE ....;
Example:
1. CREATE TABLE ExampleTable AS
2. SELECT EmployeeName, PhoneNumber
3. FROM Employee_Info;
2. DROP
› This statement is used to drop an existing table or a
database.
› The ‘DROP DATABASE’ Statement
› This statement is used to drop an existing database. When
you use this statement, complete information present in the
database will be lost.
Syntax:
› DROP DATABASE DatabaseName;
› Example:
1 DROP DATABASE Employee;
The ‘DROP TABLE’ Statement
› This statement is used to drop an existing table. When you
use this statement, complete information present in the
table will be lost.
› Syntax
› DROP TABLE TableName;
› Example
1. DROP Table Employee_Info;
3. TRUNCATE
› This command is used to delete the information present in
the table but does not delete the table.
› So, once you use this command, your information will be
lost, but not the table.
› Syntax
› TRUNCATE TABLE TableName;
Example:
1 TRUNCATE Table Employee_Info;
4. ALTER
› This command is used to delete, modify or add constraints or columns
in an existing table.
› The ‘ALTER TABLE’ Statement
› This statement is used to add, delete, modify columns in an existing
table.
› The ‘ALTER TABLE’ Statement with ADD/DROP COLUMN
› You can use the ALTER TABLE statement with ADD/DROP Column
command according to your need.
› If you wish to add a column, then you will use the ADD COLOUM
command, and if you wish to delete a column, then you will use the
DROP COLUMN command.
Syntax
› ALTER TABLE TableName ADD ColumnName Datatype;
ALTER TABLE TableName DROP COLUMN ColumnName;
› Examples:
1. -- ADD Column BloodGroup --
2. ALTER TABLE Employee_Info
3. ADD BloodGroup varchar(255);

4. -- DROP Column BloodGroup --


5. ALTER TABLE Employee_Info
6. DROP COLUMN BloodGroup ;
› SQL Commandas: Data Manipulation Language
Command (DML)
1. INSERT INTO
› This statement is used to insert new records into the table.
Syntax:
INSERT INTO TableName (Column1, Column2, Column3, ...,ColumnN) VALUES (value1,
value2, value3, ...);

› --If you don't want to mention the column names then use the below syntax :
INSERT INTO TableName VALUES (Value1, Value2, Value3, ...);

› Examples:
1. INSERT INTO Employee1(EmployeeID, EmployeeName, Emergency_ContactName,
PhoneNumber, Address, City, Country)
2. VALUES('06', 'Sanjana','Jagannath', '992132114', 'Camel Street House No 12',
'Chennai', 'India');

3. INSERT INTO Employee_Info


4. VALUES ('07', 'Sayantini','Praveen', '9934567654', 'Nice Road 21', 'Pune', 'India');
2. UPDATE

› This statement is used to modify the records already present


in the table.
› Syntax
› UPDATE TableName SET Column1 = Value1, Column2 =
Value2, ... WHERE Condition;
Example:
1. UPDATE Employee_Info
2. SET EmployeeName = 'Aahana', City= 'Ahmedabad'
3. WHERE EmployeeID = 1;
3. DELETE
› This statement is used to delete the existing records in a
table.
› Syntax
› DELETE FROM TableName WHERE Condition;
› Example
1. DELETE FROM Employee_Info
2. WHERE EmployeeName='Preeti';
4. SELECT
› This statement is used to select data from a database and the data
returned is stored in a result table, called the result-set.
› Syntax
SELECT Column1, Column2, ...ColumN
FROM TableName;

› --(*) is used to select all from the table


SELECT * FROM table_name;
› -- To select the number of records to return use:
SELECT FROM TableName
LIMIT number;
› Select Example
1. SELECT EmployeeID, EmployeeName
2. FROM Employee_Info;
3.
4. --(*) is used to select all from the table
5. SELECT * FROM Employee_Info;
6.
7. -- To select the number of records to return use:
8. SELECT * FROM Employee_Info
9. LIMIT ‘2’;
Basic SQL clauses
› Apart from just using the SELECT keyword individually, we can use the
following keywords with the SELECT statement:
– DISTINCT
– ORDER BY
– GROUP BY
– HAVING Clause

› The ‘SELECT DISTINCT’ Statement


› This statement is used to return only different values.
› Syntax
› SELECT DISTINCT Column1, Column2, ...ColumnN FROM TableName;
› Example
› 1 SELECT DISTINCT PhoneNumber FROM Employee_Info;
› The ‘ORDER BY’ Statement
› The ‘ORDER BY’ statement is used to sort the required results in
ascending or descending order.
› The results are sorted in ascending order by default. Yet, if you wish to
get the required results in descending order, you have to use
the DESC keyword.
› Syntax
› SELECT Column1, Column2, ...ColumnN FROM TableName ORDER
BY Column1, Column2, ... ASC|DESC;
ORDER BY Examples:
› -- Select all employees from the 'Employee_Info' table sorted by Emergency
ContactName--
1. SELECT * FROM Employee_Info
2. ORDER BY Emergency_ContactName;

› -- Select all employees from the 'Employee_Info' table sorted by Emergency


ContactName in Descending order--
1. SELECT * FROM Employee_Info
2. ORDER BY Emergency_ContactName DESC;

› /* Select all employees from the 'Employee_Info' table sorted by


EmergencyContactName in Descending order and EmployeeName in
Ascending order: */
1. SELECT * FROM Employee_Info
2. ORDER BY EmergencyContactName ASC, EmployeeName DESC;
The ‘GROUP BY’ Statement
› This ‘GROUP BY’ statement is used with the aggregate functions to
group the result-set by one or more columns.

Syntax
› SELECT Column1, Column2,..., ColumnN FROM TableName WHERE
Condition GROUP BY ColumnName(s) ORDER BY ColumnName(s);
› Example
1. -- To list the number of employees from each city--
2. SELECT COUNT(EmployeeID), City
3. FROM Employee_Info
4. GROUP BY City;
The ‘HAVING’ Clause

› The ‘HAVING’ clause is used in SQL because the WHERE keyword cannot be used
everywhere.
› We use the HAVING clause to filter groups by using single or multiple columns.
› It is noted that the WHERE clause filters the records while the HAVING clause filter the groups.
Syntax
› SELECT ColumnName(s) FROM TableName WHERE Condition GROUP BY ColumnName(s)
HAVING Condition ORDER BY ColumnName(s);
› Example
› /* To list the number of employees in each city. The employees should be sorted high to low
and only those cities must be included who have more than 1 employees:*/

› SELECT COUNT(EmployeeID), City


› FROM Employee_Info
› GROUP BY City
› HAVING COUNT(EmployeeID) > 1
› ORDER BY COUNT(EmployeeID) DESC;
DCL Commands
› DCL commands are used to enforce database security in a
multiple database environment.
› Two types of DCL commands are •
› Grant
› Revoke
› Database Administrator's or owner’s of the database object
can provide/remove privileges on a database object.
SQL Grant Command
› SQL Grant command is used to provide access or privileges on the
database objects to the users. •
› The syntax for the GRANT command is:
› GRANT privilege_name ON object_name TO {user_name |
PUBLIC | role_name} [with GRANT option];
› Here, privilege_name: is the access right or privilege granted to the
user.
› object_name: is the name of the database object like table, view etc.,.
› user_name: is the name of the user to whom an access right is being
granted.
› Public is used to grant rights to all the users.
› With Grant option: allows users to grant access rights to other users.
› SQL Revoke Command •
› The revoke command removes user access rights or
privileges to the database objects. •
› The syntax for the REVOKE command is:
› REVOKE privilege_name ON object_name FROM
{User_name | PUBLIC | Role_name}
› For Example:
1. GRANT SELECT ON employee TO user1
› This command grants a SELECT permission on employee
table to user1.
2. REVOKE SELECT ON employee FROM user1
› This command will revoke a SELECT privilege on employee
table from
Privileges and Roles
Privileges defines the access rights provided to a user on a
database objects.
There are two types of privileges:
(a) System Privileges: This indicate user to CREATE, ALTER, or
" "DROP database elements.
(b) (b) Object Privileges: This allows user to EXECUTE,
SELECT, INSERT, or DELETE data from database objects to
which the privileges apply.
Roles are the collection of privileges or access rights. When
there are many users in a database it becomes difficult to
grant or revoke privileges to the users.
So, if we define roles we can automatically grant/revoke
privileges.
Transaction Control Language(TCL)
› Transaction Control Language can be defined as the portion
of a database language used for maintaining consistency of
the database and managing transactions in the database.
› A set of SQL statements that are co-related logically and
executed on the data stored in the table is known as a
transaction.
› There are three commands that come under the TCL.
1. Commit
2. Rollback
3. Savepoint
1. Commit
› The main use of Commit command is to make the transaction
permanent.
› If there is a need for any transaction to be done in the database that
transaction permanent through commit command.
› Syntax: COMMIT;
› Example
1. UPDATE Employee_Info SET Employee_Name= ‘Maria’ WHERE
Employee_Name= ‘Sanjana’;
2. COMMIT;

By using the above set of instructions, you can update the wrong Employee
Name by the correct one and save it permanently in the database.
The update transaction gets completed when commit is used.
If commit is not used, then there will be lock on ‘Sanjana’ record till the
rollback or commit is issued.
Rollback
› Using this command, the database can be restored to the last committed
state.
› Additionally, it is also used with savepoint command for jumping to a
savepoint in a transaction.
› Syntax : Rollback to savepoint-name;
› For example
1. UPDATE Employee_Info SET Employee_Name= ‘Maria’
2. WHERE EmployeeName= ‘Sanjana’;
3. ROLLBACK;
› This command is used when the user realizes that he/she has updated the
wrong information after the student name and wants to undo this update.
› The users can issues ROLLBACK command and then undo the update.
Have a look at the below tables to know better about the implementation
of this command.
3. Savepoint:
› The main use of the Savepoint command is to save a transaction
temporarily. This way users can rollback to the point whenever it is needed.
Syntax:
SAVEPOINT SAVEPOINT_NAME; --Syntax for saving the SAVEPOINT
ROLLBACK TO SAVEPOINT_NAME; --Syntax for rolling back to the Savepoint command

Example:
› Use some SQL queries on the above table and then watch the results
1. INSERT into CLASS VALUES (101, ‘Rahul);
2. Commit;
3. UPDATE CLASS SET NAME= ‘Tyler’ where id= 101
4. SAVEPOINT A;
5. INSERT INTO CLASS VALUES (102, ‘Zack’);
6. Savepoint B;
7. INSERT INTO CLASS VALUES (103, ‘Bruno’)
8. Savepoint C;
9. Select * from Class;
11. --Now rollback to savepoint B--
12. Rollback to B;
13. SELECT * from Class;

You might also like