0% found this document useful (0 votes)
11 views35 pages

Comprehensive SQL Guide and Commands

The document provides a comprehensive overview of SQL, including its commands, constraints, joins, data types, and operators. It also covers PL/SQL, stored procedures, functions, triggers, cursors, and transaction control. Additionally, it discusses Oracle Forms and Reports, set operators, and attribute declarations in PL/SQL.

Uploaded by

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

Comprehensive SQL Guide and Commands

The document provides a comprehensive overview of SQL, including its commands, constraints, joins, data types, and operators. It also covers PL/SQL, stored procedures, functions, triggers, cursors, and transaction control. Additionally, it discusses Oracle Forms and Reports, set operators, and attribute declarations in PL/SQL.

Uploaded by

Shubham Sah
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

SQL- Structured Query Language

standard language for managing relational databases


SQL is supported by MySQL, Oracle, SQL Server, PostgreSQL, etc.

Important Commands example-


1. CREATE TABLE – Creates a new table
CREATE TABLE students (
id INT PRIMARY KEY,
name VARCHAR(50),
age INT
);

2. INSERT INTO- Inserts new records


INSERT INTO students (id, name, age) VALUES (1, 'John', 20);

3. SELECT – Retrieves data


SELECT name, age FROM students WHERE age > 18;

4. GRANT – Gives permissions


GRANT SELECT ON students TO user1;

5. REVOKE – Removes permissions


REVOKE SELECT ON students FROM user1;

SAHIL S 1
SQL Constraints
Constraints ensure data integrity in tables.

Example:
CREATE TABLE employees (
emp_id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
salary DECIMAL(10,2) CHECK (salary > 0)
);

SQL Joins
Joins combine records from multiple tables

SQL Aggregate Functions


Used for calculations on data.

SAHIL S 2
SQL Subqueries & Views
• Subquery: A query inside another query.
SELECT name FROM students WHERE age = (SELECT MAX(age) FROM students);
• View: A virtual table based on a query.
CREATE VIEW student_view AS SELECT name, age FROM students;

SQL Data Types:


Data types define the type of data that can be stored in a column.
Different categories:
1. Numeric Data types
Used for storing numbers (integers and floating-point values).

Example:
CREATE TABLE employees (
emp_id INT,
salary NUMBER(10,2),
bonus DECIMAL(8,2)
);

2. Character/String Data Types


Used for storing text and string values.

SAHIL S 3
Example:
CREATE TABLE students (
student_id INT,
name VARCHAR(50),
remarks TEXT
);

3. Date/Time Data Types


Used for storing date and time values.

Example:
CREATE TABLE orders (
order_id INT,
order_date DATE,
delivery_time TIMESTAMP
);
4. Other SQL Data Types

Components of SQL system:


[Link] [Link] [Link]
[Link] [Link] [Link]
[Link] [Link] Procedure
[Link]- (group of SQL statements executed as a single unit)

SAHIL S 4
Types of SQL Operators

SAHIL S 5
Operator Precedence (Execution Order)
Operators follow a specific order of execution, similar to BODMAS (Brackets, Orders,
Division, Multiplication, Addition, Subtraction) in Mathematics.

1. Arithmetic Operators (*, /, %, +, -)


2. Comparison Operators (=, >, <, >=, <=, !=)
3. Logical NOT
4. Logical AND
5. Logical OR

SAHIL S 6
PL/SQL
PL/SQL (Procedural Language/SQL) is an extension of SQL.
Allows procedural programming using loops, conditions, and exception handling.
PL/SQL is used for writing stored procedures, triggers, functions, and packages.

Features:
1. Supports procedural programming (IF, LOOP, CASE).
2. Allows error handling using EXCEPTION
3. Enhances performance by reducing multiple SQL calls.
4. Supports modular programming with procedures and functions.
5. Ensures data security with stored procedures.
PL/SQL block structure:
DECLARE -- (Optional) Declare variables
BEGIN -- (Mandatory) Execution section
-- SQL and PL/SQL statements
EXCEPTION -- (Optional) Error handling
-- Error-handling code
END;
/

PL/SQL Data Types

PL/SQL Control Statements


1. Conditional Statements
IF-THEN
IF salary > 50000 THEN

SAHIL S 7
DBMS_OUTPUT.PUT_LINE('High Salary');
END IF;

IF-THEN-ELSE
IF salary > 50000 THEN
DBMS_OUTPUT.PUT_LINE('High Salary');
ELSE
DBMS_OUTPUT.PUT_LINE('Low Salary');
END IF;

