Advanced SQL and RDBMS

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson

Questions and Answers

Which database object describes any component of a database, regardless of the user who created it?

  • View
  • Schema
  • Catalog (correct)
  • Table

What is the primary function of Data Definition Language (DDL) commands in SQL?

  • Granting or revoking user privileges.
  • Managing transactions in the database.
  • Creating, altering, and dropping tables and views. (correct)
  • Updating, inserting, modifying, and querying data.

Which SQL command is used to remove a table and its associated data and definitions from a database?

  • DELETE TABLE
  • ERASE TABLE
  • DROP TABLE (correct)
  • REMOVE TABLE

What does establishing a referential integrity constraint between two tables accomplish?

<p>It makes the primary key on one side corresponds to a value on the other side. (D)</p> Signup and view all the answers

What is the effect of using ON DELETE CASCADE when defining a foreign key constraint?

<p>It automatically deletes related records in the child table when a record is deleted from the parent table. (D)</p> Signup and view all the answers

What is a 'view' in SQL?

<p>A virtual table based on the result-set of a SELECT query. (B)</p> Signup and view all the answers

How do views enhance database security?

<p>By restricting users to only see specific rows and columns of data. (C)</p> Signup and view all the answers

In SQL, what is the main purpose of using JOIN operations?

<p>To combine rows from two or more tables based on a related column. (B)</p> Signup and view all the answers

What is the difference between an INNER JOIN and a LEFT OUTER JOIN?

<p>An INNER JOIN returns only matching rows, while a LEFT OUTER JOIN returns all rows from the left table and matching rows from the right table. (D)</p> Signup and view all the answers

What is the purpose of a UNION operator in SQL?

<p>To combine the result sets of two or more <code>SELECT</code> statements into a single result set. (C)</p> Signup and view all the answers

What is a key characteristic of using the UNION ALL operator compared to UNION?

<p><code>UNION ALL</code> includes duplicate rows, while <code>UNION</code> returns only distinct rows. (C)</p> Signup and view all the answers

What distinguishes a subquery from a regular query in SQL?

<p>A subquery is a query nested inside another SQL query, while a regular query stands alone. (D)</p> Signup and view all the answers

What is a noncorrelated subquery?

<p>A subquery that does not depend on any values from the outer query. (A)</p> Signup and view all the answers

What is the key difference between a correlated and a non-correlated subquery?

<p>Correlated subqueries refer to columns in the outer query, while non-correlated subqueries do not. (D)</p> Signup and view all the answers

Which characteristic describes a stored procedure?

<p>It is a segment of SQL code stored in the database catalog. (D)</p> Signup and view all the answers

How do stored procedures improve application performance?

<p>By reducing network traffic between the application and database server. (A)</p> Signup and view all the answers

What is a disadvantage of using stored procedures?

<p>They only contain declarative SQL (and are difficult to debug). (A)</p> Signup and view all the answers

What SQL command is used to execute a stored procedure?

<p>CALL (B)</p> Signup and view all the answers

Which of the following is true about variables declared inside a stored procedure?

<p>They are local in scope and only exist during the execution of the stored procedure. (C)</p> Signup and view all the answers

In the context of stored procedures, what does an OUT parameter signify?

<p>A parameter used to return data from the stored procedure. (A)</p> Signup and view all the answers

What is the purpose of the DETERMINISTIC characteristic when creating a stored function?

<p>It indicates that the function always returns the same result for the same input values. (A)</p> Signup and view all the answers

What is the key distinction between a stored procedure and a stored function?

<p>A stored procedure can return multiple values, while a stored function can only return a single value. (C)</p> Signup and view all the answers

What is the purpose of SQL triggers?

<p>To automatically execute a set of SQL statements in response to an event on a database table. (A)</p> Signup and view all the answers

Which type of trigger is executed before an update operation is performed on a table?

<p>BEFORE UPDATE trigger (A)</p> Signup and view all the answers

What is a potential disadvantage of using SQL triggers?

<p>They can increase the workload on the database server and slow down system performance. (C)</p> Signup and view all the answers

