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

UNIT 3 - Final

The document outlines the course content for Advanced DBMS at St. Philomena's College, focusing on SQL, including data definition, data types, and query structures. It covers key concepts such as creating tables, schemas, constraints, and various SQL operations like joins and views. Additionally, it explains handling NULL values, basic retrieval queries, and the differences between SQL and the relational model.

Uploaded by

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

UNIT 3 - Final

The document outlines the course content for Advanced DBMS at St. Philomena's College, focusing on SQL, including data definition, data types, and query structures. It covers key concepts such as creating tables, schemas, constraints, and various SQL operations like joins and views. Additionally, it explains handling NULL values, basic retrieval queries, and the differences between SQL and the relational model.

Uploaded by

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

St.

Philomena's College (Autonomous), Mysore


MCA Department
Course Name: Advanced DBMS

Course Content
UNIT- III - Introduction to SQL
Overview of the SQL Query Language, SQL Data Definition, Basic structure of SQL Queries, Additional Basic
Operations, Null values, Aggregate Functions, nested Sub queries, Modification of the Database, Join
Expressions, Views, Transactions, Integrity Constraints, SQL Data Types and Schemas, Authorization.
Database programming issues and techniques, Embedded SQL

The above concepts are taken from the textbook called


Database System Concepts by Abraham Silberschatz, H. Korth, Sudarshan - Page no 87
SQL Data Definition and Data Types

➔ Terminology: SQL uses table (relation), row (tuple), and column (attribute) interchangeably.

➔ CREATE Statement: Used to create schemas, tables, and domains, plus views, assertions, and

triggers.

➔ Schemas and Catalogs: Organize database objects, providing context for table creation.

➔ Table Creation: CREATE TABLE defines tables and specifies columns with data types.

➔ Data Types: SQL supports various types, including numeric, string, and date/time.
Schema and Catalog Concepts in SQL

➔ Early SQL versions had no relational database schema concept; all tables belonged to the same

schema.

➔ Starting with SQL2, schemas were introduced to group tables and related constructs within a specific

application.

➔ A schema includes:

➔ Schema Name: Identifies the schema.

➔ Authorization Identifier: Indicates the owner (user or account).

➔ Schema Elements: Includes tables, constraints, views, domains, and authorization grants.

➔ A schema is created using the CREATE SCHEMA statement, either with all elements defined initially or

assigned a name and authorization identifier for later definition.

Example:

➔ CREATE SCHEMA COMPANY AUTHORIZATION 'Jsmith';


The CREATE TABLE Command in SQL

➔ The CREATE TABLE command defines a new table (relation), specifying:

Table name

◆ Attributes: Each with a name, data type (domain), and constraints (e.g., NOT NULL).

◆ Constraints: Key, entity integrity, and referential integrity constraints can be included or added

later via ALTER TABLE.

➔ The SQL schema for tables is usually implicit but can be explicitly stated by prefixing the schema name

(e.g., CREATE TABLE COMPANY.EMPLOYEE vs. CREATE TABLE EMPLOYEE).


Base Tables vs. Virtual Relations

➔ Base Tables: Declared using CREATE TABLE, these are actual tables with tuples stored in files by the

DBMS.

➔ Virtual Relations: Created using CREATE VIEW, these do not always correspond to physical files.

➔ Attributes in a base table are ordered as defined in CREATE TABLE, but rows (tuples) are not ordered.

Foreign Keys

➔ Circular references (e.g., Super_ssn in the EMPLOYEE table) or references to tables not yet created

(e.g., Dno in EMPLOYEE referring to DEPARTMENT) can cause errors.

➔ To avoid issues, foreign key constraints can be added later using ALTER TABLE.
Attribute Data Types and Domains in SQL

Numeric Data Types:

➔ INTEGER/INT, SMALLINT: For integers.

➔ FLOAT/REAL, DOUBLE PRECISION: For floating-point numbers.

➔ DECIMAL(i,j), NUMERIC(i,j): For formatted numbers, where i is the total number of digits, and j is

digits after the decimal point.

Character-String Data Types

➔ Fixed Length: CHAR(n) or CHARACTER(n) defines strings of fixed length.