CASE Statement
CASE
WHEN salary > 50000 THEN DBMS_OUTPUT.PUT_LINE('High Salary');
WHEN salary > 30000 THEN DBMS_OUTPUT.PUT_LINE('Medium Salary');
ELSE DBMS_OUTPUT.PUT_LINE('Low Salary');
END CASE;

Loops in PL/SQL

Example: FOR LOOP


BEGIN
FOR i IN 1..5 LOOP
DBMS_OUTPUT.PUT_LINE('Iteration: ' || i);
END LOOP;
END;
/

SAHIL S 8
SQL *PLUS
SQL*Plus is an interactive tool provided by Oracle for executing SQL commands and PL/SQL
blocks. t supports both command-line and GUI versions.
SQL*Plus Commands
1. Environment Commands

2. Formatting Commands

3. Query Execution Commands

SQL*Plus Editing Commands


SQL*Plus provides editing commands to modify SQL statements.

SAHIL S 9
Running SQL Scripts in SQL*Plus
1. Open Notepad or any text editor.
2. Write SQL commands and save as [Link]:
SELECT * FROM employees;
3. Run in SQL*Plus:
START [Link];

SAHIL S 10
Stored Procedures
A Stored Procedure is a precompiled set of SQL statements stored in the database. It
executes as a single unit
Key Characteristics

✔ Stored in the database schema and executed when needed.

✔ Supports parameters to accept input values and return output.


✔ Can be used to perform DML and DDL operations.
✔ Reduces redundancy by allowing reuse of SQL logic.

Advanatges-
[Link] it is precompiled, it saves execution time.
2. Code Reusability
3. Centralized logic ensures uniform business rules across application

A stored procedure typically consists of:

Types of Stored Procedures

SAHIL S 11
Stored Procedure vs. Regular SQL Queries

SAHIL S 12
Functions in SQL
SQL Functions are built-in operations that perform calculations, modify data, and return
results.
Types of SQL Functions
SQL functions are categorized into two main types:

1. Single-Row (Scalar) Functions


• Operate on a single value and return a single result.
• Used for string, numeric, date, and conversion operations.

2. Aggregate (Group) Functions


• Operate on multiple rows and return a single summary value.
• Commonly used with GROUP BY for summarizing data.

Single-Row (Scalar) Functions


A. String Functions (Used to manipulate text data)

B. Numeric Functions (Perform mathematical calculations)

SAHIL S 13
C. Date & Time Functions (Work with date and time values)

D. Conversion Functions (Convert data types)

Aggregate (Group) Functions

SAHIL S 14
TRIGGER
A Trigger is a stored PL/SQL block that automatically executes when a specified event
occurs in the database. Triggers can be set to fire BEFORE or AFTER an event.

Advantages of Triggers

✔ Automatic Execution – No manual execution required.


✔ Enforces Business Rules – Restrict invalid data.
✔ Audit and Logging – Track changes automatically.
✔ Maintains Data Integrity – Prevent unauthorized modifications.

SAHIL S 15
CURSOR
A cursor in PL/SQL is a pointer to a result set of a SQL query. It is used to fetch and process
multiple rows from a database. Cursors are essential for handling query results row by row.

Advantages of Cursors

✔ Handles multiple rows from queries efficiently.


✔ Provides row-by-row processing for complex logic.
✔ Dynamic processing using parameterized or REF cursors.
✔ Improves performance by avoiding multiple query executions

SAHIL S 16
JOIN
Joins in SQL are used to combine data from two or more tables based on a related column

Given two tables-

SAHIL S 17
[Link] join:
SELECT Students.student_name, Courses.course_name

FROM Students

INNER JOIN Courses

ON Students.course_id = Courses.course_id;

[Link] join:
SELECT Students.student_name, Courses.course_name

FROM Students

LEFT JOIN Courses

ON Students.course_id = Courses.course_id;

[Link] join:
SELECT Students.student_name, Courses.course_name

FROM Students

RIGHT JOIN Courses

ON Students.course_id = Courses.course_id;

SAHIL S 18
[Link] join:
SELECT Students.student_name, Courses.course_name

FROM Students

FULL JOIN Courses

ON Students.course_id = Courses.course_id;

[Link] join:
SELECT Students.student_name, Courses.course_name

FROM Students

CROSS JOIN Courses;

