Slide 5: Relational query languages: SQL

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

In SQL, how does the handling of NULL values affect aggregate functions?

  • Aggregate functions typically ignore NULL values in the computation. (correct)
  • Aggregate functions automatically replace NULL values with zero before computation.
  • Aggregate functions return an error when encountering NULL values.
  • Aggregate functions include NULL values in their calculations as a distinct value.

In the context of SQL's three-valued logic, how does the NOT operator affect an UNKNOWN value?

  • It converts `UNKNOWN` to `FALSE`.
  • It returns `UNKNOWN`. (correct)
  • It converts `UNKNOWN` to `TRUE`.
  • It returns `TRUE` if `UNKNOWN`, `FALSE` if not `UNKNOWN`.

When creating a table in SQL, what is the purpose of defining a PRIMARY KEY?

  • To establish a relationship with a foreign key in another table.
  • To create an index that speeds up query performance on the specified column.
  • To specify a column that will automatically increment in value with each new row.
  • To ensure that the column or combination of columns has unique values and does not contain NULL, thus uniquely identifying each row in the table. (correct)

What is the outcome of the SQL command DROP TABLE Students?

<p>It completely removes the <code>Students</code> table, including its structure and all data. (D)</p> Signup and view all the answers

Which SQL command is used to modify the structure of an existing table?

<p>ALTER TABLE (D)</p> Signup and view all the answers

What SQL command is used to insert new data into a table?

<p>INSERT (D)</p> Signup and view all the answers

What does referential integrity in SQL ensure?

<p>That relationships between tables remain consistent. (A)</p> Signup and view all the answers

In the context of referential integrity, what does the action ON DELETE CASCADE do?

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

What type of integrity constraint is used to specify the permissible data values for a given attribute?

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

What is the purpose of an ASSERTION in SQL?

<p>To define a constraint that is not associated with any single table. (C)</p> Signup and view all the answers

What is a 'View' in SQL?

<p>A virtual table whose contents are the result of a query. (D)</p> Signup and view all the answers

What is the primary advantage of using SQL views for security?

<p>Views can hide sensitive data by displaying only certain columns from the base tables. (D)</p> Signup and view all the answers

How does a materialized view differ from a regular view?

<p>A materialized view stores the result of the view’s query as a physical table, while a regular view's query is executed every time the view is accessed. (A)</p> Signup and view all the answers

What is eager update in the context of materialized views?

<p>Updating the materialized view immediately whenever the base tables are modified. (B)</p> Signup and view all the answers

Under what condition can data in a materialized view be updated?

<p>When the keys of the base tables are part of the view definition, allowing for a one-to-one mapping to the base tables. (D)</p> Signup and view all the answers

What is a Table Function in SQL?

<p>A function that returns a table. (D)</p> Signup and view all the answers

In SQL, where can a table function be used?

<p>Only in the <code>FROM</code> clause. (C)</p> Signup and view all the answers

What is a correlated nested query in SQL?

<p>A query nested inside another query that depends on the values from the outer query for its execution. (C)</p> Signup and view all the answers

How does a correlated nested query affect performance compared to a non-correlated one?

<p>Correlated nested queries generally result in poorer performance because the inner query is executed for each row of the outer query. (B)</p> Signup and view all the answers

What is the result of including non-aggregated attributes in the SELECT list if they are not included in the GROUP BY clause?

<p>SQL will return an error if non-aggregated attributes are in the <code>SELECT</code> list without being in the <code>GROUP BY</code> clause. (C)</p> Signup and view all the answers

What is the purpose of the HAVING clause in SQL?

<p>To specify conditions on the result of a <code>GROUP BY</code> clause. (D)</p> Signup and view all the answers

Which of the following is a valid aggregate function in SQL?

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

Which SQL clause is used to sort the result-set of a query?

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

What are SQL Triggers?

<p>Functions that are executed automatically in response to certain events on a particular table or view in a database. (A)</p> Signup and view all the answers

Which of the following components must be defined for a trigger in SQL?

<p>Event, Condition, Action (B)</p> Signup and view all the answers

In the context of SQL triggers, what does REFERENCING NEW TABLE refer to?

<p>The updated version of the table after an insert, update, or delete operation. (C)</p> Signup and view all the answers

Which concept do SQL cursors enable?

<p>Tuple-at-a-time processing (D)</p> Signup and view all the answers

In SQL, what is the purpose of EXEC SQL open dbc END-EXEC when working with cursors?

<p>Opens the cursor for processing. (B)</p> Signup and view all the answers

In SQL, which operation retrieves the next row from a cursor into local program variables?

<p>FETCH (D)</p> Signup and view all the answers

Which SQL feature is designed to support recursion directly within SQL queries?

