Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
10 views60 pages

DBMS Syntax Description

The document outlines various SQL commands and concepts, including DDL and DML commands, constraints, foreign key constraints, aggregate functions, and different types of joins. It provides syntax and examples for creating tables, inserting data, querying with SELECT statements, and using WHERE clauses, subqueries, and joins. Each section includes SQL execution queries demonstrating the application of these concepts in database management.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views60 pages

DBMS Syntax Description

The document outlines various SQL commands and concepts, including DDL and DML commands, constraints, foreign key constraints, aggregate functions, and different types of joins. It provides syntax and examples for creating tables, inserting data, querying with SELECT statements, and using WHERE clauses, subqueries, and joins. Each section includes SQL execution queries demonstrating the application of these concepts in database management.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 60

Ex No.

1 DDL and DML commands, constraints(unique, not null, check)

AIM: To create a table using DDL and DML commands along with constraints.

Syntax:
create table <table_name>(
column1 datatype1 NOT NULL,
column2 datatype2,
column3 datatype3,
.
.
columnN datatype4,
);

insert into table name values (value1,…,valuen);


select <column1>,<column2> (or) * from table_name;
ALTER TABLE table_name
ADD CONSTRAINT constraint_name UNIQUE (column_name);
update table_name set <column_name> where <condition>;
Description:
The create table table_name syntax is used to create a table with columns of
specific data types and constraints

INSERT command is used to insert each row in the table

SELECT command can be used to display the entired data in the table as well as
selecting specific columns from the table with or without condition.

UPDATE command is used to set a column value to a new one based on the
condition.

ALTER table command is used to add columns, constraints to specified columns


in the table and modify datatype size.
(Query Execution)
SQL> CREATE TABLE employees (
2 emp_id INT PRIMARY KEY,
3 emp_name VARCHAR(100) NOT NULL,
4 emp_salary DECIMAL(10, 2) NOT NULL,
5 emp_dept_id INT,
6 CONSTRAINT chk_emp_salary CHECK (emp_salary >= 0)
7 );

Table created.
SQL> ALTER TABLE employees
2 ADD CONSTRAINT uc_emp_dept_id UNIQUE (emp_dept_id);

Table altered

SQL> insert into employees values (100, 'John Doe', 50000.00, 100);

1 row created.

SQL> insert into employees values (101, 'Stevenson', 45000.00, 102);

1 row created.

SQL> insert into employees values (102, 'Robinson', 65000.00, 105);


1 row created.
SQL> select * from employees;

EMP_ID EMP_NAME EMP_SALARY EMP_DEPT_ID


---------- ---------------- ---------------- --------------
100 John Doe 50000.00 100
101 Stevenson 45000.00 102
102 Robinson 65000.00 105

SQL> update employees set emp_salary=60000.00 where emp_name='John


Doe';
1 row updated.

EMP_ID EMP_NAME EMP_SALARY EMP_DEPT_ID


---------- ---------------- ---------------- --------------
100 John Doe 60000.00 100
101 Stevenson 45000.00 102
102 Robinson 65000.00 105

Result:
Ex No. 2 Foreign Key Constraints and Referential Integrity

AIM: To create tables with foreign key constraints and referential integrity

Syntax:
CREATE TABLE table_name (
column1 datatype PRIMARY KEY,
column2 datatype,
...
);

CREATE TABLE table_name1 (


column1 datatype PRIMARY KEY,
column2 datatype,
...
FOREIGN KEY (coulmn1) REFERNCES table_name(column1)
);
Description:
1) In the first syntax, a parent table is created with first column as primary
key which means all the values and unique(distinct) and the other
columns which their respective datatypes.

2) The second syntax creates a child table with columns and the column
that matches column can refer same attribute present in the parent table
SQL Execution Queries

CREATE TABLE customers (


customer_id INT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100)
);

O/P: Table created

CREATE TABLE orders (


order_id INT PRIMARY KEY,
customer_id INT,
order_date DATE,
total_amount DECIMAL(10,2),
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);

O/P: Table created


Ex No 3 Where Clause and Aggregate Functions

AIM: To query the database tables using different where clauses and also
implement aggregate functions.

Syntax
CREATE table table_name(
column1 datatype primary key,
.
.
columnN datatypeN
);

Insert into table_name values (value1, value2,…);

Select * from <table_name> where <condition>;


Select col1, col2 from <table_name> where <condition>;

Select <column_name>, count(*) as <alternate_name> from books group by


<column_name>;

Description

The create table will create tables with primary key in one and foreign key to
refer matching attribute in the second table.
Insert command is used to insert a record into the database table. If syntax is
correct then it will return 1 row created.

