Introduction to SQL

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson
Download our mobile app to listen on the go
Get App

Questions and Answers

Which SQL standard is most commonly supported by commercial database systems?

  • SQL-86
  • SQL:1999
  • SQL-92 (correct)
  • SQL-89

The SQL data definition language (DDL) is used to specify the schema for each relation, but not the integrity constraints.

False (B)

Which SQL data type is used to store variable-length character strings?

  • numeric(p,d)
  • int
  • varchar(n) (correct)
  • char(n)

In the create table command, what does the term 'integrity-constraint' refer to?

<p>Rules or conditions that ensure data validity within a table</p> Signup and view all the answers

A ______ key declaration on an attribute automatically ensures not null.

<p>primary</p> Signup and view all the answers

To ensure that all values in the name attribute of the instructor table are present, which constraint is used?

<p><code>not null</code> (B)</p> Signup and view all the answers

The delete table command removes all rows from a table, but leaves the table structure intact.

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

What is the purpose of the alter table command in SQL?

<p>Modify the existing table structure.</p> Signup and view all the answers

Match the following SQL clauses with their functions:

<p><code>select</code> = Specifies the attributes to retrieve <code>from</code> = Specifies the table(s) to retrieve data from <code>where</code> = Filters the rows based on a condition <code>distinct</code> = Eliminates duplicate rows from the result set</p> Signup and view all the answers

In SQL, what is the purpose of the * when used in a select statement?

<p>Select all attributes in the table. (D)</p> Signup and view all the answers

SQL names are case-sensitive, meaning name and Name will be treated as different attributes.

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

The ______ clause in SQL is used to specify conditions that the result must satisfy.

<p>where</p> Signup and view all the answers

Which operation combines rows from two tables into a single row?

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

How can you rename the 'salary/12' column to 'monthly_salary' in a SQL query?

<p>Use the 'as' clause.</p> Signup and view all the answers

What is the purpose of the distinct keyword in a select statement?

<p>To remove duplicate records. (C)</p> Signup and view all the answers

String comparisons in SQL using the like operator are case-insensitive.

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

The SQL operator ______ is used for string matching using patterns.

<p>like</p> Signup and view all the answers

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

<p><code>order by</code> (B)</p> Signup and view all the answers

What is the default sort order when using the order by clause?

<p>Ascending</p> Signup and view all the answers

What does numeric(8,2) specify in the create table statement?

<p>A number with a total of 8 digits, 2 of which are after the decimal point. (D)</p> Signup and view all the answers

Duplicates are automatically eliminated when using the union all operator.

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

SQL uses the keyword ______ to indicate an unknown value or that a value does not exist.

<p>null</p> Signup and view all the answers

Which predicate is used to check for null values?

<p><code>is null</code> (A)</p> Signup and view all the answers

What is the result of any arithmetic expression involving null?

<p>null</p> Signup and view all the answers

Match the Aggregate function with description.

<p><code>avg</code> = average value <code>min</code> = minimum value <code>max</code> = maximum value <code>sum</code> = sum of values</p> Signup and view all the answers

Which aggregate function is used to count the number of values in a column?

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

Aggregate functions include null values in their calculations.

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

The group by clause is used to group rows that have the same value in a specified column into ______ rows.

<p>summary</p> Signup and view all the answers

Which clause is used to filter results after grouping?

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

If a collection has only null values, what does the count function return?

<p>0</p> Signup and view all the answers

What is a subquery in SQL?

<p>A query nested inside another query. (C)</p> Signup and view all the answers

Subqueries can only appear in the where clause of a SQL statement.

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

The SQL keyword ______ is used to test whether a value is in a set of values returned by a subquery.

<p>in</p> Signup and view all the answers

What is the purpose of the exists construct in SQL?

<p>Check if subquery is non-empty</p> Signup and view all the answers

Which clause is used to specify a temporary relation in SQL?

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

The unique construct evaluates to "true" if a given subquery contains ______.

<p>no duplicates</p> Signup and view all the answers

Match the database modification operation with the correct description:

<p><code>delete</code> = Removes tuples from a relation <code>insert</code> = Adds new tuples to a relation <code>update</code> = Modifies values in tuples of a relation</p> Signup and view all the answers

