Unit III Fis

Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

Data Definition and Querying

Data Definition Language (DDL) is a set of commands used to define and manage the structure
of a database. DDL commands are used to create, modify, and delete database objects such as
tables, indexes, and views. Some common DDL commands include CREATE, ALTER, and DROP.

Data Query Language (DQL) is a set of commands used to retrieve data from a database. DQL
commands are used to search, filter, and sort data in a database. Some common DQL commands
include SELECT, FROM, and WHERE.

When working with databases, DDL commands are used to create and modify the database
schema, while DQL commands are used to retrieve and manipulate data within the database. It's
important to understand both DDL and DQL commands in order to effectively manage and use a
database.

Basic DDL
Here are some basic DDL (Data Definition Language) commands:

1. CREATE: This command is used to create a new database, table, index, or view.

Example: CREATE DATABASE dbname;

2. ALTER: This command is used to modify the structure of an existing table.

Example: ALTER TABLE tablename ADD COLUMN columnname datatype;

3. DROP: This command is used to delete a database, table, index, or view.

Example: DROP DATABASE dbname;

4. TRUNCATE: This command is used to delete all the data in a table, but it keeps the table
structure intact.

Example: TRUNCATE TABLE tablename;

5. COMMENT: This command is used to add comments to the database objects, such as
tables, columns, views, etc.

Example: COMMENT ON COLUMN tablename.columnname IS 'description';

6. RENAME: This command is used to rename an existing database object, such as a table,
column, or view.

Example: ALTER TABLE oldname RENAME TO newname;

These are just a few examples of the basic DDL commands that can be used to define and
manage the structure of a database.
Introduction to SQL
SQL (Structured Query Language) is a programming language used to manage and manipulate
relational databases. It is used to create, modify, and query databases, and is widely used in both
industry and academia. SQL is a standard language and is supported by most relational database
management systems, including Oracle, MySQL, Microsoft SQL Server, and PostgreSQL.

SQL consists of two types of commands: Data Definition Language (DDL) and Data Manipulation
Language (DML). DDL commands are used to create and modify the structure of a database,
including creating tables, defining relationships between tables, and creating indexes. DML
commands are used to insert, update, delete, and retrieve data from a database.

SQL queries are written using a syntax that is similar to English. The basic syntax for a SELECT
statement, which is used to retrieve data from a database, is as follows:

SELECT column1, column2, ...

FROM table_name

WHERE condition;

This statement selects data from one or more columns in a table, based on a specified condition.
The result of the query is a set of rows that match the specified condition.

SQL also includes a number of built-in functions that can be used to manipulate data, such as
calculating averages, finding maximum or minimum values, and converting data types.

Overall, SQL is a powerful tool for managing and analyzing data in a relational database, and is
an essential skill for anyone working with databases.

Data Constraints
Data constraints are rules that are enforced on the data stored in a database to ensure its
accuracy, consistency, and integrity. Constraints are used to prevent invalid data from being
inserted or updated in a database, and to maintain the relationships between tables. Here are
some common data constraints used in databases:

1. Primary Key Constraint: This constraint is used to uniquely identify a row in a table. It
ensures that each row has a unique value for the specified column or set of columns. The
primary key constraint is used to enforce referential integrity between tables.
2. Foreign Key Constraint: This constraint is used to ensure that the values in a column or
set of columns in one table correspond to the values in a primary key column in another
table. It is used to enforce referential integrity between tables.
3. NOT NULL Constraint: This constraint is used to ensure that a column cannot have null
values. It is used to enforce data integrity by requiring that a value must be provided for a
column.
4. CHECK Constraint: This constraint is used to ensure that the values in a column or set of
columns meet a specified condition. It is used to enforce data integrity by requiring that
the data meet certain criteria.
5. UNIQUE Constraint: This constraint is used to ensure that the values in a column or set of
columns are unique. It is used to enforce data integrity by preventing duplicate values
from being inserted in a table.
6. Default Constraint: This constraint is used to provide a default value for a column if no
value is specified during an insert operation.

Data constraints help to ensure the accuracy and consistency of data in a database. They are an
important tool for maintaining data integrity and for enforcing relationships between tables.

Advanced SQL
Advanced SQL is a set of techniques and concepts used to manipulate data in a database beyond
the basic SELECT, INSERT, UPDATE, and DELETE statements. Here are some advanced SQL
techniques:

1. Subqueries: A subquery is a query nested inside another query. It is used to retrieve data
that will be used in the main query. Subqueries can be used in the WHERE, HAVING, and
FROM clauses.

Example:

SELECT product_name, product_price

FROM products

WHERE product_id IN (SELECT product_id FROM orders WHERE order_date = '2023-04-08');

2. Joins: Joins are used to combine data from two or more tables based on a
common column. There are several types of joins, including INNER JOIN, LEFT
JOIN, RIGHT JOIN, and FULL OUTER JOIN.

Example:

SELECT orders.order_id, customers.customer_name

FROM orders

INNER JOIN customers ON orders.customer_id = customers.customer_id;

3. Views: A view is a virtual table that is based on the result of a SELECT


statement. Views are used to simplify complex queries and to provide a
customized view of the data to different users.

Example:

CREATE VIEW customer_orders AS

SELECT customers.customer_name, orders.order_id, orders.order_date

FROM customers

INNER JOIN orders ON customers.customer_id = orders.customer_id;


4. Stored Procedures: A stored procedure is a set of SQL statements that are
stored in a database and can be executed on demand. Stored procedures are
used to encapsulate complex business logic and to improve performance by
reducing network traffic.

Example:

CREATE PROCEDURE get_orders_by_customer(IN customer_id INT)

BEGIN

SELECT order_id, order_date, order_amount

FROM orders

WHERE customer_id = customer_id;

END;

5. Transactions: A transaction is a series of SQL statements that are executed as a


single unit of work. Transactions are used to ensure data integrity by enforcing
the ACID properties: Atomicity, Consistency, Isolation, and Durability.

Example:

BEGIN TRANSACTION;

UPDATE accounts SET balance = balance - 100 WHERE account_id = 1;

UPDATE accounts SET balance = balance + 100 WHERE account_id = 2;

COMMIT TRANSACTION;

These are just a few examples of advanced SQL techniques. Advanced SQL is a powerful tool for
manipulating and analyzing data in a database, and is an essential skill for database
professionals.

Views
In SQL, a view is a virtual table that is based on the result of a SELECT statement. Views are used
to simplify complex queries and to provide a customized view of the data to different users. Here
are some key features of views:

1. A view is defined by a SELECT statement. The result of the SELECT statement is stored as a
virtual table in the database.
2. A view is created using the CREATE VIEW statement. The syntax is as follows:
CREATE VIEW view_name AS

SELECT column1, column2, ...

FROM table_name
WHERE condition;

3. Views can be used to provide a customized view of the data to different users. For
example, a sales department may only need to see customer and order information, while
a marketing department may need to see additional data such as product details and
sales figures.
4. Views can be used to simplify complex queries. For example, a complex query that
involves multiple tables and joins can be simplified by creating a view that combines the
necessary data.
5. Views can be used to provide an additional layer of security by controlling access to
sensitive data. For example, a view can be created that only shows non-sensitive data to
users who do not have permission to view the sensitive data.
6. Views do not store data themselves. They are based on the underlying tables in the
database, and any changes to the underlying tables will be reflected in the view.
7. Views can be updated just like tables, provided that they meet certain criteria. For
example, the view must be based on a single table, and it must not contain any
aggregate functions or subqueries.

Overall, views are a powerful tool for simplifying complex queries and providing a customized
view of the data to different users. They can be used to improve performance, enhance security,
and provide an additional layer of abstraction between the data and the users.

Triggers
In SQL, a trigger is a set of actions that are automatically executed in response to a specific
database event, such as an insert, update, or delete operation on a table. Here are some key
features of triggers:

1. Triggers are defined using the CREATE TRIGGER statement. The syntax is as follows:
CREATE TRIGGER trigger_name

BEFORE/AFTER INSERT/UPDATE/DELETE

ON table_name

FOR EACH ROW

BEGIN

-- trigger actions go here

END;

The trigger_name is the name of the trigger, BEFORE or AFTER specifies when the trigger should
be executed, INSERT, UPDATE, or DELETE specifies the type of operation that should activate the
trigger, table_name is the name of the table on which the trigger should be defined, and the FOR
EACH ROW specifies that the trigger should be executed once for each row affected by the
operation.

