Podcast
Questions and Answers
Which SQL standard is most commonly supported by commercial database systems?
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.
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?
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?
In the create table
command, what does the term 'integrity-constraint' refer to?
A ______ key declaration on an attribute automatically ensures not null
.
A ______ key declaration on an attribute automatically ensures not null
.
To ensure that all values in the name
attribute of the instructor
table are present, which constraint is used?
To ensure that all values in the name
attribute of the instructor
table are present, which constraint is used?
The delete table
command removes all rows from a table, but leaves the table structure intact.
The delete table
command removes all rows from a table, but leaves the table structure intact.
What is the purpose of the alter table
command in SQL?
What is the purpose of the alter table
command in SQL?
Match the following SQL clauses with their functions:
Match the following SQL clauses with their functions:
In SQL, what is the purpose of the *
when used in a select
statement?
In SQL, what is the purpose of the *
when used in a select
statement?
SQL names are case-sensitive, meaning name
and Name
will be treated as different attributes.
SQL names are case-sensitive, meaning name
and Name
will be treated as different attributes.
The ______ clause in SQL is used to specify conditions that the result must satisfy.
The ______ clause in SQL is used to specify conditions that the result must satisfy.
Which operation combines rows from two tables into a single row?
Which operation combines rows from two tables into a single row?
How can you rename the 'salary/12' column to 'monthly_salary' in a SQL query?
How can you rename the 'salary/12' column to 'monthly_salary' in a SQL query?
What is the purpose of the distinct
keyword in a select
statement?
What is the purpose of the distinct
keyword in a select
statement?
String comparisons in SQL using the like
operator are case-insensitive.
String comparisons in SQL using the like
operator are case-insensitive.
The SQL operator ______ is used for string matching using patterns.
The SQL operator ______ is used for string matching using patterns.
Which SQL clause is used to sort the result-set of a query?
Which SQL clause is used to sort the result-set of a query?
What is the default sort order when using the order by
clause?
What is the default sort order when using the order by
clause?
What does numeric(8,2)
specify in the create table
statement?
What does numeric(8,2)
specify in the create table
statement?
Duplicates are automatically eliminated when using the union all
operator.
Duplicates are automatically eliminated when using the union all
operator.
SQL uses the keyword ______ to indicate an unknown value or that a value does not exist.
SQL uses the keyword ______ to indicate an unknown value or that a value does not exist.
Which predicate is used to check for null values?
Which predicate is used to check for null values?
What is the result of any arithmetic expression involving null
?
What is the result of any arithmetic expression involving null
?
Match the Aggregate function with description.
Match the Aggregate function with description.
Which aggregate function is used to count the number of values in a column?
Which aggregate function is used to count the number of values in a column?
Aggregate functions include null values in their calculations.
Aggregate functions include null values in their calculations.
The group by
clause is used to group rows that have the same value in a specified column into ______ rows.
The group by
clause is used to group rows that have the same value in a specified column into ______ rows.
Which clause is used to filter results after grouping?
Which clause is used to filter results after grouping?
If a collection has only null
values, what does the count
function return?
If a collection has only null
values, what does the count
function return?
What is a subquery in SQL?
What is a subquery in SQL?
Subqueries can only appear in the where
clause of a SQL statement.
Subqueries can only appear in the where
clause of a SQL statement.
The SQL keyword ______ is used to test whether a value is in a set of values returned by a subquery.
The SQL keyword ______ is used to test whether a value is in a set of values returned by a subquery.
What is the purpose of the exists
construct in SQL?
What is the purpose of the exists
construct in SQL?
Which clause is used to specify a temporary relation in SQL?
Which clause is used to specify a temporary relation in SQL?
The unique
construct evaluates to "true" if a given subquery contains ______.
The unique
construct evaluates to "true" if a given subquery contains ______.
Match the database modification operation with the correct description:
Match the database modification operation with the correct description:
Which SQL command is used to modify existing data in a table?
Which SQL command is used to modify existing data in a table?
When deleting tuples based on a condition involving an aggregate function, the aggregate function is recomputed for each tuple deletion.
When deleting tuples based on a condition involving an aggregate function, the aggregate function is recomputed for each tuple deletion.
Which SQL statement is used to increase salaries of instructors by a certain percentage?
Which SQL statement is used to increase salaries of instructors by a certain percentage?
Which of the following SQL commands is used to add new rows to a table?
Which of the following SQL commands is used to add new rows to a table?
Flashcards
What is SQL?
What is SQL?
A language used for managing and manipulating databases.
What is DDL?
What is DDL?
A subset of SQL used for defining data structures.
What does DDL specify?
What does DDL specify?
Specifies the schema for each relation.
What is CHAR(n)?
What is CHAR(n)?
Signup and view all the flashcards
What is VARCHAR(n)?
What is VARCHAR(n)?
Signup and view all the flashcards
What is INT?
What is INT?
Signup and view all the flashcards
What is SMALLINT?
What is SMALLINT?
Signup and view all the flashcards
What is NUMERIC(p,d)?
What is NUMERIC(p,d)?
Signup and view all the flashcards
What is REAL?
What is REAL?
Signup and view all the flashcards
What is CREATE TABLE?
What is CREATE TABLE?
Signup and view all the flashcards
What is an Integrity Constraint?
What is an Integrity Constraint?
Signup and view all the flashcards
What does NOT NULL mean?
What does NOT NULL mean?
Signup and view all the flashcards
What is a Primary Key?
What is a Primary Key?
Signup and view all the flashcards
What is a Foreign Key?
What is a Foreign Key?
Signup and view all the flashcards
What does INSERT do?
What does INSERT do?
Signup and view all the flashcards
What does DELETE do?
What does DELETE do?
Signup and view all the flashcards
What does DROP TABLE do?
What does DROP TABLE do?
Signup and view all the flashcards
What does ALTER do?
What does ALTER do?
Signup and view all the flashcards
What does 'ALTER TABLE ADD' do?
What does 'ALTER TABLE ADD' do?
Signup and view all the flashcards
What does 'ALTER TABLE DROP' do?
What does 'ALTER TABLE DROP' do?
Signup and view all the flashcards
What is SELECT-FROM-WHERE?
What is SELECT-FROM-WHERE?
Signup and view all the flashcards
What does SELECT do?
What does SELECT do?
Signup and view all the flashcards
What does DISTINCT do?
What does DISTINCT do?
Signup and view all the flashcards
What does ALL do?
What does ALL do?
Signup and view all the flashcards
What does asterisk (*) mean in SELECT?
What does asterisk (*) mean in SELECT?
Signup and view all the flashcards
What does WHERE do?
What does WHERE do?
Signup and view all the flashcards
What is a Cartesian Product?
What is a Cartesian Product?
Signup and view all the flashcards
What is the AS clause?
What is the AS clause?
Signup and view all the flashcards
What is NATURAL JOIN?
What is NATURAL JOIN?
Signup and view all the flashcards
What does LIKE do?
What does LIKE do?
Signup and view all the flashcards
What is ORDER BY?
What is ORDER BY?
Signup and view all the flashcards
What does BETWEEN do?
What does BETWEEN do?
Signup and view all the flashcards
What does INTERSECT do?
What does INTERSECT do?
Signup and view all the flashcards
What does EXCEPT do?
What does EXCEPT do?
Signup and view all the flashcards
What does NULL mean?
What does NULL mean?
Signup and view all the flashcards
What is three-valued logic?
What is three-valued logic?
Signup and view all the flashcards
What does IS NULL do?
What does IS NULL do?
Signup and view all the flashcards
What are Aggregate Functions?
What are Aggregate Functions?
Signup and view all the flashcards
What does AVG() do?
What does AVG() do?
Signup and view all the flashcards
What does MIN() do?
What does MIN() do?
Signup and view all the flashcards
What does MAX() do?
What does MAX() do?
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 wheren
specifies the length.varchar(n)
: Variable-length character string wheren
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 ofp
digits, whered
digits are to the right of the decimal pointreal, double precision
: Floating point numbers with machine-dependent precision.float(n)
: Floating point number with user-specified precision of at leastn
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 relationr
.Di
is the data type of values in the domain of attributeAi
.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 relationr
.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 tablesec_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 theinstructor
table.delete from student
: Removes all tuples from thestudent
relation.drop table r
: Deletes the tabler
.alter table r add A D
: Adds an attribute named A with domain D to relation r; existing tuples are assignednull
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 thesalary
attribute divided by 12.select ID, name, salary/12 as monthly_salary
usesas
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
, andnot
. 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 formatold-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 toinstructor.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, andasc
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
, andexcept
and works with queries union
automatically eliminates duplicates; useunion 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 usingunion
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 as5 + null
returningnull
. - The predicate
is null
checks fornull
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 valuemin
: minimum valuemax
: maximum valuesum
: sum of the valuescount
: 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 thegroup 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 thewhere
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 returnnull
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 returnstrue
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 thewith
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.