Select command can be used to display entire data entered or display certain
columns based on a condition with help of where clause. It can also be used
with aggregate functions.

Where clause is used to hold a condition for displaying or updating data.

Count(*)- It is used to count the records in the table.

Group By- It can be used after aggregate function to print number of records
grouped by specific values in an attribute.
(Query execution)

SQL> CREATE TABLE books (

2 book_id INT PRIMARY KEY,

3 title VARCHAR(255) NOT NULL,

4 author VARCHAR(100) NOT NULL,

5 genre VARCHAR(50),

6 publish_year INT

7 );

Table created.

SQL> insert into books values (1, 'To Kill a Mockingbird', 'Harper Lee', 'Fiction',
1960);

1 row created.

SQL> insert into books values (2, ‘1984’, 'George Orwell', 'Science Fiction',
1949);

1 row created.
SQL> insert into books values (3, 'Pride and Prejudice', 'Jane Austen',
'Romance', 1813);

1 row created.

SQL> insert into books values (4, 'The Catcher in the Rye', 'J.D. Salinger',
'Fiction', 1951);

1 row created.

SQL> select * from books;

book_id title author genre published_year


---------- --------------------------- --------------- -------- ---------------------
1 To Kill a Mockingbird Harper Lee Fiction 1960
2 1984 George Orwell Science Fiction 1949
3 Pride and Prejudice Jane Austen Romance 1813
4 The Catcher in the Rye J.D. Salinger Fiction 1951

select book_id, title from books where genre='Fiction';

book_id title
----------- ------------------------
1. To Kill a Mockingbird
4 The Catcher in the Rye

select * from books where publish_year>1900;

book_id title author genre published_year


---------- --------------------------- --------------- -------- ---------------------
1 To Kill a Mockingbird Harper Lee Fiction 1960
2 1984 George Orwell Science Fiction 1949
4 The Catcher in the Rye J.D. Salinger Fiction 1951
SQL> SELECT genre, COUNT(*) AS genre_count

2 FROM books

3 GROUP BY genre;

GENRE GENRE_COUNT

---------------------------------------------- -----------

Fiction 2

Science Fiction 1
Romance 1
Ex No. 4 Subqueries and Joins

AIM: To query the database tables using subqueries and join


operations

Syntax

INSERT INTO table_name [ (column1, column2,…columnN) ];

SELECT column_name2, column_name3


FROM table1
WHERE column_name1 OPERATOR
(SELECT column_name1
FROM table1
[WHERE]);

SELECT columns
FROM table1
JOIN table2
ON table1.column = table2.column;
Description

Insert Statement is used to insert 1 row at a time in a database table.


The output will be 1 row created.

The select subquery selects the columns specified based on the


condition of select statement inside within with contains a condition.

There are a few rules that subqueries must follow:

1. Subqueries must be enclosed within parentheses


2. A subquery can have only one column in the SELECT clause,
unless multiple columns are in the main query for the subquery to
compare its selected columns

SQL JOINS are used to retrieve data from multiple tables. A SQL JOIN
is performed whenever two or more tables are joined in a SQL
statement. In JOIN ON, JOIN is a clause used to combine rows from two
or more tables based on a related column between them. The ON
keyword is used to specify the condition for joining tables.

(Query execution)
SQL> CREATE TABLE empls(

2 emp_id INT PRIMARY KEY,

3 emp_name VARCHAR(100),

4 emp_salary DECIMAL(10, 2),

5 emp_department VARCHAR(100)

6 );
Table created.

SQL> CREATE TABLE departments (

2 dept_id INT PRIMARY KEY,

3 dept_name VARCHAR(100),

4 location VARCHAR(100)

5 );
Table created.

SQL> insert into empls values (1, 'John Doe', 30000.00, 'IT');

1 row created.

SQL> insert into empls values (2, 'Jane Smith', 50000.00, 'Finance');

1 row created.

SQL> INSERT INTO departments values (1, 'IT', 'New York');


1 row created.

SQL> INSERT INTO departments values (2, 'Finance', 'Boston');

1 row created.

SQL> SELECT emp_name, emp_salary from empls where emp_salary


> (SELECT AVG(emp_salary) FROM empls);

EMP_NAME EMP_SALARY
----------------- --------------------
Jane Smith 50000

SQL> SELECT emp_name, emp_salary, dept_name from empls join


departments on empls.emp_department = departments.dept_name;

EMP_NAME EMP_SALARY DEPT_NAME