What is the purpose of the IF-THEN-ELSE statement in SQL stored procedures?

<p>To execute different SQL statements based on a specified condition. (D)</p> Signup and view all the answers

What is the function of a CASE statement in SQL?

<p>To make the code more readable and efficient. (C)</p> Signup and view all the answers

Which SQL statement allows you to execute one or more statements repeatedly?

<p>LOOP (A)</p> Signup and view all the answers

What is the function of the LEAVE statement within a SQL loop?

<p>To exit the loop entirely. (D)</p> Signup and view all the answers

Which of the following best describes a 'catalog' in the SQL environment?

<p>A description of any object that is a part of the database, regardless of who created it. (B)</p> Signup and view all the answers

What is the purpose of Data Control Language (DCL) commands in SQL?

<p>To control access and permissions to the database and its objects. (D)</p> Signup and view all the answers

To establish a referential integrity constraint between two tables in a relational database, which of the following steps is essential?

<p>Defining a primary key in both tables and linking them using foreign keys. (B)</p> Signup and view all the answers

If an SQL view is created with criteria such that P_PRICE > 50.00, what happens when new products with prices greater than 50.00 are added to the underlying table?

<p>The view is dynamically updated, and the new products will automatically appear when the view is invoked. (B)</p> Signup and view all the answers

In SQL, under what circumstances is a self-join typically used?

<p>When the table is joined with itself. (B)</p> Signup and view all the answers

Consider an SQL query that includes a subquery to find customers who have placed orders ('Outer Query'). Which statement is true about the subquery's execution?

<p>The subquery is executed first and its results are used by the outer query. (D)</p> Signup and view all the answers

Why might creating a vast number of stored procedures lead to difficulties in database server management?

<p>The database server becomes overloaded in both memory and processors. (B)</p> Signup and view all the answers

Which type of stored procedure parameter is used to pass values both into and out of the procedure?

<p>INOUT (C)</p> Signup and view all the answers

When creating stored functions, the DETERMINISTIC characteristic should be used under which of the following conditions?

<p>When there is a need for a function that is expected to return the same output. (D)</p> Signup and view all the answers

What is the primary benefit of using SQL Triggers in database management?

<p>SQL Triggers executes specific tasks whenever a specific action is executed. (A)</p> Signup and view all the answers

In SQL, what is the purpose of the WHILE loop statement in stored procedures?

<p>To define a block of SQL code that runs repeatedly. (A)</p> Signup and view all the answers

Flashcards

Relational DBMS (RDBMS)

A data management system that implements a relational data model, where data are stored in tables.

Catalog

It describes any object that is a part of the database, regardless of which user created that object.

Schema

A collection of related objects, including tables, views, domains, constraints, character sets, triggers, and roles.

Data Definition Language (DDL)

SQL commands used to create, alter and drop tables, views and indexes.

Signup and view all the flashcards

Data Manipulation Language (DML)

SQL commands used for updating, inserting, modifying, and querying data in the database.

Signup and view all the flashcards

Data Control Language (DCL)

SQL commands to grant or revoke privileges to access the database or specific objects.

Signup and view all the flashcards

CREATE TABLE

Defines a new table and its columns, can be a base or derived table.

Signup and view all the flashcards

CREATE VIEW

Defines a logical table from one or more tables or views, with limitations on updating data.

Signup and view all the flashcards

DROP TABLE

Destroys a table along with its definition, contents, constraints, views and indexes.

Signup and view all the flashcards

ALTER TABLE

Modify the definition of an existing base table by adding, dropping, or changing a column or constraint.

Signup and view all the flashcards

SQL REFERENCES Clause

Ensures that foreign key values exist in the referenced primary key column; prevents invalid foreign key values.

Signup and view all the flashcards

ON UPDATE CASCADE

Automatically updates corresponding child table records when a parent table's primary key is updated.

Signup and view all the flashcards

ON UPDATE SET NULL

Sets the foreign key values in the child table to NULL when the corresponding primary key in the parent table is updated.

Signup and view all the flashcards

ON DELETE RESTRICT

Prevents deletion of a record if matching records exist in a related table.

Signup and view all the flashcards