<p>The <code>WITH</code> clause (B)</p> Signup and view all the answers

What is the significance of DISTINCT in a SELECT statement?

<p>It ensures that the output table does not contain duplicate rows. (A)</p> Signup and view all the answers

What happens if a KEY is part of the projection list when using the DISTINCT keyword?

<p><code>DISTINCT</code> has no effect, as the key guarantees uniqueness. (C)</p> Signup and view all the answers

What is the difference between bags and sets in the context of SQL?

<p>SQL is based on <code>bags</code> by default, not <code>sets</code>. (D)</p> Signup and view all the answers

Which of the following is an example of a tuple variable in SQL?

<p><code>S</code> from <code>Students S</code> (C)</p> Signup and view all the answers

Given the query Select DISTINCT S.name, S.gpa From Students S Where S.age < 21, what does the Where clause represent?

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

Flashcards

SQL

A standard query language used since 1986

Declarative Language

Specifies what you want, not how to get it

DISTINCT keyword

Output table should not contain duplicates

Null value in SQL

Means missing value or unknown

Signup and view all the flashcards

Three-Valued Logic

Logic with true, false, and unknown values

Signup and view all the flashcards

CREATE TABLE

SQL command to make a new table

Signup and view all the flashcards

DROP TABLE

SQL command to remove a table

Signup and view all the flashcards

ALTER TABLE

SQL command to add a new column

Signup and view all the flashcards

INSERT INTO

SQL Command to add new row

Signup and view all the flashcards

UPDATE

SQL command to update an existing value

Signup and view all the flashcards

DELETE FROM

SQL Command to delete a table

Signup and view all the flashcards

Integrity Constraints

Rules to maintain data quality

Signup and view all the flashcards

Domain Constraints

Data values permitted in an attribute

Signup and view all the flashcards

Key Constraints

Combination of attribute values is unique the entire table

Signup and view all the flashcards

Referential Integrity

Foreign key values must match primary key values.

Signup and view all the flashcards

CHECK

SQL command to check validity of conditions.

Signup and view all the flashcards

ASSERTION

SQL command not associated with any one table

Signup and view all the flashcards

View

Virtual relation derived from the select statement.

Signup and view all the flashcards

Materialized View

Evaluate view to create a persistent table.

Signup and view all the flashcards

Eager Update

Updates views when base tables change immediately

Signup and view all the flashcards

Lazy Update

Updates views later accumulate updates.

Signup and view all the flashcards

Table Function

Can only be used in FROM clause

Signup and view all the flashcards

Nested Query

Query within another query

Signup and view all the flashcards

Correlated Nested Query

Inner query depends on outer one

Signup and view all the flashcards

Aggregate Operators

Finds sum, count, avg, min, max

Signup and view all the flashcards

Group By

Group rows with same values.

Signup and view all the flashcards

Having Clause

Excludes some groups

Signup and view all the flashcards

Triger

Executes when events happen

Signup and view all the flashcards

With Clause

Local fly views

Signup and view all the flashcards

SQL Cursor

Process one tuple at a time.

Signup and view all the flashcards

Study Notes

  • SQL, or Structured Query Language, is a standard language for relational databases since 1986.
  • SQL is declarative; the user states what they want without specifying how to evaluate it.
  • It builds on Tuple Relational Calculus, using variables that refer to tuples.
  • The basic structure of an SQL query involves specifying what to SELECT, FROM where, and specify WHERE.

DISTINCT Keyword

  • The "DISTINCT" keyword in SQL is optional. The output table should not contain duplicates. The default is to include duplicates
  • SQL is based on bags, allowing duplicate tuples, unlike Relational Algebra, based on sets.
  • Using "DISTINCT" can be expensive, as it needs to eliminate duplicate tuples.
  • If a 'Key' is part of the projection list, then "DISTINCT" has no effect as the key will always be unique.

SQL Features Outline

  • SQL features include Null values, three-valued logic, creating/altering tables, data manipulation, integrity constraints, views, scalar/table functions, nested queries, grouping/aggregation, and triggers.

SQL Null Values

  • Nulls in SQL represent a missing value, an unknown value, or that a value does not exist or is not applicable.
  • Handling Nulls in SQL complicates things.
  • Aggregate functions in SQL ignore null values and could return null instead.
  • When there are nulls involved with a predicate, it may evaluate to True, False, or Null.

SQL Three-Valued Logic

  • SQL uses three-valued logic which includes True, False, and Unknown.
  • OR truth table:
    • Unknown OR True = True, Unknown OR False = Unknown, Unknown OR Unknown = Unknown
  • AND truth table:
    • True AND Unknown = Unknown, False AND Unknown = False, Unknown AND Unknown = Unknown
  • NOT truth table:
    • NOT Unknown = Unknown
  • SQL predicates with an unknown value will evaluate to true.