SAHIL S 19
CLAUSES
SQL clause helps us to retrieve a set of records from the table by specifying a condition on
the columns or records of a table.

(A) WHERE Clause

Used to filter records based on a condition


Works with SELECT, UPDATE, DELETE statements

Example: Get students enrolled in course 101


SELECT * FROM Students WHERE course_id = 101;

(B) HAVING Clause

Used to filter records based on aggregated data (GROUP BY results)


Works only with GROUP BY

Example: Get courses where more than 2 students are enrolled


SELECT course_id, COUNT(student_id)

FROM Students

GROUP BY course_id

HAVING COUNT(student_id) > 2;

SAHIL S 20
(C) ORDER BY Clause

Used to sort query results in ascending or descending order


Default sorting is ASC (Ascending)

Example: Get all students sorted by name in descending order


SELECT * FROM Students ORDER BY student_name DESC;

SAHIL S 21
(D) GROUP BY Clause

Groups rows based on a column’s value and applies aggregate functions

Example: Count the number of students in each course


SELECT course_id, COUNT(student_id)
FROM Students
GROUP BY course_id;

SAHIL S 22
CONSTRAINTS
SQL Constraints are rules applied to table columns to ensure data integrity and accuracy.
They prevent invalid, duplicate, or inconsistent data in the database.
Constraints are applied during table creation using the CREATE TABLE or later with
ALTER TABLE.

Types of SQL Constraints


(A) PRIMARY KEY Constraint

Ensures that each row in a column is unique and NOT NULL.


A table can have only one PRIMARY KEY
CREATE TABLE Students (
student_id INT PRIMARY KEY,
student_name VARCHAR(50),
course_id INT
);

Key Points:
• Each student_id must be unique and cannot be NULL.
• A table can have only one PRIMARY KEY, but it can consist of multiple columns
(Composite Key).

(B) FOREIGN KEY Constraint

Ensures referential integrity by linking a column to the PRIMARY KEY of another table.
Prevents invalid data entry in child tables.
CREATE TABLE Courses (
course_id INT PRIMARY KEY,
course_name VARCHAR(50)
);

CREATE TABLE Students (


student_id INT PRIMARY KEY,

SAHIL S 23
student_name VARCHAR(50),
course_id INT,
FOREIGN KEY (course_id) REFERENCES Courses(course_id)
);

Key Points:
• course_id in Students must match a valid course_id in Courses.
• If a course_id does not exist in Courses, it cannot be inserted in Students.

(C) UNIQUE Constraint

Ensures that values in a column are unique (no duplicates allowed).


Unlike PRIMARY KEY, it allows NULL values (unless NOT NULL is used).
CREATE TABLE Users (
user_id INT PRIMARY KEY,
email VARCHAR(100) UNIQUE
);

Key Points:
• Each email must be unique but can be NULL.
• A table can have multiple UNIQUE columns.

(D) NOT NULL Constraint

Ensures that a column cannot store NULL values.


CREATE TABLE Employees (
emp_id INT PRIMARY KEY,
emp_name VARCHAR(50) NOT NULL,
salary DECIMAL(10,2) NOT NULL
);

Key Points:
• emp_name and salary must have values (cannot be NULL).
• Useful for mandatory fields like Name, Email, etc.

SAHIL S 24
(E) CHECK Constraint

Ensures that column values meet a specific condition.


CREATE TABLE Products (
product_id INT PRIMARY KEY,
price DECIMAL(10,2) CHECK (price > 0)
);

Key Points:
• The price must be greater than 0.
• Helps enforce valid data ranges (e.g., age must be ≥18).

(F) DEFAULT Constraint

Assigns a default value to a column if no value is provided.


CREATE TABLE Orders (
order_id INT PRIMARY KEY,
order_status VARCHAR(20) DEFAULT 'Pending'
);

Key Points:
• If no value is inserted in order_status, it defaults to 'Pending'.
• Useful for setting default values like 0 for quantity, CURRENT_TIMESTAMP for dates,
etc.

SAHIL S 25
Transaction Control & Concurrency Control
1. Transaction Control in SQL
What is a Transaction?

A transaction is a set of SQL operations executed as a single unit.


It follows the ACID properties (Atomicity, Consistency, Isolation, Durability).

Transaction Control Language (TCL) Commands


SQL provides TCL commands to manage transactions effectively:

2. Concurrency Control in SQL


What is Concurrency Control?

Concurrency control manages multiple users accessing the database simultaneously to