➔ Variable Length: VARCHAR(n) or CHARACTER VARYING(n) allows strings of variable length.

➔ String literals are enclosed in single quotes (case-sensitive). Fixed-length strings are padded with

spaces if shorter than the specified length.

➔ Comparison: Strings are ordered alphabetically (lexicographically).


➔ Concatenation Operator: || combines two strings (e.g., 'abc' || 'XYZ' results in 'abcXYZ').

➔ CLOB: For large text values like documents, specified in kilobytes, megabytes, or gigabytes (e.g.,

CLOB(20M) for 20 megabytes).

Bit-string Data Types

➔ Fixed Length: BIT(n) specifies a fixed-length bit string of n bits.

➔ Variable Length: BIT VARYING(n) allows for variable-length bit strings, with a maximum of n bits.

➔ Literal Format: Bit strings are written as B'10101' (preceded by B to distinguish from character

strings).

➔ BLOB (Binary Large Object): Used for large binary data (e.g., images), with a size specified in

kilobits (K), megabits (M), or gigabits (G). Example: BLOB(30G) for 30 gigabits.

Boolean Data Type

➔ Values: TRUE, FALSE, or UNKNOWN (due to the presence of NULL in SQL, a third value, UNKNOWN, is

part of the three-valued logic).


DATE Data Type

➔ Format: YYYY-MM-DD (10 positions), with components YEAR, MONTH, and DAY.

➔ Only valid dates are allowed (e.g., month between 1-12, valid day for each month).

TIME Data Type

➔ Format: HH:MM:SS (at least 8 positions), with components HOUR, MINUTE, and SECOND.

➔ Literal representation: Enclosed in single quotes, e.g., DATE '2008-09-27' or TIME '09:12:47'.
Specifying Constraints in SQL

➔ Basic Constraints: These can be defined during table creation and include:

➔ Key Constraints: Define primary and unique keys.

➔ Referential Integrity Constraints: Ensure relationships between tables (e.g., foreign keys).

➔ Domain and NULL Constraints: Restrict the type of data for attributes and whether NULL is allowed.

➔ Tuple-Level Constraints: Apply restrictions to individual rows.

Attribute Constraints and Defaults in SQL

➔ NOT NULL: Used to prevent NULL values for an attribute. This is implicit for primary key attributes but

can be specified for others.

➔ DEFAULT: Defines a default value for an attribute if no explicit value is provided during insertion. If no

default is specified, the default is NULL (unless NOT NULL is applied).

➔ CHECK Constraint: Restricts attribute values. For example, to limit department numbers to between 1

and 20: Dnumber INT NOT NULL CHECK (Dnumber > 0 AND Dnumber < 21);
Key and Referential Integrity Constraints in SQL

➔ PRIMARY KEY: Specifies one or more attributes as the primary key. For single attributes, it can be

written directly: Dnumber INT PRIMARY KEY;

➔ UNIQUE: Used to define alternate (secondary) keys, either for one or multiple attributes:

Dname VARCHAR(15) UNIQUE;

➔ FOREIGN KEY: Specifies referential integrity, ensuring that values in one table correspond to values in

another table. Violations (e.g., inserts, deletes, or updates) are restricted by default.

➔ Referential Triggered Actions

➔ SET NULL: Sets foreign key values to NULL when the referenced row is deleted.

➔ CASCADE: Propagates changes—deletes or updates—through related rows.

➔ SET DEFAULT: Replaces foreign key values with a predefined default when a referenced row is deleted

or updated.
➔ ON DELETE and ON UPDATE: Qualify the action to take for foreign key violations, for example:

ON DELETE SET NULL

ON UPDATE CASCADE

➔ Example: In EMPLOYEE, if a supervising employee is deleted, Super_ssn is set to NULL for the

employees they supervised. If the supervisor’s Ssn is updated, it cascades to Super_ssn.

➔ CASCADE is often suitable for relationship relations, multivalued attributes, or weak entity types.
Basic Retrieval Queries in SQL

➔ SELECT Statement: SQL's main command for retrieving data from a database. It differs from the

relational algebra SELECT operation.

➔ Gradual Introduction: We'll explore features of the SELECT statement using sample queries.

SQL vs. Relational Model