Relational Database Schema Examples

  • Students(sid: string, name: string, login: string, age: integer, gpa: real)
  • Courses(cid: string, cname: string, credits: integer)
  • Enrolled(sid: string, cid: string, grade: string)
  • Instructor(iid: string, iname: string, irank: string, isalary: real)
  • Teaches(iid: string, cid: string, year: integer, semester: string)

Creating Tables

  • Table Creation Example:
    • CREATE TABLE Students (sid CHAR(20), name CHAR(20), login CHAR(10), age INTEGER, gpa REAL, PRIMARY KEY SID);
    • CREATE TABLE Enrolled (sid CHAR(20), cid CHAR(20), grade CHAR(2), PRIMARY KEY (sid, cid), FOREIGN KEY (sid) REFERENCES Students ON DELETE CASCADE ON UPDATE SET DEFAULT, FOREIGN KEY (cid) REFERENCES Courses ON DELETE CASCADE ON UPDATE CASCADE);
  • Additional options for CREATE TABLE include:
    • ON DELETE REJECT
    • UNIQUE (cid, grade)

Deleting/Altering Tables

  • To delete a table, DROP TABLE Students.
  • To add an attribute to a table: ALTER TABLE Students ADD COLUMN GraduationYear: integer.
  • A default value can be set when altering tables.

Data Manipulation

  • Tuples can be inserted into a table:
    • INSERT INTO Students (sid, name, login, age, gpa) VALUES (0111, 'Bright, Mary', '[email protected]', 22, 4.0).
  • Bulk inserts are possible, selecting from another table.
  • Deleting tuples that satisfy a predicate
    • DELETE FROM Students S WHERE S.name = 'Bright, Mary'.
  • Attributes inside a table can be updated
    • UPDATE Instructors SET isalary = isalary * 1.05 WHERE irank = "B".

Integrity Constraints

  • Integrity Constraints (ICs) protect data and must be true at all times in the database.
  • You can not detect if the data is true, as long as the IC's are satisfied, but you can detect if data is wrong
  • They are a strong feature in SQL associated with the data definition, not the program logic.
  • ICs are specified when a schema is defined and are always verified by the system.
  • Checks occur whenever the relation is modified or updated, adding execution overhead.

Types of Integrity Constraints

  • Domain Constraints: Permissible data values for an attribute.
  • Key Constraints: Unique combinations of attribute values; includes primary and unique key constraints.
  • Referential Integrity Constraints (Foreign Key Constraints): ensures that every foreign key value matches a primary key value in another relation; avoids dangling pointers.

Referential Integrity

  • Ensures foreign key values point to valid primary key values.
  • It should address what should happen when a primary key value is deleted or updated via integrity constraints.
  • Database specifications should be explicit such as: "CREATE" table definitions, "Foreign key" references, "On Delete Reject" or "On update cascade" or "On delete set default" etc

General Constraints

  • General constraints check general conditions:
    • CREATE TABLE Students (sid CHAR(20), name CHAR(20), login CHAR(10), age INTEGER, gpa REAL, PRIMARY KEY SID, CHECK gpa >= 0.0 and gpa <=4.0);
  • The CHECK condition can contain Select statements.
  • ASSERTION is not associated with any one table
    • Create Assertion Student-InstructorRatio(Check ((select count() from students) / (select count() from instructors) < 15))
  • Assertions come with a performance implication, as these need to be rechecked with every update.

Views

  • A view is a relation stored by saving the Select Statement in system catalogs: CREATE VIEW BrightStudents (name, gpa) AS SELECT name, gpa FROM Students WHERE gpa > 3.6 ORDER BY gpa desc.
  • Add LIMIT 3 to get the top 3 students in BrightStudents table
  • Views increase security (data protection) by hiding sensitive information.
  • Replacing security attributes could lead to nested queries
  • Replacing attributes may not be very efficient.

Materialized Views

  • Instead of saving the view expression, the view select statement is evaluated with the result materialized and stored as a regular table.
  • CREATE MATERIALIZED VIEW ....
  • A form of redundancy with the materialized view is partly replicated in the base tables.

Base Table Updated Effects

  • Eager Update of materialized views mean whenever base tables are updated, the views must be updated immediately which leads to an overhead.
  • Lazy Update of materialized views means whenever base tables are updated, the updates are stored and accumulated in delta tables. The view tables themselves are updated eagerly. When a query happens the delta tables are related and propagated, and then the view is evaluated

Updating Materialized View Data

  • To update data means the view must translate the unambiguous update of the (base) relations in the database
  • Thus, tuples will have a one-to-one mapping, making updates possible, as long as the user has the permissions. Otherwise, the update is denied.