ON DELETE CASCADE

Removing customer removes the associated order records from Order_T

Signup and view all the flashcards

ON DELETE SET NULL

Sets the order records for a customer to null if the parent record is deleted

Signup and view all the flashcards

View

Virtual table based on a SELECT query that dynamically updates when invoked.

Signup and view all the flashcards

Base Tables

The tables upon which a view is based.

Signup and view all the flashcards

Join

Combines tables on common attributes to retrieve data from more than one table.

Signup and view all the flashcards

INNER JOIN

Returns records that have matching values in both tables.

Signup and view all the flashcards

LEFT (OUTER) JOIN

Returns all records from the left table and matched records from the right table.

Signup and view all the flashcards

RIGHT (OUTER) JOIN

Returns all records from the right table and matched records from the left table.

Signup and view all the flashcards

FULL (OUTER) JOIN

Returns all records when there is a match in either left or right table.

Signup and view all the flashcards

Self Join

A regular join where a table is joined with itself.

Signup and view all the flashcards

UNION operator

Combines the result-set of two or more SELECT statements with the same number and types of columns.

Signup and view all the flashcards

UNION ALL

Includes duplicate values when combining result-sets.

Signup and view all the flashcards

Subquery

A query inside another query (SELECT statement).

Signup and view all the flashcards

Noncorrelated Subquery

Executed once for the entire outer query.

Signup and view all the flashcards

Correlated Subquery

Executed once for each row returned by the outer query.

Signup and view all the flashcards

Stored Procedure

A segment of declarative SQL code stored in the database catalog, invoked by programs or triggers.

Signup and view all the flashcards

Recursive Stored Procedure

A stored procedure that calls itself.

Signup and view all the flashcards

Advantages of Stored Procedures

Increases performance of application and reduces traffic between app and database server.

Signup and view all the flashcards

Disadvantages of Stored Procedures

Make database server high load in both memory and processors

Signup and view all the flashcards

Variables

Used in stored procedures to store immediate results.

Signup and view all the flashcards

Variable Scope

Determines where a variable is accessible.

Signup and view all the flashcards

Stored Procedure Parameters

Allow stored procedures to be more flexible and useful as input and/or out parameters.

Signup and view all the flashcards

IN Parameter

It takes a parameter as input, such as an attribute. The calling program has to pass an argument to the stored procedure, this parameter's value is always protected.

Signup and view all the flashcards

OUT Parameter

Pass a parameter as output where its value can be changed inside the stored procedure, and the new value is passed back to the calling program

Signup and view all the flashcards

INOUT Parameter

Combination of IN and OUT parameters, means the calling program can pass the argument, and the procedure can modify it, then pass it back to the caller.

Signup and view all the flashcards

Stored Function

A special kind stored program that returns a single value.

Signup and view all the flashcards

Study Notes

Introduction to Advanced SQL

  • The importance of SQL in database architecture is less obvious to application users due to relational DBMSs and application generators.
  • Many database application users lack direct SQL knowledge.
  • SQL-based relational database applications consist of a user interface, database tables, and an SQL-capable Relational Database Management System (RDBMS).
  • SQL is used within the RDBMS to create tables, translate user requests, maintain the data dictionary and system catalog, update tables, ensure security, and perform backups/recovery.
  • A relational DBMS implements a relational data model, stores data in tables, and represents relationships via common values.

SQL Environment and Commands

  • The SQL environment aligns with the SQL:200n standard.
  • A catalog contains each database; it describes every database object, regardless of the creator.
  • Companies maintain multiple database versions; PROD_C represents the production version which captures real business data.
  • A schema is a collection of related objects like tables, views, domains, constraints, character sets, triggers, and roles.
  • An information schema within each catalog contains descriptions of all schemas, tables, views, attributes, privileges, constraints and domains.
  • The DBMS maintains the catalog based on SQL commands; users can browse catalog contents by using SQL SELECT statements.
  • Data Definition Language, Data Manipulation Language and Data Control Language are the SQL commands classifications.
  • DDL commands create, alter, and drop tables, views, and indexes.
  • DML commands update, insert, modify, and query database data.
  • DCL commands allow a DBA to control database access by granting or revoking privileges, and managing transactions.