----------------- -------------------- -------------------
John Doe 30000 IT
Jane Smith 50000 Finance
Ex No. 5 Natural, Equi and Outer joins.

AIM: To query database tables using natural, equi and outer joins.

Syntax:

SELECT column_list

FROM table1
NATURAL JOIN table2;

SELECT column_list

FROM table1
JOIN table2 ON table1.column_name = table2.column_name;

SELECT column_list

FROM table1
LEFT JOIN table2 ON table1.column_name = table2.column_name;

Description
In natural join syntax,
SELECT column_list: Specifies the columns you want to retrieve
from the resulting joined table.
table1 and table2: Are the tables you want to join.
NATURAL JOIN: Specifies that you want to perform a natural
join, which automatically matches columns with the same name
in both tables.

In equi join syntax, we join the column data(displayed) on both


the tables(excluding the common column) on the basis of value
match in the tables having common column name.

In left outer join syntax,


SELECT column_list: Specifies the columns you want to retrieve from
the resulting joined table.
table1 and table2: Are the tables you want to join.
LEFT JOIN: Specifies that you want to perform a left outer join. This
means all rows from the left table (table1) will be included in the result,
even if there are no matching rows in the right table (table2). If there is
no match, NULL values will be included for columns from the right table.
ON: Specifies the condition for the join. It determines how rows from
table1 and table2 are matched.

(Query execution)

CREATE TABLE customers (

2 customer_id INT PRIMARY KEY,


3 customer_name VARCHAR(100),

4 email VARCHAR(100),

5 phone_number VARCHAR(20)

6 );

Table created.

CREATE TABLE reservations (

2 reservation_id INT PRIMARY KEY,

3 customer_id INT,

4 reservation_date DATE,

5 room_number VARCHAR(10),

6 CHECK (customer_id > 0), -- Ensures customer_id is


valid

7 FOREIGN KEY (customer_id) REFERENCES


customers(customer_id)

8 );
Table created.

SQL> INSERT INTO customers values (1, 'John Doe',


'[email protected]', '123-456-7890');

1 row created.

SQL> INSERT INTO customers values (2, 'Jane Smith',


'[email protected]', '987-654-3210');
1 row created.

SQL> INSERT INTO customers values (3, 'Michael Johnson',


'[email protected]', '555-123-4567');

1 row created.

INSERT INTO reservations VALUES (1, 1, '2024-06-25', '101');


1 row created

INSERT INTO reservations VALUES (2, 2, '2024-07-05', '202');


1 row created

INSERT INTO reservations VALUES (3, 1, '2024-08-15', '103');


1 row created

INSERT INTO reservations VALUES (4, 3, '2024-09-01', '105');


1 row created

INSERT INTO reservations VALUES (5, 2, '2024-09-15', '201');


1 row created

Select * from customers;

CUSTOMER_ID CUSTOMER_NAME EMAIL PHONE_NUMBER


--------------------- ---------------------------- --------- -------------------------
1 John Doe [email protected] 123-456-7890
2 Jane Smith [email protected] 987-654-3210
3 Michael Johnson [email protected] 555-123-4567

Select * from reservations


reservation_id customer_id reservation_date room_number
------------------ ----------------- --------------------- -------------------
1 1 2024-06-25 101
2 2 2024-07-05 202
3 1 2024-08-15 103
4 3 2024-09-01 105
5 2 2024-09-15 201

SELECT * FROM customers NATURAL JOIN reservations;


customer customer_ phone_nu reservatio reservation room_nu
email
_id name mber n_id _date mber
[email protected] 123-456-
1 John Doe 1 2024-06-25 101
m 7890
[email protected] 123-456-
1 John Doe 3 2024-08-15 103
m 7890
[email protected] 987-654-
2 Jane Smith 2 2024-07-05 202
m 3210
[email protected] 987-654-
2 Jane Smith 5 2024-09-15 201
m 3210
Michael michael.johnson@e 555-123-
3 4 2024-09-01 105
Johnson mail.com 4567

SELECT *

FROM customers c

JOIN reservations r ON c.customer_id = r.customer_id;


custome customer phone_nu reservati reservatio room_nu
email
r_id _name mber on_id n_date mber
[email protected] 123-456-
1 John Doe 1 2024-06-25 101
om 7890
[email protected] 123-456-
1 John Doe 3 2024-08-15 103
om 7890
jane.smith@email. 987-654-
2 Jane Smith 2 2024-07-05 202
com 3210
jane.smith@email. 987-654-
2 Jane Smith 5 2024-09-15 201
com 3210
Michael michael.johnson@ 555-123-
3 4 2024-09-01 105
Johnson email.com 4567
SELECT