Scalar and Table Functions

  • They are user-defined functions that are defined in SQL "CREATE FUNCTION .. RETURNS TABLE/INTEGER ..."
  • They return calculations based on parameters as input
  • The parameters can be scalar, or single valued from a scalar equation
  • Table Functions do the above but produce a table as an output with multiple values, and they can be inserted to a clause location or table

Nested SQL Queries

  • SELECT i.iname FROM instructors i WHERE i.iid in (select t.iid from teaches t where t.cid = "CS441");
  • SQL queries can be connected anywhere so long as it produces a table, like in the FROM statement, or as shown
  • Other locations include, IN, EXISTS, UNIQUE, OR ANY & ALL

Nested Correlated Queries

  • SELECT i.iname From instructors i WHERE exists (select * from teaches t WHERE i.iid = t.iid and t.cid = "CS441");
  • Notice that the inner query is dependent upon outer variables
  • The inner query needs to be re-evaluated for every tuple

Aggregation Operators

  • SQL aggregation operators: SUM, COUNT, AVG, MIN, MAX
  • Example: Finding the name of the youngest student requires a nested query. SELECT s1.name FROM Students s1 WHERE s1.age = (SELECT min(s2.age) FROM students s2).
  • Cannot use "Select name, min(age) from Students"

SQL Grouping

  • It is possible to find the average GPA for each group via a Select statement SELECT age, avg(gpa) FROM Students GROUP BY age.
  • The selected attribute must be listed in the "GROUP BY" clause
  • To include by the name in the GROUP BY clause, either eliminate the selected name or add it to the group by clause

Grouping and Exclusion

  • To exclude tuples from being grouped, use WHERE:
  • To specify the min student # SELECT age, avg(gpa) FROM Students where GPA >= 2 GROUP BY age.
  • To exclude groups, create a HAVING: SELECT age, avg(gpa) FROM Students WHERE GPA >= 2 GROUP BY age HAVING count(*) > 2.
  • "count(*)" computes the number of tuples within a group.

Database Search and Aggregation

  • Schemas can be used in examples such as students(str,login,age,gpa), Courses{str, credits), Enrolled(str, grade
  • Find a student in a class with max grade via this select operator "Select s.name from students s, enrolled e, courses c where c.name = 'Database Systems' and c.cid = e.cid and e.sid = s.sid and e.grade >= all (Select e1.grade from enrolled e1, courses c1 where c1.cname = 'CS441' and c1.cid = e1.cid)"
  • A shorter alternative way Select max(e1.grade)"

SQL Triggers

  • A trigger is a rule triggered to execute when some event happens
  • Defined in SQL a Create Trigger statement, and they require an event, condition, and a action
  • Syntax example "CREATE TRIGGER Young BrightStudents AFTER INSERT ON Students REFERENCING NEW TABLE NewStudents FOR EACH STATEMENT INSERT INTO Young BrightStudents (sid, name, login, age, gpa) SELECT sid, name, login, age, gpa FROM NewStudents N WHERE N.age <= 18 and N.gpa > 3.6"
  • Other options include referencing the old table, before the insert, or for each row

The With Clause

  • Defines a local view in the query
  • Can create a temporary table for the query and delete the table afterwards
  • To maximize best(maxGPA) table, select the max(gpa) from students but be sure to select the name of the gpa
  • To select name from students, create the "best" maxGPA" table to ensure that the student.gpa best.maxGPA, this makes these best scores not defined afterwards
  • Recursive queries are extremely useful

SQL Cursors

  • SQL Select queues are set-oriented, meaning they create and return data sets
  • Cursors create and use embedded SQL in a host language
  • Helps the host recognize results in a queue via tuple at a time
  • Cursor is declare from an SQL Queue

Cursor Examples

  • Declarations of "select i.name, t.year, t.sem from instructor i, teaches t, courses c where c.name = 'database system' and c.cid = t.cid, and t.id i.id forUpdate" Open statement examples "EXEC SQL open dbc End-exec"
  • To retrieve this queue for the local programmer, "Fetch into:en:,cy:cs End exec)"

Interesting Topics

  • Supporting recursion within the language how it would call itself and better evaluate it
  • Unnesting nested queries, so that a nested noncorrelsted statement might become unnested

Studying That Suits You

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

Quiz Team

Related Documents

More Like This

SQL Basics Quiz
10 questions

SQL Basics Quiz

HaleRetinalite2094 avatar
HaleRetinalite2094
Introduction to SQL Database Model
10 questions
ClassicModels SQL Exercises
26 questions
Use Quizgecko on...
Browser
Browser