Which SQL command is used to modify existing data in a table?

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

When deleting tuples based on a condition involving an aggregate function, the aggregate function is recomputed for each tuple deletion.

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

Which SQL statement is used to increase salaries of instructors by a certain percentage?

<p>update</p> Signup and view all the answers

Which of the following SQL commands is used to add new rows to a table?

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

Flashcards

What is SQL?

A language used for managing and manipulating databases.

What is DDL?

A subset of SQL used for defining data structures.

What does DDL specify?

Specifies the schema for each relation.

What is CHAR(n)?

Fixed length character string with user-specified length.

Signup and view all the flashcards

What is VARCHAR(n)?

Variable length character strings, with user-specified maximum length.

Signup and view all the flashcards

What is INT?

Integer, a finite subset of the integers that is machine-dependent.

Signup and view all the flashcards

What is SMALLINT?

Small integer - a machine-dependent subset of the integer domain type.

Signup and view all the flashcards

What is NUMERIC(p,d)?

Fixed point number, with user-specified precision and scale.

Signup and view all the flashcards

What is REAL?

Floating point numbers with machine-dependent precision.

Signup and view all the flashcards

What is CREATE TABLE?

SQL command to define a new table.

Signup and view all the flashcards

What is an Integrity Constraint?

A rule enforced on data in a table.

Signup and view all the flashcards

What does NOT NULL mean?

Specifies that an attribute cannot contain NULL values.

Signup and view all the flashcards

What is a Primary Key?

Uniquely identifies each record in a table.

Signup and view all the flashcards

What is a Foreign Key?

Establishes a link between data in two tables.

Signup and view all the flashcards

What does INSERT do?

Adds new records to a table.

Signup and view all the flashcards

What does DELETE do?

Removes records from a table.

Signup and view all the flashcards

What does DROP TABLE do?

Removes a table from the database.

Signup and view all the flashcards

What does ALTER do?

Modifies the structure of an existing table.

Signup and view all the flashcards

What does 'ALTER TABLE ADD' do?

Adds a new column to a table.

Signup and view all the flashcards

What does 'ALTER TABLE DROP' do?

Removes an attribute (column) of relation r.

Signup and view all the flashcards

What is SELECT-FROM-WHERE?

Basic structure of an SQL query.

Signup and view all the flashcards

What does SELECT do?

Clause that lists the attributes desired in the result of a query

Signup and view all the flashcards

What does DISTINCT do?

Keyword to eliminate duplicates in a query result.

Signup and view all the flashcards

What does ALL do?

Specifies that duplicates should not be removed.

Signup and view all the flashcards

What does asterisk (*) mean in SELECT?

Represents all attributes.

Signup and view all the flashcards

What does WHERE do?

Specifies conditions that the result must satisfy

Signup and view all the flashcards

What is a Cartesian Product?

Combines tables without a WHERE clause.

Signup and view all the flashcards

What is the AS clause?

SQL allows renaming relations and attributes.

Signup and view all the flashcards

What is NATURAL JOIN?

Considers only those pairs of tuples with the same value

Signup and view all the flashcards

What does LIKE do?

SQL string-matching operator for comparisons on character strings.

Signup and view all the flashcards

What is ORDER BY?

Used to sort the result-set.

Signup and view all the flashcards

What does BETWEEN do?

comparison operator to test whether a value is within a specified range.

Signup and view all the flashcards

What does INTERSECT do?

Courses that ran in both Fall 2009 and Spring 2010.

Signup and view all the flashcards

What does EXCEPT do?

Find courses that ran in Fall 2009 but not in Spring 2010

Signup and view all the flashcards

What does NULL mean?

Indicates an unknown value or that a value does not exist.

Signup and view all the flashcards

What is three-valued logic?

Three values are: True, False and Unknown.

Signup and view all the flashcards

What does IS NULL do?

Used to check for NULL values.

Signup and view all the flashcards

What are Aggregate Functions?

Functions that operate on a set of values.

Signup and view all the flashcards

What does AVG() do?

Average value

Signup and view all the flashcards