FROM customers c

LEFT OUTER JOIN reservations r ON c.customer_id = r.customer_id;


custome customer phone_nu reservati reservatio room_nu
email
r_id _name mber on_id n_date mber
[email protected] 123-456-
1 John Doe 1 2024-06-25 101
om 7890
[email protected] 123-456-
1 John Doe 3 2024-08-15 103
om 7890
jane.smith@email. 987-654-
2 Jane Smith 2 2024-07-05 202
com 3210
jane.smith@email. 987-654-
2 Jane Smith 5 2024-09-15 201
com 3210
Michael michael.johnson@ 555-123-
3 4 2024-09-01 105
Johnson email.com 4567
Ex No 6 User defined functions and stored procedures in SQL.

AIM: To create user defined functions and procedure and execute them in SQL.

Syntax:
CREATE FUNCTION function_name (
parameter1 datatype1,
parameter2 datatype2,
...
)
RETURNS return_datatype
AS
BEGIN
-- Function body with SQL statements
DECLARE local_variable1 datatype;
DECLARE local_variable2 datatype;
-- Initialization or other processing

-- SQL statements

-- RETURN statement
RETURN expression; -- expression can be a variable, calculation, query
result, etc.
END;

CREATE PROCEDURE procedure_name


[parameter1 datatype1 [ = default_value1 ]]
[, parameter2 datatype2 [ = default_value2 ]]
[...]
AS
BEGIN
-- Procedure body with SQL statements
END;

Description:
In user defined function syntax,

CREATE FUNCTION: Begins the function creation statement.

function_name: Name of the function you are creating.

Parameters: Optional list of parameters that the function accepts. Each


parameter consists of a name and a data type (datatype). Parameters are
enclosed in parentheses ().

RETURNS return_datatype: Specifies the data type that the function returns.
return_datatype can be any valid data type supported by your database system.

AS: Indicates the beginning of the function body.

BEGIN ... END;: Encloses the statements that define the function's behavior.

Local Variables: Optional local variables (DECLARE local_variable datatype;) that the
function can use for temporary storage or calculations.

SQL Statements: Actual SQL statements that perform the desired operations
within the function.

RETURN statement: Specifies what value or result the function should return. This
can be a variable, an expression, a query result, etc.
In procedure syntax,

CREATE PROCEDURE: Begins the stored procedure creation


statement.

procedure_name: Name of the procedure you are creating.

Parameters: Optional list of parameters that the procedure can


accept. Each parameter consists of a name, a data type (datatype),
and optionally a default value (default_value). Parameters are
enclosed in parentheses ().

AS: Indicates the beginning of the procedure body.

BEGIN ... END;: Encloses the statements that define the procedure's
behavior.

SQL Statements: Actual SQL statements that perform the desired


operations within the procedure.

-- Create the function


CREATE FUNCTION dbo.CalculateSquare(@num INT)

RETURNS INT

AS

BEGIN

DECLARE @square INT;

SET @square = @num * @num;

RETURN @square;

END;

GO

-- Example of using the function

DECLARE @input INT = 5;

DECLARE @result INT;

-- Call the function to compute the square

SET @result = dbo.CalculateSquare(@input);

-- Print the result (for illustration)


PRINT 'The square of ' + CAST(@input AS VARCHAR(10)) + '
is ' + CAST(@result AS VARCHAR(10));
O/P: The square of 5 is 25

CREATE PROCEDURE InsertEmployee


@EmpName NVARCHAR(50),

@EmpDept NVARCHAR(50),

@EmpSalary DECIMAL(10, 2)

AS

BEGIN

INSERT INTO Employees (EmpName, EmpDept,


EmpSalary)

VALUES (@EmpName, @EmpDept, @EmpSalary);

-- Print message indicating successful insertion

PRINT 'Employee ' + @EmpName + ' added successfully.';


END;

O/P:Employee John Doe added successfully.

Ex No. 7 DCL and TCL Commands

AIM: To query database table using DCL and TCL Commands.

Syntax

(DCL commands)
GRANT {privileges} ON {object} TO {user | role};

REVOKE {privileges} ON {object} FROM {user | role};

(TCL commands)

COMMIT;

ROLLBACK;

Description

GRANT command is used to grant specific operations to a particular


user.
REVOKE command is used to revoke an operation on the database
table

COMMIT command is used to permanently save the changes


made during a transaction to the database.

ROLLBACK command reverses the effects of the UPDATE


statement, restoring the Salary values to what they were before
the transaction began.