➔ SQL tables can have duplicate rows, meaning they are multisets (or "bags") of tuples, unlike sets in the

formal relational model which don’t allow duplicates.

➔ SQL tables can be constrained to sets if a key constraint is declared or the DISTINCT option is used in

SELECT to eliminate duplicates.


Basic SQL Query Structure: SELECT-FROM-WHERE

➔ The basic form of an SQL query consists of three main clauses:

➔ SELECT: Specifies the attributes (columns) to retrieve.

➔ FROM: Lists the tables required for the query.

➔ WHERE: Specifies the condition for filtering rows (Boolean expressions like =, <>, <, etc.).

Example Queries

➔ Query 0: Retrieve birth date and address of employees named 'John B. Smith':

SELECT Bdate, Address

FROM EMPLOYEE

WHERE Fname = 'John' AND Minit = 'B' AND Lname = 'Smith';


ORDER BY Clause

➔ The ORDER BY clause is used to sort the result set of a query by one or more columns. By default,

sorting is done in ascending order, but you can specify descending order if needed. Syntax

SELECT column1, column2, ...

FROM table_name

ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;

➔ ASC: Sorts in ascending order (default).

➔ DESC: Sorts in descending order.

DISTINCT Keyword

➔ The DISTINCT keyword is used to remove duplicate rows from the result set. If a column contains

duplicate values, using DISTINCT ensures only unique rows are returned. Syntax:

SELECT DISTINCT column1, column2, ...

FROM table_name
LIMIT and OFFSET

➔ The LIMIT and OFFSET keywords are used to restrict the number of rows returned by a query and to

paginate results.

➔ LIMIT: Specifies the maximum number of rows to return.

➔ OFFSET: Skips a specific number of rows before starting to return rows.

SELECT column1, column2, ...

FROM table_name

LIMIT number_of_rows OFFSET skip_rows;

Example

SELECT Fname, Lname

FROM EMPLOYEE

LIMIT 10 OFFSET 20;

➔ This query retrieves 10 rows starting from the 21st row, useful for pagination in

applications.
BETWEEN, IN, LIKE, and Other Operators

BETWEEN

➔ The BETWEEN operator is used to filter the result set within a specific range of values. It can be used

with numeric, date, and text values. Syntax

SELECT column1, column2, ...

FROM table_name

WHERE column_name BETWEEN value1 AND value2;

IN

➔ The IN operator is used to specify multiple possible values for a column. It’s an alternative to multiple

OR conditions. Syntax

SELECT column1, column2, ...

FROM table_name

WHERE column_name IN (value1, value2, ...);


LIKE

➔ The LIKE operator is used for pattern matching. It searches for a specified pattern in a column.

➔ %: Matches any number of characters.

➔ _: Matches a single character.

Syntax

SELECT column1, column2, ...

FROM table_name

WHERE column_name LIKE 'pattern';


Understanding NULL in SQL

➔ In SQL, NULL represents the absence of a value or an unknown value. It's important to note that NULL

is not the same as:

➔ Zero (0) for numeric fields.

➔ Empty string ('') for text fields.

Key points about NULL

➔ It indicates missing or undefined data.

➔ NULL values do not participate in regular comparisons (e.g., NULL is not equal to NULL).

➔ Any arithmetic or comparison operation involving NULL results in NULL (unknown).

Example

➔ In an employee database, if an employee's phone number is not available, the phone number column

can be set to NULL instead of an empty string.


Handling NULL Values in Queries

➔ When working with queries, you often need to account for the presence of NULL values, especially

when filtering or aggregating data.

Key behaviors with NULL:

➔ Arithmetic operations: If a column with NULL is involved in an operation like addition or

multiplication, the result will be NULL.

◆ Example: 10 + NULL results in NULL.

➔ Comparison operations: Comparisons involving NULL return UNKNOWN. For example, NULL = NULL

does not return TRUE; it returns NULL (or unknown).

◆ Example: SELECT * FROM EMPLOYEE WHERE Salary = NULL; returns no results, even if a salary

is missing.

➔ To handle NULL effectively in queries, SQL provides the IS NULL and IS NOT NULL operators.
IS NULL and IS NOT NULL Operators