Defining and Generating SQL Databases

  • You may not be allowed to create a database due to system storage allocation.
  • Database creation privileges are reserved for the database administrator in some systems.
  • Command Structure: CREATE SCHEMA database_name; AUTHORIZATION owner_user id
  • Several SQL DDL CREATE commands are included in SQL:200n

DDL CREATE Command Functions:

  • CREATE SCHEMA defines the portion of a database owned by a particular user.
  • Schemas are dependent on a catalog and contain schema objects.
  • Schema objects include base tables and views, domains, constraints, assertions, character sets, and collations
  • CREATE TABLE defines a new table (base or derived) and its columns.
  • Tables are dependent on a schema
  • Derived tables are created by executing a query of tables or views.
  • CREATE VIEW defines a logical table from one or more tables or views.
  • Views cannot be indexed.
  • Updated views transfer changes to the referenced base tables.
  • DDL CREATE commands can be reversed by using a DROP command.
  • The DROP TABLE tablename command destroys a table and its definition, contents, constraints, views, and indexes.
  • ALTER TABLE adds, drops, or changes a column in an existing base table.

Creating Tables and Data Integrity Controls

  • Once the data model is designed and normalized, the SQL CREATE TABLE command defines the columns for each table.
  • Syntax: CREATE TABLE Customer_T (CustomerlD NUMBER(11,0) NOT NULL, CustomerName VARCHAR2(25) NOT NULL, CustomerAddress VARCHAR 2(30), CustomerCity VARCHAR 2(20), Customer State CHAR (2), CustomerPostal Code VARCHAR 2(9), CONSTRAINT Customer_PK PRIMARY KEY (CustomerID));"
  • Syntax establishes foreign keys to establish referential integrity between two tables with a 1:M relationship.
  • Referential integrity means that a value in the matching column on the many side must correspond to a value in the primary key, or be NULL.
  • The SQL REFERENCES clause prevents a foreign key value from being added if it's not a valid value in the referenced primary key.
  • ON UPDATE CASCADE passes changes through to child tables.
  • ON UPDATE SET NULL changes the CustomerID value in the Order_T table to NULL if the Customer_T table is updated.
  • ON DELETE RESTRICT prevents customer record deletion if there are orders from that customer.
  • With DELETE CASCADE, removing a customer removes all associated order records.
  • ON DELETE SET NULL sets the order records for that customer to null.
  • ON DELETE SET DEFAULT sets the order records for that customer to a default value.
  • Update and delete permissions may be revoked if the SQL RDBMS does not provide for primary key referential integrity.

Views

  • A view is a virtual table based on a SELECT query.
  • The query may extract columns, computed columns, aliases, and aggregate functions from one or more base tables.
  • The CREATE VIEW command creates a view.
  • Syntax: CREATE VIEW viewname AS SELECT query
  • The CREATE VIEW statement is a data definition command that stores the subquery specification in the data dictionary.
  • Views can be used wherever a table name is expected in a SQL statement.
  • They are dynamically updated (re-created on demand).
  • Views supply a certain level of security in the database by restricting the users to specified columns and rows.
  • Views may be used as the basis for reports.

Joining and Combining Database Tables

  • Joining tables on common attributes is a key aspect of relational databases.
  • A join is performed to retrieve data from more than one table at a time.

SQL JOIN Types:

  • (INNER) JOIN: Returns records with matching values in both tables.
  • LEFT (OUTER) JOIN: Returns all records from the left table and matched records from the right table.
  • RIGHT (OUTER) JOIN: Returns all records from the right table and the matched records from the left table.
  • FULL (OUTER) JOIN: Returns all records when there is a match in either the left or right table.
  • The inner join keyword selects records with matching values in both tables.
  • The left join keyword returns all records from the left table and the matched records from the right table; if there is no match, the result from the right side is NULL.
  • The right join keyword returns all records from the right table and the matched records from the left table; if there is no match, the result from the left side is NULL.
  • The full outer join keyword returns all records when there is a match in either the left or right table.
  • a self JOIN is where the table is joined with itself.
  • The UNION operator combines the result-set of two or more SELECT statements. Each SELECT statement within UNION must have the same number of columns with similar data types in the same order.
  • UNION only selects distinct values by default; use UNION ALL to allow duplicate values.