(SQL execution)
-- Create a table

CREATE TABLE employees (

emp_id INT PRIMARY KEY,

emp_name VARCHAR(50),

emp_salary DECIMAL(10, 2)

);

Table created

-- Insert some rows

INSERT INTO employees (emp_id, emp_name, emp_salary) VALUES


(1, 'Alice', 50000.00);

1 row created

INSERT INTO employees (emp_id, emp_name, emp_salary) (2, 'Bob',


60000.00);

1 row created
INSERT INTO employees (emp_id, emp_name, emp_salary) (3,
'Charlie', 75000.00);
1 row created

-- Grant SELECT privilege to a user


GRANT SELECT ON employees TO user1;
Grant succeeded.
-- Revoke INSERT privilege from a user
REVOKE INSERT ON employees FROM user2;
Revoke succeeded.
-- Start a transaction
START TRANSACTION;
-- Update salary for Alice
UPDATE employees SET emp_salary = 55000.00 WHERE emp_name = 'Alice';
1 row updated
-- Check the updated salary
SELECT * FROM employees WHERE emp_name = 'Alice';

emp_id emp_name emp_salary


---------- --------------- ---------------
1 Alice 55000.00
2 Bob 60000.00
3 Charlie 75000.00

COMMIT;
Commit complete

ROLLBACK;
Rollback complete

Ex No 8 SQL Triggers

AIM: To write SQL triggers for insert, delete and update

Syntax:
CREATE TRIGGER trigger_name
AFTER INSERT ON table_name
FOR EACH ROW
BEGIN
-- Trigger action statements
END;

CREATE TRIGGER trigger_name


AFTER UPDATE ON table_name
FOR EACH ROW
BEGIN
-- Trigger action statements
END;

CREATE TRIGGER trigger_name


AFTER DELETE ON table_name
FOR EACH ROW
BEGIN
-- Trigger action statements
END;

Description:
Insert Trigger
trigger_name: Specify a name for your trigger.
AFTER INSERT ON table_name: Indicates that the trigger fires after
an insert operation on table_name.
FOR EACH ROW: Specifies that the trigger will execute once for
each row affected by the insert operation.
BEGIN ... END: Encloses the trigger action statements.
Update Trigger
AFTER UPDATE ON table_name: Indicates that the trigger fires after an
update operation on table_name.

Delete Trigger
AFTER DELETE ON table_name: Indicates that the trigger fires after a
delete operation on table_name.

create table sailor(sid number(10)primary key,name varchar(20),dob


varchar(20),gender varchar(10));
Table created
CREATE TABLE sailor_audit_log (
log_id NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY,
operation_type VARCHAR2(10),
operation_time TIMESTAMP,
sid NUMBER(10),
name VARCHAR2(20),
dob VARCHAR2(20),
gender VARCHAR2(10),
PRIMARY KEY (log_id)
);
Table created

CREATE TRIGGER trg_insert_sailor


AFTER INSERT ON sailor
FOR EACH ROW
BEGIN
-- Insert into audit log
INSERT INTO sailor_audit_log (sailor_id, action, action_time)
VALUES (NEW.sailor_id, 'INSERT', NOW());

-- Update sailor_status table based on the insert


UPDATE sailor_status
SET status = 'Active' -- Assuming this is how you determine status
WHERE sailor_id = NEW.sailor_id;

-- You can perform other actions here if needed


-- Example: Log the update action
INSERT INTO sailor_audit_log (sailor_id, action, action_time)
VALUES (NEW.sailor_id, 'UPDATE_STATUS', NOW());

-- Example: Send a notification or perform additional updates

-- Example: Calculate and update related metrics

END;
/
Trigger created

CREATE OR REPLACE TRIGGER trg_before_delete_sailor