➔ These operators are used to explicitly check whether a column contains NULL values.

➔ IS NULL: This operator checks if a column's value is NULL.

SELECT column1, column2

FROM table_name

WHERE column_name IS NULL;

➔ IS NOT NULL: This operator checks if a column's value is not NULL.

SELECT column1, column2

FROM table_name

WHERE column_name IS NOT NULL;


Join Expressions in SQL

➔ Joins in SQL are used to combine rows from two or more tables based on a related column between

them. This allows you to retrieve data that exists across multiple tables in a relational database.
Inner Join

➔ An Inner Join returns only the rows where there is a match between the columns in both tables. If no

match is found, the row is excluded from the result.

SELECT column1, column2, ...

FROM table1

INNER JOIN table2

ON table1.column = table2.column;

SELECT EMPLOYEE.Fname, EMPLOYEE.Lname, DEPARTMENT.Dname

FROM EMPLOYEE

INNER JOIN DEPARTMENT

ON EMPLOYEE.Dno = DEPARTMENT.Dnumber;

➔ This query retrieves employee first names, last names, and department names, but only for employees

who are assigned to a department. It excludes any employees who are not assigned to a department.
Outer Join

➔ Outer Joins return rows even when there is no match between the tables. There are three types of

outer joins: Left Outer Join, Right Outer Join, and Full Outer Join.

Left Outer Join (or Left Join)

➔ Returns all rows from the left table and the matching rows from the right table. If there’s no match,

NULL is returned for columns from the right table.

SELECT column1, column2, ...

FROM table1

LEFT JOIN table2

ON table1.column = table2.column;
Right Outer Join (or Right Join)

➔ Returns all rows from the right table and the matching rows from the left table. If there’s no match,

NULL is returned for columns from the left table.

SELECT column1, column2, ...

FROM table1

RIGHT JOIN table2

ON table1.column = table2.column;

Full Outer Join

➔ Returns all rows when there is a match in either table. If there is no match, NULL values are returned

for the missing matches in both the left and right tables.

SELECT column1, column2, ...

FROM table1

FULL OUTER JOIN table2

ON table1.column = table2.column;
Cross Join

➔ A Cross Join produces the Cartesian product of two tables. It returns every possible combination of rows

from both tables.

SELECT column1, column2, ...

FROM table1

CROSS JOIN table2;

Self Join

➔ A Self Join is when a table is joined to itself. It’s useful when you want to compare rows within the same

table.

SELECT A.column1, B.column2, ...

FROM table_name A, table_name B

WHERE A.column = B.column;


Views in SQL

➔ A view in SQL is a virtual table that is based on the result of a SELECT query.

➔ Unlike a real table, a view doesn’t store data itself; it displays data from one or more underlying tables.

➔ Views are useful for simplifying complex queries, enhancing security by restricting access to certain

data, and creating customized data representations.


Creating Views (CREATE VIEW)

➔ The CREATE VIEW statement is used to create a new view. The view is defined by a SELECT query, and

when the view is queried, the SQL engine runs the underlying SELECT query to return the results.

CREATE VIEW view_name AS

SELECT column1, column2, ...

FROM table_name

WHERE condition;

Managing and Using Views

➔ Once a view is created, you can use it just like a regular table in queries. You can select data from it,

filter rows, join it with other tables, etc.

SELECT Fname, Lname

FROM EmployeeView

WHERE Dname = 'Research';


Updating Views

➔ In some cases, you can update the data in the underlying tables through the view. However, not all

views are updatable. Updatable views generally follow these rules:

◆ The view must refer to only one table.

◆ The view should not include aggregate functions, DISTINCT, GROUP BY, HAVING, or UNION.

◆ It must include all required columns (columns with NOT NULL constraints) from the base table.

UPDATE EmployeeView

SET Lname = 'Smith'

WHERE Fname = 'John';

➔ This query updates the last name of the employee 'John' in the EmployeeView. The change will affect

the underlying EMPLOYEE table.

➔ If you try to update a view that doesn't meet the conditions for updatable views, you will receive an

error.
Dropping Views (DROP VIEW)

➔ You can delete a view using the DROP VIEW statement. This removes the view definition from the