What does MIN() do?

Minimum value

Signup and view all the flashcards

What does MAX() do?

Maximum value

Signup and view all the flashcards

Study Notes

Introduction to SQL

  • SQL is a query language used to interact with databases.
  • SQL can be used for data definition, basic querying, and modification of databases.
  • SQL also supports set operations, null values, aggregate functions, and nested subqueries.

History of SQL

  • IBM developed Sequel as part of the System R project at the IBM San Jose Research Laboratory
  • Sequel was eventually renamed to Structured Query Language (SQL)
  • SQL-86 was the first ANSI and ISO standard SQL
  • Other versions: SQL-89, SQL-92, SQL:1999 (Y2K compliant), SQL:2003, and SQL:2008.
  • Commercial systems generally offer SQL-92 features, with varying feature sets from later standards and proprietary additions
  • https://dev.mysql.com/doc/refman/8.0/en/windows-installation.html is a MySQL installation link

DDL (Data Definition Language)

  • SQL's DDL allows specification of information about relations, including schema, attribute domain values, integrity constraints, and indices.

Domain Types in SQL

  • char(n): Fixed-length character string where n specifies the length.
  • varchar(n): Variable-length character string where n is the maximum length.
  • int: Integer (machine-dependent).
  • smallint: Small integer (machine-dependent subset of the integer domain).
  • numeric(p,d): Fixed-point number with user-specified precision of p digits, where d digits are to the right of the decimal point
  • real, double precision: Floating point numbers with machine-dependent precision.
  • float(n): Floating point number with user-specified precision of at least n digits.

Create Table Command

  • The create table command defines an SQL relation.
  • create table r (A1 D1, A2 D2,..., An Dn, (integrity-constraint1),...,(integrity-constraintk))
  • r is the name of the relation.
  • Ai is an attribute name in the schema of relation r.
  • Di is the data type of values in the domain of attribute Ai.
  • create table instructor (ID char(5), name varchar(20), dept_name varchar(20), salary numeric(8,2)) is an example of a table creation

Integrity Constraints in Create Table

  • not null: Ensures that an attribute cannot have a null value.
  • primary key (A1,..., An): Specifies the primary key of the table.
  • foreign key (Am,..., An) references r: Specifies a foreign key referencing another relation r.
  • create table instructor (ID char(5), name varchar(20) not null, dept_name varchar(20), salary numeric(8,2), primary key (ID), foreign key (dept_name) references department) is an example of using integrity constraints
  • A primary key declaration automatically ensures not null.

More Relation Definitions

  • create table student (ID varchar(5), name varchar(20) not null, dept_name varchar(20), tot_cred numeric(3,0), primary key (ID), foreign key (dept_name) references department(dept_name)) creates a student table

Additional Relation Definitions

  • create table takes (ID varchar(5), course_id varchar(8), sec_id varchar(8), semester varchar(6), year numeric(4,0), grade varchar(2), primary key (ID, course_id, sec_id, semester,year), foreign key (ID) references student(ID), foreign key (course_id, sec_id, semester, year) references section((course_id, sec_id, semester, year))): defines a takes table
  • sec_id can be dropped from the primary key to prevent a student from registering for two sections of the same course in the same semester.
  • create table course (course_id varchar(8), title varchar(50), dept_name varchar(20), credits numeric(2,0), primary key (course_id), foreign key (dept_name) references department(dept_name)): creates a course table.

Updates to Tables

  • insert into instructor values ('10211', 'Smith', 'Biology', 66000): Inserts a new tuple into the instructor table.
  • delete from student: Removes all tuples from the student relation.
  • drop table r: Deletes the table r.
  • alter table r add A D: Adds an attribute named A with domain D to relation r; existing tuples are assigned null for the new attribute.
  • alter table r drop A: Removes the attribute named A from relation r (not supported by all databases).

Basic Query Structure

  • select A1, A2,..., An from r1, r2,..., rm where P is a typical SQL query form.
  • Ai represents an attribute.
  • Ri represents a relation.
  • P is a predicate
  • The result of an SQL query is itself a relation.

