UNIT 3 - Final
UNIT 3 - Final
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
➔ 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 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
Example:
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
➔ The SQL schema for tables is usually implicit but can be explicitly stated by prefixing the schema name
➔ 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
➔ To avoid issues, foreign key constraints can be added later using ALTER TABLE.
Attribute Data Types and Domains in SQL
➔ DECIMAL(i,j), NUMERIC(i,j): For formatted numbers, where i is the total number of digits, and j is
➔ String literals are enclosed in single quotes (case-sensitive). Fixed-length strings are padded with
➔ CLOB: For large text values like documents, specified in kilobytes, megabytes, or gigabytes (e.g.,
➔ 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.
➔ Values: TRUE, FALSE, or UNKNOWN (due to the presence of NULL in SQL, a third value, UNKNOWN, is
➔ 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).
➔ 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:
➔ 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.
➔ NOT NULL: Used to prevent NULL values for an attribute. This is implicit for primary key attributes but
➔ DEFAULT: Defines a default value for an attribute if no explicit value is provided during insertion. If no
➔ 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
➔ UNIQUE: Used to define alternate (secondary) keys, either for one or multiple attributes:
➔ 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.
➔ SET NULL: Sets foreign key values to NULL when the referenced row is deleted.
➔ 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 UPDATE CASCADE
➔ Example: In EMPLOYEE, if a supervising employee is deleted, Super_ssn is set to NULL for the
➔ 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
➔ Gradual Introduction: We'll explore features of the SELECT statement using sample queries.
➔ SQL tables can have duplicate rows, meaning they are multisets (or "bags") of tuples, unlike sets in the
➔ SQL tables can be constrained to sets if a key constraint is declared or the DISTINCT option is used in
➔ 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':
FROM EMPLOYEE
➔ 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
FROM table_name
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:
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.
FROM table_name
Example
FROM EMPLOYEE
➔ 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
FROM table_name
IN
➔ The IN operator is used to specify multiple possible values for a column. It’s an alternative to multiple
OR conditions. Syntax
FROM table_name
➔ The LIKE operator is used for pattern matching. It searches for a specified pattern in a column.
Syntax
FROM table_name
➔ In SQL, NULL represents the absence of a value or an unknown value. It's important to note that NULL
➔ NULL values do not participate in regular comparisons (e.g., NULL is not equal to NULL).
Example
➔ In an employee database, if an employee's phone number is not available, the phone number column
➔ When working with queries, you often need to account for the presence of NULL values, especially
➔ Comparison operations: Comparisons involving NULL return UNKNOWN. For example, NULL = NULL
◆ 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.
FROM table_name
FROM table_name
➔ 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
FROM table1
ON table1.column = table2.column;
FROM EMPLOYEE
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.
➔ Returns all rows from the left table and the matching rows from the right table. If there’s no match,
FROM table1
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,
FROM table1
ON table1.column = table2.column;
➔ 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.
FROM table1
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 table1
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.
➔ 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
➔ 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.
FROM table_name
WHERE condition;
➔ Once a view is created, you can use it just like a regular table in queries. You can select data from it,
FROM EmployeeView
➔ In some cases, you can update the data in the underlying tables through the view. However, not all
◆ 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
➔ This query updates the last name of the employee 'John' in the EmployeeView. The change will affect
➔ 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
➔ 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
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.
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.
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
AFTER|BEFORE INSERT|UPDATE|DELETE
ON table_name
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
OPEN cursor_name;
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
➔ 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.
➔ privilege_type: The type of action allowed (e.g., SELECT, INSERT, UPDATE, DELETE).
➔ 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
➔ privilege_type: The permission being revoked (e.g., SELECT, INSERT, UPDATE, DELETE).
➔ 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
Creating Roles
Example
➔ This creates a role named HR_MANAGER and grants it permission to SELECT, INSERT, and UPDATE rows