0% found this document useful (0 votes)
36 views

Dbms 1

This document discusses database management systems (DBMS) and Structured Query Language (SQL). It begins by defining what data and databases are. It then explains what SQL is and some common SQL commands like CREATE, SELECT, UPDATE, DELETE, and INSERT. It discusses different types of DBMS languages including DDL, DML, DCL, and TCL. It also covers SQL concepts like tables, columns, rows, NULL values, and the DISTINCT keyword.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

Dbms 1

This document discusses database management systems (DBMS) and Structured Query Language (SQL). It begins by defining what data and databases are. It then explains what SQL is and some common SQL commands like CREATE, SELECT, UPDATE, DELETE, and INSERT. It discusses different types of DBMS languages including DDL, DML, DCL, and TCL. It also covers SQL concepts like tables, columns, rows, NULL values, and the DISTINCT keyword.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 45

DBMS-LAB

• What is Data?
• Data is a collection of a distinct small unit of information. It can be used in a variety of forms like text, numbers, media,
bytes, etc. it can be stored in pieces of paper or electronic memory, etc.
• A database is an organized collection of data, so that it can be easily accessed and managed.
• You can organize data into tables, rows, columns, and index it to make it easier to find relevant information.
• Database handlers create a database in such a way that only one set of software program provides access of data
to all the users.
• The main purpose of the database is to operate a large amount of information by storing, retrieving, and
managing data.
• There are many dynamic websites on the World Wide Web nowadays which are handled through databases. For
example, a model that checks the availability of rooms in a hotel. It is an example of a dynamic website that uses
a database.
• There are many databases available like MySQL, Sybase, Oracle, MongoDB, Informix, PostgreSQL, SQL Server, etc.
• Modern databases are managed by the database management system (DBMS).
• SQL or Structured Query Language is used to operate on the data stored in a database. SQL depends on relational
algebra and tuple relational calculus.
SQL
• SQL (Structured Query Language) is used to perform operations on
the records stored in the database, such as updating records, inserting
records, deleting records, creating and modifying database tables,
views, etc.
• SQL is not a database system, but it is a query language.
• Suppose you want to perform the queries of SQL language on the
stored data in the database. You are required to install any database
management system in your systems, for example, Oracle, MySQL,
MongoDB, PostgreSQL, SQL Server, DB2, etc.
• Why SQL?
• Nowadays, SQL is widely used in data science and analytics. Following are the
reasons which explain why it is widely used:
• The basic use of SQL for data professionals and SQL users is to insert, update, and
delete the data from the relational database.
• SQL allows the data professionals and users to retrieve the data from the relational
database management systems.
• It allows SQL users to create, drop, and manipulate the database and its tables.
• It also helps in creating the view, stored procedure, and functions in the relational
database.
• It allows you to define the data and modify that stored data in the relational
database.
• It also allows SQL users to set the permissions or constraints on table columns,
views, and stored procedures.
• Some SQL Commands
• The SQL commands help in creating and managing the database. The
most common SQL commands which are highly used are mentioned
below:
• CREATE command
• UPDATE command
• DELETE command
• SELECT command
• DROP command
• INSERT command
CREATE Command
This command helps in creating the new database, new table, table view, and other objects of the database.
UPDATE Command
This command helps in updating or changing the stored data in the database.
DELETE Command
This command helps in removing or erasing the saved records from the database tables. It erases
single or multiple tuples from the tables of the database.
SELECT Command
This command helps in accessing the single or multiple rows from one or multiple tables of the
database. We can also use this command with the WHERE clause.

DROP Command
This command helps in deleting the entire table, table view, and other objects from the database.
INSERT Command
This command helps in inserting the data or records into the database tables. We can easily insert the
records in single as well as multiple rows of the table.
Types of DBMS Language
• Data Definition Language (DDL)
• DDL stands for Data Definition Language. It is used to define database structure or pattern.
• It is used to create schema, tables, indexes, constraints, etc. in the database.
• Using the DDL statements, you can create the skeleton of the database.
• Data definition language is used to store the information of metadata like the number of tables
and schemas, their names, indexes, columns in each table, constraints, etc.
• Here are some tasks that come under DDL:
• Create: It is used to create objects in the database.
• Alter: It is used to alter the structure of the database.
• Drop: It is used to delete objects from the database.
• Truncate: It is used to remove all records from a table.
• Rename: It is used to rename an object.
• Comment: It is used to comment on the data dictionary.
• These commands are used to update the database schema that's why they come under Data
definition language.
Data Manipulation Language (DML)
DML stands for Data Manipulation Language. It is used for accessing and manipulating data
in a database. It handles user requests.
Here are some tasks that come under DML:

• Select: It is used to retrieve data from a database.