The Select Clause

  • The select clause lists desired attributes in the query result.
  • Example: select name from instructor finds the names of all instructors.
  • SQL names are case-insensitive.
  • SQL allows duplicates in relations and query results.
  • distinct keyword eliminates duplicates like in: select distinct dept_name from instructor.
  • The all keyword specifies duplicates should not be removed like in: select all dept_name from instructor.
  • select * from instructor denotes all attributes.
  • Arithmetic expressions using +, -, *, / are allowed
  • select ID, name, salary/12 from instructor would return a relation with the salary attribute divided by 12.
  • select ID, name, salary/12 as monthly_salary uses as to rename an attribute
  • The where clause specifies conditions for the result.
  • select name from instructor where dept_name = 'Comp. Sci.' to find all instructors in Comp. Sci.
  • Comparison results are combined using logical connectives and, or, and not.
  • select name from instructor where dept_name = 'Comp. Sci.' and salary > 80000 finds instructors in 'Comp. Sci.' with salary > 80000.

Cartesian Product

  • select * from instructor, teaches: Generates every possible instructor-teaches pair with all attributes from both relations.

Examples with Joins

  • select i.name, t.course_id from instructor i, teaches t where instructor.ID = teaches.ID: finds names of all instructors who have taught a course and the course IDs.

More Query Examples

  • select i.name, t.course_id from instructor i, teaches t where i.ID = t.ID and i.dept_name = 'Art': Finds the names of all instructors in the Art department who have taught some course and the course ID.

The Rename Operation

  • Allows renaming relations and attributes using the as clause with the format old-name as new-name

Rename Operation Examples

  • select distinct T.name from instructor as T, instructor as S where T.salary > S.salary and S.dept_name = 'Comp. Sci.': finds names of instructors with a higher salary than someone in 'Comp. Sci'

Natural Join

  • Considers pairs of tuples with the same value on attributes that appear in both relations' schemas.
  • select name, course_id from instructor natural join teaches: Returns instructor names and course IDs from a natural join of instructor and teaches, which is equivalent to instructor.ID = teaches.ID.
  • select name, title from instructor natural join teaches, course where teaches.course_id = course.course_id: finds instructor names and course titles using natural join.
  • select name, title from (instructor natural join teaches) join course using (course_id): specifies the course_id attribute

String Operations

  • SQL includes a string-matching operator, like, which uses % to match any substring and _ to match any character.
  • select name from instructor where name like '%dar%': finds the names of instructors whose names include the substring "dar".
  • like '100 \\%' matches the string "100%" using backslash \ as the escape character.
  • SQL supports concatenation (using "||"), converting case, finding string length, and extracting substrings.
  • Patterns used in like are case-sensitive.
  • 'Intro%': Matches any string beginning with "Intro"
  • '%Comp%': Matches any string containing "Comp" in it
  • '___': Matches any string of exactly three characters
  • '___%': Matches any string of at least three characters

Ordering the Display of Tuples

  • select distinct name from instructor order by name: Lists names of all instructors in alphabetical order.
  • desc specifies descending order, and asc for ascending, with ascending order being the default.
  • sort on multiple attributes such as order by dept_name, name

Where Clause Predicates

  • SQL includes between comparison
  • select name from instructor where salary between 90000 and 100000: find names that have a salary between 90000 and 10000

Set Operations

  • Set operations includes union, intersect, and except and works with queries
  • union automatically eliminates duplicates; use union all operator to include them.
  • (select course_id from section where semester = 'Fall' and year = 2009) union (select course_id from section where semester = 'Spring' and year = 2010) is a SQL query for returning the union using union

Null Values

  • Tuples can have a null value to represent missing information
  • null signifies an unknown or non-existent value.
  • Arithmetic expressions involving null evaluate to null, such as 5 + null returning null.
  • The predicate is null checks for null values in select queries, e.g. select name from instructor where salary is null.
  • Comparisons with null return unknown results
  • Used in a three-valued logic with values including true, false, and unknown
  • Returns based on the truthiness of the values, example
  • (unknown or true) = true
  • (unknown or false) = unknown
  • (unknown or unknown) = unknown
  • where clause predicate is treated as false if it evaluates to unknown