prevent conflicts.
It ensures data consistency and integrity when multiple transactions are executed at the
same time.

SAHIL S 26
SAHIL S 27
FORMS
1. What is a Form in Oracle?

Forms in Oracle are graphical user interfaces (GUI) that allow users to view, insert,
update, and delete data from a database easily.
They provide an interactive way to interact with database tables without writing SQL
queries manually.
Used in Oracle Forms Builder, a tool in Oracle Developer Suite.

2. Features of Oracle Forms

3. Types of Forms in Oracle

4. Components of an Oracle Form

Blocks → Containers that hold items (text fields, buttons, etc.).


Items → Individual fields (text boxes, radio buttons, checkboxes).
Canvas → The area where the form is displayed.
Triggers → PL/SQL code executed when an event occurs (e.g., clicking a button).
Alerts → Pop-up messages to show warnings or confirmations.

SAHIL S 28
REPORTS
1. What is a Report in Oracle?

Reports in Oracle are formatted documents that present database data in a structured
way.
Used for data analysis, summaries, invoices, charts, and printable documents.
Created using Oracle Reports Builder, part of Oracle Developer Suite.

2. Features of Oracle Reports

3. Types of Reports in Oracle

4. Components of an Oracle Report

Data Model → Defines the data source (SQL query, table, view).
Layout Model → Controls the report structure and formatting.
Parameter Form → Allows user input to filter data dynamically.
Triggers → PL/SQL code executed before/after the report runs.
Report Output → Can be displayed as PDF, HTML, Excel, or printed documents.

SAHIL S 29
SET OPERATORS
SET operators are special type of operators which are used to combine the result of two
queries. The queries must have the same number of columns.
Types of Set Operators in SQL

Examples of Set Operators


Consider two tables: Students_2023 and Students_2024

(1) UNION (Removes Duplicates)

Combines both tables but removes duplicate records.

SAHIL S 30
Result of UNION

(2) UNION ALL (Keeps Duplicates)

Combines both tables but keeps duplicates.


Result of UNION ALL

(3) INTERSECT (Common Rows in Both Tables)

Returns only the common records present in both tables.


Result of INTERSECT

(4) MINUS (First Table - Second Table)

Returns records from Students_2023 that are not in Students_2024.


Result of MINUS

SAHIL S 31
ATTRIBUTE DECLARATIONS (%TYPE, %ROWTYPE)
Attribute declarations in PL/SQL are placeholders used to declare variables dynamically
based on existing database structures.
They ensure data consistency and reduce maintenance efforts by automatically
adapting to changes in database schema.
The two main types of attribute declarations in PL/SQL are:
• %TYPE → Inherits the data type of a specific column.
• %ROWTYPE → Inherits the structure (all columns) of a table or cursor.

%TYPE Attribute
Definition:

The %TYPE attribute is used to declare a variable that inherits the data type of a specific
column in a table or another variable.
This ensures that if the column’s data type changes, the variable automatically adapts.
Syntax:
variable_name table_name.column_name%TYPE;

Advantages of %TYPE:

Prevents datatype mismatches.


Adapts automatically if the column’s data type changes.

%ROWTYPE Attribute
Definition:

The %ROWTYPE attribute is used to declare a record variable that inherits the structure
of an entire table row.
This means the record will have all columns and their respective data types from the
table.

Syntax:
record_name table_name%ROWTYPE;

SAHIL S 32
Advantages of %ROWTYPE:

Stores multiple column values at once.


Reduces the number of variables needed.
Adapts automatically to table structure changes.

Key Differences Between %TYPE and %ROWTYPE

SAHIL S 33
LIBRARY, ALERTS and LOV IN DEVELOPER 2000

1. Library

A Library (.PLL file) is a collection of reusable PL/SQL procedures, functions, and


packages.
It allows developers to store and share commonly used PL/SQL code across multiple
forms and reports.
Libraries help in maintaining modular programming and code reusability.
Key Features of Libraries:

Encapsulation – Store reusable PL/SQL code in one place.


Modularity – Helps in reducing redundant code in forms and reports.

2. Alerts
What is an Alert?

An Alert is a popup message box used to display important messages, warnings, or


confirmations to users.
Alerts help in getting user input or providing error messages during form execution.
Types of Alerts in Oracle Developer 2000:

3. LOV (List Of Values)

List of Values (LOV) is a popup window that displays a list of valid values for a field in an
Oracle Form.
It helps users select values easily instead of manually entering them.