• 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 all records from a table.
• Merge: It performs UPSERT operation, i.e., insert or update
operations.
• Data Control Language (DCL)
• DCL stands for Data Control Language. It is used to retrieve the stored
or saved data.
• The DCL execution is transactional. It also has rollback parameters.
• Grant: It is used to give user access privileges to a database.
• Revoke: It is used to take back permissions from the user.
• There are the following operations which have the authorization of
Revoke:
• CONNECT, INSERT, USAGE, EXECUTE, DELETE, UPDATE and SELECT.
• Transaction Control Language (TCL)
• TCL is used to run the changes made by the DML statement. TCL can
be grouped into a logical transaction.
• Here are some tasks that come under TCL:
• Commit: It is used to save the transaction on the database.
• Rollback: It is used to restore the database to original since the last
Commit.
• SQL Table
• A table is also known as Relation that’s why it is called as Relational DBMS.
• Table is a collection of data, organized in terms of rows and columns. In DBMS term, table is
known as relation and row as tuple.
• Note: A table has a specified number of columns, but can have any number of rows.
• Table is the simple form of data storage. A table is also considered as a convenient representation
of relations.
• Let's see an example of an employee table:
Some of The Most Important SQL •ALTER DATABASE - modifies a database
Commands •CREATE TABLE - creates a new table
•SELECT - extracts data from a database •ALTER TABLE - modifies a table
•UPDATE - updates data in a database •DROP TABLE - deletes a table
•DELETE - deletes data from a database •CREATE INDEX - creates an index (search
•INSERT INTO - inserts new data into a key)
database •DROP INDEX - deletes an index
•CREATE DATABASE - creates a new
database
• SQL CREATE TABLE
• SQL CREATE TABLE statement is used to create table in a database.
• If you want to create a table, you should name the table and define its
column and each column's data type.
• Let's see the simple syntax to create the table.

• create table tablename  (column1 datatype,  column2 datatype, .......  
columnN datatype);  
Let us take an example to create a STUDENTS table with ID as primary key and NOT NULL
are the constraint showing that these fields cannot be NULL while creating records in the
table.

• SQL> CREATE TABLE STUDENTS (  
ID Number                           NOT NULL,  
NAME VARCHAR (20)  NOT NULL,  
AGE Number                        NOT NULL,  
ADDRESS VARCHAR2 (25),  
PRIMARY KEY (ID)  
);  
The SQL INSERT INTO Statement
The INSERT INTO statement is used to insert new records in a table.
INSERT INTO Syntax
It is possible to write the INSERT INTO statement in two ways:
1. Specify both the column names and the values to be inserted:

INSERT INTO table_name (column1, column2, column3, ...)


VALUES (value1, value2, value3, ...);

2. If you are adding values for all the columns of the table, you do not need to specify the column names in the
SQL query. However, make sure the order of the values is in the same order as the columns in the table. Here, the
INSERT INTO syntax would be as follows:

INSERT INTO table_name


VALUES (value1, value2, value3, ...);

Ex: INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)
VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway');

Ex: INSERT INTO Customers (CustomerName, City, Country)


VALUES ('Cardinal', 'Stavanger', 'Norway'); ->inserting data in only specified columns.
NULL VALUE
• What is a NULL Value?
• A field with a NULL value is a field with no value.
• If a field in a table is optional, it is possible to insert a new record or
update a record without adding a value to this field. Then, the field
will be saved with a NULL value.
SELECT
The SQL SELECT Statement
The SELECT statement is used to select data from a database.
The data returned is stored in a result table, called the result-set.
SELECT Syntax:

SELECTcolumn1, column2, ...


FROM table_name;

Here, column1, column2, ... are the field names of the table you want to select data from.
If you want to select all the fields available in the table, use the following syntax:

SELECT * FROM table_name;


The SQL SELECT DISTINCT Statement

The SELECT DISTINCT statement is used to return only distinct (different) values.
Inside a table, a column often contains many duplicate values;
and sometimes you only want to list the different (distinct) values.
SELECT DISTINCT Syntax

SELECT DISTINCT column1, column2, ...


FROM table_name;

The following SQL statement selects only the DISTINCT values from the "Country" column in the
"Customers" table:
EX: SELECT DISTINCT Country FROM Customers;

The following SQL statement lists the number of different (distinct) customer countries:
EX: SELECT COUNT(DISTINCT Country) FROM Customers;
The SQL WHERE Clause
The WHERE clause is used to filter records.
It is used to extract only those records that fulfill a specified condition.

column1, column2, ...


SELECT

FROM table_name WHERE condition;

Ex: SELECT * FROM Customers


WHERE Country='Mexico';

Ex: SELECT * FROM Customers


WHERE CustomerID=1;
The SQL AND, OR and NOT Operators:

The WHERE clause can be combined with AND, OR, and NOT operators.
The AND and OR operators are used to filter records based on more than one condition:
•The AND operator displays a record if all the conditions separated by AND are TRUE.
•The OR operator displays a record if any of the conditions separated by OR is TRUE.
•The NOT operator displays a record if the condition(s) is NOT TRUE.
AND Syntax:

SELECT column1, column2, ...


FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;

Ex: The following SQL statement selects all fields from "Customers" where country is
"Germany" AND city is "Berlin":

SELECT * FROM Customers


WHERE Country='Germany' AND City='Berlin';
OR Syntax
• SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
• The following SQL statement selects all fields from "Customers" where country is "Germany" OR
"Spain":
• Ex: SELECT * FROM Customers
WHERE Country='Germany' OR Country='Spain';
NOT Syntax
• SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;
• Ex:The following SQL statement selects all fields from "Customers" where country is NOT
"Germany":
SELECT * FROM Customers
WHERE NOT Country='Germany';
The SQL ORDER BY Keyword

The ORDER BY keyword is used to sort the result-set in ascending or descending order.
TheORDER BY keyword sorts the records in ascending order by default.
To sort the records in descending order, use the DESC keyword.

ORDER BY Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
The following SQL statement selects all customers from the "Customers" table, sorted by the
"Country" column:
SELECT * FROM Customers
ORDER BY Country;
The following SQL statement selects all customers from the "Customers" table, sorted
DESCENDING by the "Country" column:
SELECT * FROM Customers
ORDER BY Country DESC;
SQL ALTER TABLE Statement
The ALTER TABLE statement 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 TABLE - ADD Column


To add a column in a table, use the following syntax:
ALTER TABLE table_name
ADD column_name datatype;
The following SQL adds an "Email" column to the "Customers" table:
Example
ALTER TABLE Customers
ADD Email varchar(255);
ALTER TABLE - DROP COLUMN
To delete a column in a table, use the following syntax (notice that some database systems don't allow
deleting a column):
ALTER TABLE table_name
DROP COLUMN column_name;
The following SQL deletes the "Email" column from the "Customers" table:
Example
ALTER TABLE Customers
DROP COLUMN Email;

ALTER TABLE - RENAME COLUMN


To rename a column in a table, use the following syntax:
ALTER TABLE table_name
RENAME COLUMN old_name to new_name;

ALTER TABLE - ALTER/MODIFY DATATYPE


To change the data type of a column in a table, use the following syntax:

ALTER TABLE table_name
MODIFY column_name datatype;
SQL Cloning Tables
Cloning or Copying a Table
There may be a situation when you just want to create an exact copy or clone of an existing table to test
or perform something without affecting the original table.
The following section describes how to do this in few easy steps.
Step 1: Creating an Empty Table
First use the following statement to create an empty table based on the definition of original table. It also
includes the column attributes and indexes defined in the original table:
CREATE TABLE emp1 LIKE employee;
Step 2: Inserting Data into Table
Now, use the following statement to populate the empty table with data from original table:
INSERT INTO new_table SELECT * FROM original_table;

Simple Cloning
However, if you just want to create a table from another table without taking into account any column
attributes and indexes you can use the simple one line statement:
CREATE TABLE new_table  as SELECT * FROM original_table;

CREATE TABLE COPYOF_DEPT AS SELECT * FROM DEPARTMENT;