Aggregate Functions

  • These functions operate on a value within a column of a relation, and return a single value
  • avg: average value
  • min: minimum value
  • max: maximum value
  • sum: sum of the values
  • count: number of values

Aggregate Functions Examples

  • select avg (salary) from instructor where dept_name= 'Comp. Sci.': computes the average salary of instructors in the Computer Science department.
  • select count (distinct ID) from teaches where semester = 'Spring' and year = 2010: finds the number of instructors who teach a course in the Spring 2010 semester.
  • select dept_name, avg (salary) as avg_salary from instructor group by dept_name: calculates average salary of instructors in each department.

Aggregate Functions & Grouping

  • Attributes in the select clause outside of aggregate functions must appear in the group by list.
  • select dept_name, avg (salary) from instructor group by dept_name: correct query for group by usage
  • predicates in the having clause are applied after forming groups whereas predicates in the where clause are applied before forming groups.
  • select dept_name, avg (salary) from instructor group by dept_name having avg (salary) > 42000: Find the names and average salaries of all departments whose average salary is greater than 42000

Null Values and Aggregates

  • select sum (salary ) from instructor ignores null salary amounts.
  • All aggregate operations except count(*) ignore tuples with null values on the aggregated attributes.
  • If a collection has only null values, count returns 0 and all other aggregates return null

Nested Subqueries

  • Allows nesting of subqueries

  • Nested subqueries follow the basic structure: select A1, A2,..., An from r1, r2,..., rm where P

  • Ai can be replaced by a subquery that generates a single value.

  • ri can be replaced by any valid subquery

  • P can be replaced with B (subquery) where B is an attribute.

Subqueries in the Where Clause

  • Used for set membership, set comparisons, set cardinality.

Set Membership

  • select distinct course_id from section where semester = 'Fall' and year= 2009 and course_id in (select course_id from section where semester = 'Spring' and year= 2010): Finds courses offered in Fall 2009 and in Spring 2010.
  • select distinct course_id from section where semester = 'Fall' and year= 2009 and course_id not in (select course_id from section where semester = 'Spring' and year= 2010): Finds course offered in fall 2009 but not in spring 2010

Set Comparison

  • Uses the some clause for comparison
  • Given by select distinct T.name from instructor as T, instructor as S where T.salary > S.salary and S.dept name = 'Biology'
  • Query using > some clause given by: select name from instructor where salary > some (select salary from instructor where dept name = 'Biology')
  • Uses the all clause for comparision
    • Find the names of all instructors whose salary is greater than the salary of all instructors in the Biology department. select name from instructor where salary > all (select salary from instructor where dept name = 'Biology');

Empty Relations Tests

  • The exists construct returns true if the argument subquery is nonempty
  • The logic for testing relations includes this syntax select course_id from section as S where semester = 'Fall' and year = 2009 and exists (select * from section as T where semester = 'Spring' and year= 2010 and S.course_id = T.course_id);
  • not exists is used to retrieve things such as employee name that has no dependents

Absence of Duplicate Tuples

  • The unique construct tests whether a subquery has any duplicate tuples in its result.
  • The unique construct evaluates to “true” if a given subquery contains no duplicates.

Subqueries in the From Clause

  • SQL allows a subquery expression to be used in the from clause
  • select dept_name, avg_salary from (select dept_name, avg (salary) as avg_salary from instructor group by dept_name) where avg_salary > 42000; Find the average instructors' salaries of those departments where the average salary is greater than $42,000.
  • Resulting subquery can be stored in a relation and the attributes in the result can be given new names

With Clause

  • The with clause provides a way of defining a temporary relation whose definition is available only to the query in which the with clause occurs.

Database Modification

  • The database can be modified through deleting, insertion and updating
  • This can be done in a variety of ways, for example, deleting from the instructor table and stating parameters such department delete from instructor where dept_name= ’Finance’
  • Insertions insert into course values (’CS-437’, ’Database Systems’, ’Comp. Sci.’, 4) And
  • Updating update instructor set salary = salary * 1.03 where salary > 100000

Studying That Suits You

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

Quiz Team

Related Documents

Use Quizgecko on...
Browser
Browser