2. Triggers can be used to enforce business rules and data integrity constraints. For
example, a trigger can be used to prevent the deletion of a row in a table that is
referenced by another table.
3. Triggers can be used to audit database activity. For example, a trigger can be used to log
information about changes to a table, such as the user who made the change and the
time of the change.
4. Triggers can be used to replicate data between tables or databases. For example, a
trigger can be used to automatically update a backup database whenever a row is
inserted, updated, or deleted in the primary database.
5. Triggers can be nested. That is, one trigger can activate another trigger.
6. Triggers can be disabled or enabled using the ALTER TABLE statement.

Overall, triggers are a powerful tool for enforcing business rules, maintaining data integrity, and
auditing database activity. However, they can also be complex to manage and can have
performance implications, especially if they are used extensively. As with any database feature, it
is important to use triggers judiciously and to carefully test and monitor their performance.

Database Security
Database security refers to the measures taken to protect a database from unauthorized access,
use, or modification. Here are some key aspects of database security:

1. Authentication: Authentication is the process of verifying the identity of a user who is


attempting to access a database. Usernames and passwords are commonly used for
authentication.
2. Authorization: Authorization is the process of granting or denying access to a database
based on a user's identity and permissions. Database permissions can be granted at the
user, group, or role level.
3. Encryption: Encryption is the process of converting data into a coded language to prevent
unauthorized access. Data encryption can be used to protect sensitive information in a
database.
4. Access control: Access control is the process of controlling who has access to a database
and what actions they can perform. Access control policies can be used to restrict access
to certain tables or columns within a database.
5. Auditing: Auditing is the process of monitoring database activity and generating audit
logs. Audit logs can be used to track changes to a database and to identify potential
security breaches.
6. Backup and recovery: Backup and recovery procedures are critical for database security.
Regular backups can help ensure that data can be restored in the event of a security
breach or system failure.
7. Patch management: Regular software updates and patches are essential for maintaining
database security. Updates can help address security vulnerabilities and prevent exploits.

Overall, database security is a complex and ongoing process that requires a combination of
technical controls, policies and procedures, and user education and awareness. By implementing
a comprehensive security program, organizations can help protect their databases from
unauthorized access and data breaches.
Embedded &Dynamic SQL
Embedded SQL and Dynamic SQL are two approaches for executing SQL statements in
applications.

1. Embedded SQL: Embedded SQL involves embedding SQL statements directly into
application code. The SQL statements are precompiled and optimized by the database
management system (DBMS) before they are executed. This approach is often used in
applications that require high performance and scalability, such as transaction processing
systems. Embedded SQL is typically used in programming languages like C/C++, COBOL,
and FORTRAN.

Example of Embedded SQL in C:

#include <stdio.h>

#include <sqlca.h>

EXEC SQL BEGIN DECLARE SECTION;

char name[20];

int age;

EXEC SQL END DECLARE SECTION;

int main() {

EXEC SQL CONNECT TO database_user IDENTIFIED BY password;

if (sqlca.sqlcode != 0) {

printf("Error connecting to database.\n");

return 1;

printf("Enter name and age: ");

scanf("%s %d", name, &age);

EXEC SQL INSERT INTO users (name, age) VALUES (:name, :age);

if (sqlca.sqlcode != 0) {

printf("Error inserting record.\n");

return 1;

EXEC SQL COMMIT;


printf("Record inserted successfully.\n");

EXEC SQL DISCONNECT;

return 0;

2. Dynamic SQL: Dynamic SQL involves constructing SQL statements at runtime


based on user input or other factors. The SQL statements are not precompiled
or optimized by the DBMS and are executed using a runtime engine. This
approach is often used in applications that require flexibility and adaptability,
such as business intelligence systems. Dynamic SQL is typically used in
programming languages like Java, PHP, and Python.

Example of Dynamic SQL in Python:

import psycopg2

conn = psycopg2.connect(database="mydatabase", user="myusername", password="mypassword",


host="localhost", port="5432")

cur = conn.cursor()

table = input("Enter table name: ")

column = input("Enter column name: ")

value = input("Enter value: ")

sql = f"SELECT * FROM {table} WHERE {column} = '{value}'"

cur.execute(sql)

rows = cur.fetchall()

for row in rows:

print(row)

cur.close()

conn.close()
In summary, Embedded SQL and Dynamic SQL are two approaches for executing SQL statements
in applications. Embedded SQL is used when performance is critical and queries are static, while
Dynamic SQL is used when flexibility is important and queries are dynamic.

You might also like