Subqueries

  • Joins are used to get information from two or more tables.
  • Example: SELECT INV_NUMBER, INVOICE.CUS_CODE, CUS_LNAME, CUS_FNAME FROM CUSTOMER, INVOICE WHERE CUSTOMER.CUS_CODE = INVOICE.CUS_CODE;
  • Subqueries can process data based on other data.
  • Example: To generate a list of vendors who provide products, use SELECT V_CODE, V_NAME FROM VENDOR WHERE V_CODE NOT IN (SELECT V_CODE FROM PRODUCT);
  • A subquery is a query (SELECT statement) inside a query, normally expressed inside parentheses
  • The first query in the SQL statement is the outer query; the query inside is the inner query.
  • The inner query executes first, is used as input for the outer query.
  • The entire SQL statement is sometimes called a nested query.
  • Subqueries can be noncorrelated (executed once for the entire outer query) or correlated (executed once for each row returned by the outer query).
  • Noncorrelated Subqueries do not depend on data from the outer query and are executed once for the entire outer query.
  • Correlated Subqueries makes use of data from the outer query, executes once for each row of the outer query, and can use the EXISTS operator.

Stored Procedures

  • A stored procedure is a segment of declarative SQL code stored in the database catalog.
  • It is invoked by programs, triggers, or other stored procedures.
  • Stored procedures calling themselves are recursive.
  • A stored procedure or function is stored within the database and compiled when used.
  • Stored procedures can receive input parameters and can return results.
  • Stored procedures can be called from standard and scripting languages or the SQL command prompt.
  • Stored procedures increase application performance, reduce traffic between application and database server, can be resued, and are secure.
  • Potential downsides includes high database server load in both memory and processors, only supporting declarative SQL, being difficult to debug, and possibly complex to write and maintain
  • Basic Syntax: DELIMITER // CREATE PROCEDURE name_of_proc() BEGIN <SQL Command> DELIMITER ;
  • Stored procedures contains variables to store immediate results.
  • Syntax: DECLARE variable_name datatype(size) DEFAULT default_value;
  • Variables can be declared together if they have the same data type.
  • The SET statement can assign other values to a variable.
  • Besides SET, the SELECT INTO statement can assign a query result to a variable.
  • Syntax: DECLARE total_products INT DEFAULT 0; SELECT COUNT(*) INTO total_products FROM products ;

Stored Procedures Parameters and Scope

  • A variable declared inside a stored procedure is out of scope when its END is reached.
  • A variable inside a block BEGIN/END is out of scope when its END is reached.
  • The variable is only effective in its scope if you can declare two variables with the same name in different scopes
  • A variable with the ‘@' prefix is a session variable that exists until the session ends.
  • Stored procedures that require parameters are more flexible and useful.

MySQL Parameters:

  • IN is the default mode, it receives parameters as input like an attribute.
  • The calling program must pass an argument to the stored procedure
  • This parameter's value is always protected.
  • OUT is used to pass a parameter as output and its value can be changed inside the stored procedure.
  • The new value is passed back to the calling program.
  • A procedure cannot access the OUT parameter's initial value when it starts.
  • INOUT combines IN and OUT parameters.
  • The calling program passes the argument; the procedure can modify it and pass the new value back.

Dropping, Functions and the Function Syntax

  • DROP PROCEDURE <name of proc> deletes a procedure.
  • A function can be called from inside a statement, and returns a scalar value.
  • A stored function is special as it returns a single value.
  • Stored functions encapsulate common formulas or business rules that are reusable among SQL statements or stored programs.
  • Stored functions can be used in SQL statements wherever an expression is valid.
  • Syntax: DELIMITER $$ CREATE FUNCTION function_name( param1, param2,...) RETURNS datatype [NOT] DETERMINISTIC
  • First, specify the name with the CREATE FUNCTION keywords.
  • List the parameters inside parentheses after the function name (all parameters are IN by default).
  • The RETURNS statement specifies the data type of the return value.
  • Determine if the function is deterministic, use the DETERMINISTIC keyword.
  • The body of the function goes in the BEGIN END block, inside which needs a RETURN statement.
  • Deterministic functions always return the same result for the same inputs, deterministic functions may return different results.