SQL DROP Database
• The SQL Drop Database statement deletes the existing database permanently from
the database system. This statement deletes all the views and tables if stored in the
database, so be careful while using this query in SQL.
• This statement deletes all the data from the database. If you want to restore the
deleted data in the future, you should keep the backup of data of that database
which you want to delete.
• Syntax of Drop Database Statement in SQL
• DROP DATABASE Database_Name;  
• In this SQL syntax, we have to specify the name of that database which we want
to delete permanently from the database system. We have to write the name of the
database after the DROP DATABASE keyword in every example.
SQL DELETE TABLE
• The DELETE statement is used to delete rows from a table. If you want to remove
a specific row from a table you should use WHERE condition.
• DELETE FROM table_name [WHERE condition];  
• But if you do not specify the WHERE condition it will remove all the rows from
the table.
• DELETE FROM table_name;  
• There are some more terms similar to DELETE statement like as DROP statement
and TRUNCATE statement but they are not exactly same there are some
differences between them.
Difference between DELETE and TRUNCATE statements
• There is a slight difference b/w delete and truncate statement. The DELETE
statement only deletes the rows from the table based on the condition defined by
WHERE clause or delete all the rows from the table when condition is not
specified.
• But it does not free the space containing by the table.
• The TRUNCATE statement: it is used to delete all the rows from the table and
free the containing space.
Difference b/w DROP and TRUNCATE statements
• When you use the drop statement it deletes the table's row together with the table's
definition so all the relationships of that table with other tables will no longer be
valid.
• When you drop a table:
• Table structure will be dropped
• Relationship will be dropped
• Integrity constraints will be dropped
• Access privileges will also be dropped
• On the other hand when we TRUNCATE a table, the table structure remains the
same, so you will not face any of the above problems.
Types of Keys in DBMS (Database Management System)
There are mainly Eight different types of Keys in DBMS and each key has it’s different
functionality:
1.Super Key
2.Primary Key
3.Candidate Key
4.Alternate Key
5.Foreign Key
6.Compound Key
7.Composite Key
8.Surrogate Key
•Super Key – A super key is a group of single or multiple keys which identifies rows in a
table.
•Primary Key – is a column or group of columns in a table that uniquely identify every row in
that table.
•Candidate Key – is a set of attributes that uniquely identify tuples in a table. Candidate Key
is a super key with no repeated attributes.
•Alternate Key – is a column or group of columns in a table that uniquely identify every row
in that table.
•Foreign Key – is a column that creates a relationship between two tables. The purpose of
Foreign keys is to maintain data integrity and allow navigation between two different instances
of an entity.
•Compound Key – has two or more attributes that allow you to uniquely recognize a specific
record. It is possible that each column may not be unique by itself within the database.
•Composite Key – is a combination of two or more columns that uniquely identify rows in a
table. The combination of columns guarantees uniqueness, though individual uniqueness is not
guaranteed.
•Surrogate Key – An artificial key which aims to uniquely identify each record is called a
surrogate key. These kind of key are unique because they are created when you don’t have any
SQL UNIQUE Constraint
The UNIQUE constraint ensures that all values in a column are
different.
Both the UNIQUE and PRIMARY KEY constraints provide a
guarantee for uniqueness for a column or set of columns.
A PRIMARY KEY constraint automatically has a UNIQUE constraint.
However, you can have many UNIQUE constraints per table, but only
one PRIMARY KEY constraint per table.

CREATE TABLE Persons (
    ID int NOT NULL UNIQUE,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int
);
The PRIMARY KEY constraint uniquely identifies each record in a table.
Primary keys must contain UNIQUE values, and cannot contain NULL values.
A table can have only ONE primary key; and in the table, this primary key can consist
of single or multiple columns (fields).

CREATE TABLE Persons (
    ID Number NOT NULL PRIMARY KEY,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age Number
);
SQL PRIMARY KEY on ALTER TABLE
To create a PRIMARY KEY constraint on the "ID" column when the table is already created, use the following
SQL:
ALTER TABLE Persons
ADD PRIMARY KEY (ID);
DROP a PRIMARY KEY Constraint
To drop a PRIMARY KEY constraint, use the following SQL:
ALTER TABLE Persons
DROP PRIMARY KEY;
SQL FOREIGN KEY Constraint
The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.
A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY KEY in another
table.
The table with the foreign key is called the child table, and the table with the primary key is called the referenced
or parent table.
CREATE TABLE Orders (
    OrderID int NOT NULL PRIMARY KEY,
    OrderNumber int NOT NULL,
    PersonID int FOREIGN KEY REFERENCES Persons(PersonID)
);
To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple
columns, use the following SQL syntax:
CREATE TABLE Orders (
    OrderID int NOT NULL,
    OrderNumber int NOT NULL,
    PersonID int,
    PRIMARY KEY (OrderID),
    CONSTRAINT FK_PersonOrder FOREIGN KEY (PersonID)
    REFERENCES Persons(PersonID)
);
Create table student_Details (
Roll No. number,
Name varchar(20),
Course_Id number,
Primary key (Course_Id)
);

Create table Student_Marks(


Course_Id number,
Gpa number,
References student_Details
(Course_Id)
);
SQL FOREIGN KEY on ALTER TABLE
To create a FOREIGN KEY constraint on the "PersonID" column when the "Orders"
table is already created, use the following SQL:
ALTER TABLE Orders
ADD FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);

DROP a FOREIGN KEY Constraint


To drop a FOREIGN KEY constraint, use the following SQL:
ALTER TABLE Orders
DROP CONSTRAINT FK_PersonOrder;
create table dept(
deptno number,
dname varchar2(14),
loc varchar2(13)
);

insert into dept


values(10, 'ACCOUNTING', 'NEW YORK');
insert into dept
values(20, 'RESEARCH', 'DALLAS');
select * from dept;

insert into emp values(&id,'&name',&deptno );


insert into dept values(&deptno,'&dname','&loc');
insert into emp values( 7839, 'KING', 'PRESIDENT',
null,
to_date('17-11-1981','dd-mm-yyyy'),
5000, null, 10
);
insert into emp values(‘&fname’,’&mini’,&deptno);
Enter fname: abc
Enter mini:a

You might also like