BEFORE DELETE ON sailor
FOR EACH ROW
BEGIN
-- Example: Prevent deletion of sailors younger than 18
IF MONTHS_BETWEEN(SYSDATE, TO_DATE(:OLD.dob, 'DD-MM-YYYY')) <
216 THEN
RAISE_APPLICATION_ERROR(-20002, 'Cannot delete sailor under 18 years
old.');
END IF;
-- Additional logic or validation can be added here
END;
/
Trigger created.
CREATE OR REPLACE TRIGGER sailor_update_trigger
BEFORE UPDATE ON sailor
FOR EACH ROW
BEGIN
-- Check if the name is being updated to a new value
IF :OLD.name <> :NEW.name THEN
-- Perform actions when the name is updated
DBMS_OUTPUT.PUT_LINE('Name is being updated from ' || :OLD.name
|| ' to ' || :NEW.name);
-- Additional actions can be added here
END IF;

-- Check if the date of birth (dob) is being updated


IF :OLD.dob <> :NEW.dob THEN
-- Perform actions when dob is updated
DBMS_OUTPUT.PUT_LINE('Date of Birth is being updated from '
|| :OLD.dob || ' to ' || :NEW.dob);
-- Additional actions can be added here
END IF;

-- Check if the gender is being updated


IF :OLD.gender <> :NEW.gender THEN
-- Perform actions when gender is updated
DBMS_OUTPUT.PUT_LINE('Gender is being updated from '
|| :OLD.gender || ' to ' || :NEW.gender);
-- Additional actions can be added here
END IF;
-- Add more IF conditions and actions as needed for other columns

END;
/

Ex No 9 VIEWS AND INDEXES

AIM: To create view and indexes for the database tables

Syntax
CREATE TABLE <table_name>(
col_name1 datatype PRIMARY KEY,
col_name2 datatype <constraint>,
col_name3 datatype UNIQUE,
.
.
);
CREATE VIEW as view_name as select col1, col2… from table_name;

CREATE INDEX index_name


ON table_name (column1, column2, ...);

Description:
In create table syntax, 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.

CREATE VIEW will create a view of some name for select operations
and we can display the content present in that view
CREATE INDEX syntax has,
 CREATE INDEX: Begins the statement to create an index.
 index_name: Specifies the name of the index you are creating.
Choose a descriptive name that indicates the purpose of the index.
 ON table_name: Specifies the table on which the index is being
created.
 (column1, column2, ...): Specifies one or more columns on which
the index is based. These columns can be from the same table and are
often chosen based on the columns frequently used in WHERE, JOIN, or
ORDER BY clauses of queries.

(SQL Execution Queries)

CREATE TABLE customers (


customer_id INT PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
email VARCHAR(100) UNIQUE,
phone VARCHAR(20),
);
Table created

INSERT INTO customers (first_name, last_name, email, phone) VALUES ('John',


'Doe', '[email protected]', '123-456-7890');
1 row created
INSERT INTO customers (first_name, last_name, email, phone) VALUES ('Jane',
'Smith', '[email protected]', '987-654-3210');
1 row created

CREATE VIEW cust as select * from customers;


View created

Select * from cust;

FIRST_NAME LAST_NAME EMAIL PHONE


John Doe john.doe@example 123-456-7890
Jane Smith jane.smith@example 987-654-3210

CREATE INDEX idx_customer_fn on customers(first_name);


Index created
Ex No 10 XML Schema Creation and Validation

AIM: To create an XML Schema by registering it and then checking if it is valid.

Syntax

BEGIN
DBMS_XMLSCHEMA.registerSchema(
schemaURL => 'http://example.com/schema.xsd',
schemaDoc => 'schema_content',
local => TRUE,
genTypes => TRUE,
genTables => TRUE,
force => FALSE,
enableHierarchy => DBMS_XMLSCHEMA.ENABLE_ALL_HIERARCHY);
END;

l_xmltype.schemavalidate;

select schema_url from user_xml_schemas;

Description
In Oracle Database, this registration procedure registers an XML
schema located at http://example.com/schema.xsd. The schemaDoc
parameter contains the actual schema content as a string.
In validate syntax,
l_xmltype: This is an XMLType variable or column containing the XML
data you want to validate.
schema_url: This parameter specifies the URL of the XML schema
against which you want to validate the XML data stored in l_xmltype.

The select schema_url command will display the url of the current XML
Schema created.

(RegXMLSChema.sql)
DECLARE
l_schema CLOB;
BEGIN

l_schema := '<?xml version="1.0" encoding="UTF-8" ?>


<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

<!-- definition of simple elements -->


<xs:element name="orderperson" type="xs:string"/>
<xs:element name="name" type="xs:string"/>
<xs:element name="address" type="xs:string"/>
<xs:element name="city" type="xs:string"/>
<xs:element name="country" type="xs:string"/>
<xs:element name="title" type="xs:string"/>
<xs:element name="note" type="xs:string"/>
<xs:element name="quantity" type="xs:positiveInteger"/>
<xs:element name="price" type="xs:decimal"/>

<!-- definition of attributes -->


<xs:attribute name="orderid" type="xs:string"/>

<!-- definition of complex elements -->


<xs:element name="shipto">
<xs:complexType>
<xs:sequence>
<xs:element ref="name"/>
<xs:element ref="address"/>
<xs:element ref="city"/>
<xs:element ref="country"/>
</xs:sequence>
</xs:complexType>
</xs:element>

<xs:element name="item">
<xs:complexType>
<xs:sequence>
<xs:element ref="title"/>
<xs:element ref="note" minOccurs="0"/>
<xs:element ref="quantity"/>
<xs:element ref="price"/>
</xs:sequence>
</xs:complexType>
</xs:element>

<xs:element name="shiporder">
<xs:complexType>
<xs:sequence>
<xs:element ref="orderperson"/>
<xs:element ref="shipto"/>
<xs:element ref="item" maxOccurs="unbounded"/>
</xs:sequence>
<xs:attribute ref="orderid" use="required"/>
</xs:complexType>
</xs:element>

</xs:schema>';
DBMS_XMLSCHEMA.registerSchema(schemaurl =>
'my_schema.xsd',
schemadoc => l_schema,
local => TRUE,
gentypes => FALSE,
gentables => FALSE,
enablehierarchy =>
DBMS_XMLSCHEMA.enable_hierarchy_none);

END;
/

(XMLSchemaValidation.sql)
DECLARE
l_xml CLOB;
l_xmltype XMLTYPE;
BEGIN

l_xml := '<?xml version="1.0" encoding="UTF-8"?>


<shiporder orderid="889923">
<orderperson>John Smith</orderperson>
<shipto>
<name>Ola Nordmann</name>
<address>Langgt 23</address>
<city>4000 Stavanger</city>
<country>Norway</country>
</shipto>
<item>
<title>Empire Burlesque</title>
<note>Special Edition</note>
<quantity>1</quantity>
<price>10.90</price>
</item>
<item>
<title>Hide your heart</title>
<quantity>1</quantity>
<price>9.90</price>
</item>
</shiporder>';

l_xmltype := XMLTYPE(l_xml, 'my_schema.xsd');


l_xmltype.schemavalidate;

END;
/
(Oracle SQL Plus)
@"C:\Users\pravi\OneDrive\Documents\RegSQLSchema.sql"

PL/SQL procedure successfully completed.

select schema_url from user_xml_schemas;

SCHEMA_URL
--------------------------------------------------------------------------------
my_schema.xsd

@"C:\Users\pravi\OneDrive\Documents\XMLSchemaValidation.sql"

PL/SQL procedure successfully completed.

Ex No 11 NOSQL database tools

AIM: To create document, column and graph based data using NOSQL
database tools.

Syntax with Description;


mongo //MongoDB connect
// Insert Document:
db.collection_name.insertOne({
key1: value1,
key2: value2,
// More key-value pairs
});
//Query
db.collection_name.find({ key: value });

cqlsh //Cassandra connect


// Create Keyspace:
CREATE KEYSPACE keyspace_name WITH replication = {'class':
'SimpleStrategy', 'replication_factor': 1};
USE keyspace_name; // To use the keyspace
//Create the table
CREATE TABLE table_name (
key1 data_type PRIMARY KEY,
key2 data_type,
// More columns
);

//Inserts one row


INSERT INTO table_name (key1, key2, ...) VALUES (value1, value2, ...);

SELECT * FROM table_name WHERE key1 = value;//Selects data


based on the value

:server connect //Neo4j connection


CREATE (:Label {key: value}); // Create Node

// Creating Relationship:

MATCH (node1:Label1), (node2:Label2)


WHERE node1.key = value1 AND node2.key = value2
CREATE (node1)-[:RELATIONSHIP]->(node2);

//Querying Nodes and Relationships:


MATCH (node1)-[:RELATIONSHIP]->(node2)
WHERE node1.key = value
RETURN node1, node2;

MongoDB utilizes a document-based model with collections


and documents.
Apache Cassandra uses a column-family model with
keyspaces, tables, rows, and columns.
Neo4j employs a graph-based model with nodes,
relationships, and properties.

MongoDB
// Inserting document-based data into MongoDB
db.customers.insertOne({
_id: ObjectId(),
name: "John Doe",
age: 30,
email: "[email protected]"
});

// Querying document-based data from MongoDB


db.customers.find({ name: "John Doe" });
O/P:
Insertion
{
"_id" : ObjectId("..."),
"name" : "John Doe",
"age" : 30,
"email" : "[email protected]"
}
Query
{ "_id" : ObjectId("..."), "name" : "John Doe", "age" : 30, "email" :
"[email protected]" }

Cassandra
// Creating a column-based table in Cassandra
CREATE KEYSPACE IF NOT EXISTS my_keyspace WITH replication = {'class':
'SimpleStrategy', 'replication_factor': 1};

USE my_keyspace;

CREATE TABLE IF NOT EXISTS users (


user_id UUID PRIMARY KEY,
name TEXT,
age INT,
email TEXT
);

// Inserting data into the column-based table


INSERT INTO users (user_id, name, age, email) VALUES (uuid(), 'Alice', 28,
'[email protected]');

// Querying data from the column-based table


SELECT * FROM users WHERE name = 'Alice';
O/P:
user_id | age | email | name
--------------------------------------+-----+--------------------+-------
41f9c3ca-b6f2-4c6e-9e3c-6a4d601fb4d8 | 28 | [email protected] | Alice

Neo4j
// Creating nodes and relationships in Neo4j
CREATE (:Person {name: 'Alice', age: 30})
CREATE (:Person {name: 'Bob', age: 25});

MATCH (alice:Person), (bob:Person)


WHERE alice.name = 'Alice' AND bob.name = 'Bob'
CREATE (alice)-[:FRIENDS]->(bob);

// Querying data from Neo4j


MATCH (person:Person)-[:FRIENDS]->(friend)
WHERE person.name = 'Alice'
RETURN person, friend;
O/P: person | friend
---------------------------|---------------------------
(:Person {name: 'Alice'}) | (:Person {name: 'Bob'})

Ex No 12 GUI database application

AIM: Develop a simple GUI based database application and incorporate all the
abovementioned features

Syntax & Description


javafx.application; //Sets up an application
javafx.scene; //It will create the appearance of the application
java.sql.Connection; //To connect java to the Database.
java.sql.DriverManager; //Makes use of JDBC driver to connect to database

private void <class_name> //To create a private class in java


e.printStackTrace();: This line is executed when an exception is caught. It prints the
stack trace of the exception to the standard error stream (System.err). The stack trace
includes information about the exception's type, message, and the sequence of
method calls that led to the exception.

<class_name>.setTitle(); //Sets title of application


<class_name>.setMessage(); //Display a message after a particular task.

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class DatabaseApplication extends Application {

// JDBC URL, username and password of MySQL server


private static final String JDBC_URL = "jdbc:oracle:thin:@localhost:1521:xe";
private static final String JDBC_USER = "your_username";
private static final String JDBC_PASSWORD = "your_password";

private Connection conn;

@Override
public void start(Stage primaryStage) {
try {
conn = DriverManager.getConnection(JDBC_URL, JDBC_USER,
JDBC_PASSWORD);
} catch (SQLException e) {
e.printStackTrace();
showAlert("Database Connection Error", "Could not connect to the
database.");
return;
}

GridPane grid = new GridPane();


grid.setPadding(new Insets(10));
grid.setHgap(5);
grid.setVgap(5);

// GUI components
TextField nameField = new TextField();
TextField ageField = new TextField();
Button insertButton = new Button("Insert");

grid.add(new Label("Name:"), 0, 0);


grid.add(nameField, 1, 0);
grid.add(new Label("Age:"), 0, 1);
grid.add(ageField, 1, 1);
grid.add(insertButton, 0, 2, 2, 1);

insertButton.setOnAction(event -> {
String name = nameField.getText();
String ageStr = ageField.getText();

if (name.isEmpty() || ageStr.isEmpty()) {
showAlert("Input Error", "Please enter both name and age.");
return;
}

try {
int age = Integer.parseInt(ageStr);
String sql = "INSERT INTO your_table_name (name, age) VALUES
(?, ?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, name);
statement.setInt(2, age);
int rowsInserted = statement.executeUpdate();

if (rowsInserted > 0) {
showAlert("Success", "Record inserted successfully!");
nameField.clear();
ageField.clear();
} else {
showAlert("Error", "Failed to insert record.");
}
} catch (NumberFormatException e) {
showAlert("Input Error", "Age must be a valid number.");
} catch (SQLException e) {
e.printStackTrace();
showAlert("Database Error", "Failed to insert record: " +
e.getMessage());
}
});

Scene scene = new Scene(grid, 300, 150);


primaryStage.setScene(scene);
primaryStage.setTitle("Database Application");
primaryStage.show();
}
@Override
public void stop() {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
// Handle error closing connection
}
}

private void showAlert(String title, String message) {


Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle(title);
alert.setHeaderText(null);
alert.setContentText(message);
alert.showAndWait();
}

public static void main(String[] args) {


launch(args);
}
}

Output:
Database Application

Input Error Please enter name and age

name: Ramesh

age: 25

Insert

//On clicking insert


Record inserted successfully!

name:
age:

Insert

You might also like