database, but it doesn't affect the data in the underlying tables.

DROP VIEW view_name;


Database Programming Issues and Techniques

➔ When working with databases, certain techniques can help manage data more efficiently and automate

common tasks. The key concepts here are stored procedures, functions, triggers, and cursors. Let’s

explore each of these.

Stored Procedures

➔ A stored procedure is a set of SQL statements that you can save and reuse. They are useful for tasks

that are performed repeatedly and allow for complex logic within the database. Stored procedures

improve performance and security by allowing code to be precompiled and stored on the server.

CREATE PROCEDURE procedure_name (parameter1 datatype, parameter2 datatype, ...)

BEGIN

-- SQL statements

END;
Functions

➔ A function in SQL is similar to a stored procedure, but it returns a value and can be used in SQL

queries. Functions are often used for calculations or operations that need to be performed repeatedly.

CREATE FUNCTION function_name (parameter1 datatype, parameter2 datatype, ...)

RETURNS return_datatype

BEGIN

-- SQL statements

RETURN value;

END;
Triggers

➔ A trigger is a set of SQL statements that automatically execute ("fire") when certain actions occur in

the database, such as when a row is inserted, updated, or deleted. Triggers are useful for enforcing

business rules, validating data, or maintaining logs.

CREATE TRIGGER trigger_name

AFTER|BEFORE INSERT|UPDATE|DELETE

ON table_name

FOR EACH ROW

BEGIN

-- SQL statements

END;
Cursors

➔ A cursor is used to process each row returned by a query, one at a time. Cursors are often used when

you need to perform row-by-row operations that cannot be easily done with standard SQL queries

(which usually operate on sets of rows).

DECLARE cursor_name CURSOR FOR SELECT_statement;

OPEN cursor_name;

FETCH cursor_name INTO variable_list;

CLOSE cursor_name;
Authorization in SQL

➔ Authorization in SQL refers to managing access control and permissions for users on database objects

like tables, views, and procedures. SQL provides the GRANT and REVOKE commands to manage what

actions users can perform on these objects. User roles and permissions are essential to controlling who

can read, modify, or delete data, ensuring database security.


GRANT Command

➔ The GRANT command is used to provide specific privileges (permissions) to users or roles for database

objects. You can grant permissions such as SELECT, INSERT, UPDATE, DELETE, and more.

➔ Syntax: GRANT privilege_type ON object_name TO user_name [WITH GRANT OPTION];

➔ privilege_type: The type of action allowed (e.g., SELECT, INSERT, UPDATE, DELETE).

➔ object_name: The name of the table, view, or procedure.

➔ user_name: The user or role receiving the permission.

➔ WITH GRANT OPTION: (Optional) Allows the user to pass the permission to others.
REVOKE Command

➔ The REVOKE command removes previously granted privileges from users or roles. This ensures that

users lose access to perform certain actions if no longer needed or authorized.

➔ Syntax: REVOKE privilege_type ON object_name FROM user_name;

➔ privilege_type: The permission being revoked (e.g., SELECT, INSERT, UPDATE, DELETE).

➔ object_name: The name of the table, view, or procedure.

➔ user_name: The user or role losing the permission.


User Roles and Permissions

➔ Roles are a way to group permissions and manage access more efficiently. Instead of assigning

permissions to individual users one by one, you can assign them to a role, and then assign users to

that role. This simplifies permission management, especially in large systems.

Creating Roles

➔ CREATE ROLE role_name;

Granting Permissions to a Role

➔ GRANT privilege_type ON object_name TO role_name;

Example

➔ CREATE ROLE HR_MANAGER;

➔ GRANT SELECT, INSERT, UPDATE ON EMPLOYEE TO HR_MANAGER;

➔ This creates a role named HR_MANAGER and grants it permission to SELECT, INSERT, and UPDATE rows

in the EMPLOYEE table.


Common Privileges in SQL

➔ SELECT: Read data from a table or view.

➔ INSERT: Add new rows to a table.

➔ UPDATE: Modify existing rows in a table.

➔ DELETE: Remove rows from a table.

➔ EXECUTE: Execute a stored procedure or function.

➔ ALL PRIVILEGES: Grants all available privileges on the object.

You might also like