Calling a Stored Function and Deterministic Functions

  • You pass parameters by listing them inside the parenthesis with a select statement
  • Deterministic functions return the same result any time they are called with a specific set of input values
  • ABS, ACOS, ASIN, ATAN, ATN2, CEILING, COALESCE, COS, COT, DATALENGTH, DATEADD, DATEDIFF, DAY, DEGREES, EXP, FLOOR, ISNULL, ISNUMERIC, LOG, LOG10, MONTH, NULLIF, POWER, RADIANS, ROUND, SIGN, SIN, SQUARE, SQRT, TAN, YEAR are deterministic functions
  • Nondeterministic functions return different results each time they are called even if their inputs are the same values.
  • @@CONNECTIONS, @@CPU_BUSY, @@DBTS, @@IDLE, @@IO_BUSY, @@MAX_CONNECTIONS, @@PACK_RECEIVED, @@PACK_SENT, @@PACKET_ERRORS, @@TIMETICKS, @@TOTAL_ERRORS, @@TOTAL_READ, @@TOTAL_WRITE, CUME_DIST, CURRENT_TIMESTAMP, DENSE_RANK, FIRST_VALUE, GETDATE, GETUTCDATE, GET_TRANSMISSION_STATUS, LAG, LAST_VALUE, LEAD, MIN_ACTIVE_ROWVERSION, NEWID, NEWSEQUENTIALID, NEXT VALUE FOR, NTILE, PARSENAME, PERCENTILE_CONT, PERCENTILE_DISC, PERCENT_RANK, RAND, RANK, ROW_NUMBER, TEXTPTR are examples of Nondeterministic Functions

SQL Triggers

  • SQL statements or a set of SQL statements activate when an event occurs with a database table are SQL Triggers.
  • Events include INSERT, UPDATE, and DELETE.
  • Triggers are special stored procedures with procedural code.
  • Triggers can check integrity, catch business logic errors at the database level.
  • Triggers run scheduled tasks allowing tasks before or after database changes.
  • It is useful to audit data changes.
  • Extended validation is only provided and cannot replace all validations by triggers.
  • SQL Triggers execute invisibly from client-application which connects to the database server so it is difficult to figure out what happen underlying database layer.
  • SQL Triggers run every updates made to the table therefore it adds workload to the database and cause system runs slower

Types of Triggers:

  • Before Update Trigger is invoked before an update is executed.
  • After Update Trigger is invoked after an update occurs.
  • Before Insert Trigger is invoked before a new insert is executed.
  • After Insert Trigger gets invoked after an insert is implemented.
  • Before Delete Trigger is invoked before a delete statement is implemented.
  • After Delete Trigger is invoked after a delete operation is implemented.

Conditional Statements in MySQL

  • The IF statement has three forms: IF - THEN, IF-THEN-ELSE, IF-THEN-ELSEIF-ELSE
  • The IF-THEN statement executes SQL statements based on a condition.
  • The IF-THEN-ELSE statement executes other statements when the IF branch's condition is FALSE.
  • The IF-THEN-ELSEIF-ELSE statement executes statements conditionally based on multiple conditions.

The CASE Statement

  • An alternative conditional statement to IF, the CASE statement helps for in stored procedures.
  • CASE statements result in code that is efficient and readable.
  • CASE statements have two forms which are Simple CASE and searched CASE statements.

Looping in MySQL

  • The LOOP statement executes one or more statements repeatedly.
  • The WHILE loop executes a block of code repeatedly as long as a condition is true.
  • The REPEAT statement executes one or more statements until a search condition is true.
  • The LEAVE statement exits a labelled flow control.

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Related Documents

More Like This

Use Quizgecko on...
Browser
Browser