SAHIL S 34
Types of LOV in Oracle Forms

SAHIL S 35

Common questions

Powered by AI

PL/SQL enhances the functionality of standard SQL by adding procedural programming capabilities that allow for control structures (like loops and conditions), exception handling, and modular programming with procedures, functions, and packages. This enables complex business logic to be applied within the database, supports error handling, and provides better performance for batch processing by combining multiple SQL operations into a single execution block. PL/SQL thereby allows for better data processing and management than traditional SQL where only declarative data manipulation language can be used .

The WHERE clause in SQL is used to filter records based on specific conditions applied before data grouping or aggregation, working effectively with SELECT, UPDATE, and DELETE statements. Conversely, the HAVING clause is used to filter aggregated data post grouping, and specifically acts on the results of GROUP BY operations. Thus, WHERE is used to set conditions on individual records, while HAVING sets conditions on groups formed by aggregate functions, providing different scopes and functionalities in query construction .

Using a stored procedure is advantageous over a regular SQL query when repetitive tasks need to be automated or when complex operations, involving multiple SQL queries, need to be encapsulated into a single execution unit. Stored procedures are precompiled, which boosts performance and ensures the consistency of operations through centralized logic. They reduce redundancy by allowing SQL logic to be reused and also provide enhanced security, as users do not directly manipulate the underlying SQL but instead interact with the database through the stored procedure interface .

Triggers help maintain data integrity and enforce business rules by automatically executing a set of instructions in response to specific events on a table or view in a database. For example, triggers can enforce business rules by ensuring that each new row added to a table meets certain criteria or maintain data integrity by restricting unauthorized changes to data fields. Triggers can also automate the auditing of changes, thereby ensuring all data modifications are logged and traced. These capabilities make triggers valuable for maintaining reliable and consistent databases .

Views in SQL are significant because they allow users to present data in a specific format without modifying the underlying tables. They act as virtual tables, generated from a SELECT query that fetches and manipulates the data dynamically. Unlike actual tables, views do not store data themselves but derive it from the existing tables. This abstraction helps in simplifying complex queries, securing sensitive data by limiting the data access to specific columns or rows, and providing a consistent interface to data that might change over time .

SQL's aggregate functions are utilized for data analysis by performing calculations on multiple rows of a table, returning a single value summarizing the data. Common aggregate functions include COUNT(), SUM(), AVG(), MIN(), and MAX(), which are often used in conjunction with the GROUP BY clause to organize and analyze data by specific groupings. For instance, they are employed to calculate the total sales for a quarter, average employee salary, or the maximum product price, thus enabling meaningful insights from aggregated data .

Cursors in PL/SQL provide benefits by allowing row-by-row processing of a SQL query result set, which is useful in scenarios requiring complex processing for each row, such as batch updates or computation transformations. Cursors enable efficient handling of result sets, avoiding multiple query executions by fetching multiple rows at once. Unlike standard SQL, where operations typically process a single row or aggregate set, PL/SQL cursors can dynamically interact with result sets and process complex logic, making them essential for procedural operations in database applications .

SQL operators affect the execution and results of queries by determining how expressions involving data fields are evaluated and manipulated within a query. Operators are classified into arithmetic, comparison, logical, and set operators, each having specific precedence rules that affect execution. For instance, arithmetic operators like + and - affect mathematical calculations, comparison operators like = and > compare values, while logical operators like AND, OR define logical connections between conditions. Understanding their precedence is crucial for crafting correct and efficient queries, ensuring accurate data retrieval and manipulation .

SQL Joins enhance data analysis by allowing the combination of records from two or more tables based on a related column, facilitating comprehensive data aggregation. There are several types of Joins in SQL: Inner Join, which retrieves records with matching values in both tables; Left Join, which returns all records from the left table, and the matched records from the right table; Right Join, which returns all records from the right table, and the matched records from the left table; Full Join, which returns all records when there is a match in either left or right table records; and Cross Join, which returns the Cartesian product of both tables .

SQL constraints are rules applied to table columns that ensure data integrity and accuracy, preventing invalid, duplicate, or inconsistent data within a database. Constraints ensure that each entry adheres to a pre-defined rule, such as uniqueness, non-nullability, or referential integrity. Common constraints include PRIMARY KEY, UNIQUE, FOREIGN KEY, NOT NULL, CHECK, and DEFAULT, each serving a distinct role in maintaining database integrity .

You might also like