SQL

0.0(0)
studied byStudied by 0 people
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
Card Sorting

1/72

encourage image

There's no tags or description

Looks like no tags are added yet.

Study Analytics
Name
Mastery
Learn
Test
Matching
Spaced

No study sessions yet.

73 Terms

1
New cards

Structured Query Language

sql
standard db language for relational databases

2
New cards

SQL consists of two core functions

Data Definition Language (DDL)
Data Manipulation Language (DML)

3
New cards

Data Manipulation Language (DML)

for manipulating and querying the data contained in the database, i.e., populating, reading, and updating the data in the tables.

4
New cards

Data Definition Language (DDL)

for defining and creating the database objects.

5
New cards

A Selection of Data Types

knowt flashcard image
6
New cards

Never Use Float or Double for Money!

They are approximate (inexact) types.

May result in discrepancies! Rounding errors.

use numeric type or the DBMS’s monetary type

7
New cards

Logical Model to Physical Model - ddata types example

knowt flashcard image
8
New cards

Naming Conventions

be consistent
popular recommendation is using snake_case in SQL
some dbms convert data objects names to lowercase automatically. use a snake_case is better for readability.

9
New cards

Creating Tables with SQL - Defining Columns (Attributes) in a Table

You define an attribute (column) for a table by specifying:

column_name: the name of the attribute in the table

data_type: the type of data the attribute can store

size: maximum length of the data it can store (optional)

<p>You define an attribute (column) for a table by specifying:</p><p>column_name: the name of the attribute in the table</p><p>data_type: the type of data the attribute can store</p><p>size: maximum length of the data it can store (optional)</p><p></p>
10
New cards

Is the order in which you create the tables important?

Yes, parent tables before child tables (tables with FKs).

11
New cards

Creating Tables - But We Also Had Constraints!

knowt flashcard image
12
New cards

Constraints

Rules formulated by the database designer may contain column or table constraints to prevent:

Accidental damage to the database

Changes that may cause data inconsistency

Many constraints can be specified using clauses in the CREATE TABLE statement.

Some may have to be specified using database procedures or rules

13
New cards

Types of Constraints

Mandatory data

Entity integrity

Referential integrity

Column value constraints

Enterprise constraints

14
New cards

mandatory data - constraints

NOT NULL

15
New cards

entity integrity constraints

PRIMARY KEY

16
New cards

Referential integrity - constraints

FOREIGN KEY

17
New cards

Column value constraints

CHECK, UNIQUE, DEFAULT

18
New cards

Referential Integrity Rule (1)

Foreign keys establish relationships between tables.

Referential integrity rule:

Value of a foreign key must either match an existing value of the primary key it refers to or be null.

19
New cards

Adding Foreign Keys: Example

knowt flashcard image
20
New cards

referential integrity (2)

It is important to enforce referential integrity in a relational database to ensure data consistency -No dangling reference in a ‘child’ table

Deletion of a record in the ‘parent’ table is not allowed if there exists any referenced records in the ‘child’ table.

21
New cards

referential integrity (3)

The effects of amendments to the ‘parent’ table depend on actions specified in the REFERENCES clause of the ‘child’ table when creating the foreign key.

By default: Any DELETION of a record in the parent table is not allowed if there exists any referenced child records in the child table.

You can change the default behaviour.

22
New cards

Cascading Referential Integrity - options

cascade
set null
set default

23
New cards

referential integrity option - cascade

Deleting a record in the ‘parent’ table automatically deletes all referenced records in ‘child’ tables.

24
New cards

referential integrity option - set null

Deleting a record in the ‘parent’ table automatically sets the foreign key value of all referenced ‘child’ records to NULL. Only works if the FK column allows nulls.

25
New cards

referential integrity option - set default

Deleting a record in the ‘parent’ table automatically sets the foreign key value of all referenced ‘child’ records to a default value.

26
New cards

SQL provides four statements for data manipulation.

Data manipulation involves:

insert - adding data to tables
update - modifying data in tables
delete - deleting data from tables
select - retrieving data from tables

27
New cards

INSERT Statement

INSERT INTO TableName [(column1, column2, column3, …)]

VALUES (dataValue1, dataValue2, dataValue3, ...);

<p>INSERT INTO TableName [(column1, column2, column3, …)]</p><p>VALUES (dataValue1, dataValue2, dataValue3, ...);</p>
28
New cards

UPDATE Statement

UPDATE TableName
SET columnName1 = newDataValue1 [, columnName2 = newDataValue2…]
[WHERE searchCondition]

<p>UPDATE TableName<br>SET columnName1 = newDataValue1 [, columnName2 = newDataValue2…]<br>[WHERE searchCondition]</p><p></p>
29
New cards

DELETE Statement

DELETE FROM TableName

[WHERE searchCondition]

<p>DELETE FROM TableName</p><p>[WHERE searchCondition]</p><p></p>
30
New cards

aggregate functions

Aggregate functions combine data and derive summary information
function is applied to selected col
Aggregate_Function(Column_Name)

31
New cards

type of aggregate functions

count,sum,avg,min,max
these functions use column expression as an argument
COUNT may also take a row – COUNT(*)
ignore null vals
return single val

32
New cards

Aggregate Functions: Examples

knowt flashcard image
33
New cards

Distinct

used to get a unique count
distinct doesn’t work with COUNT(*)

34
New cards

Aggregate Functions: Group By

specifies attributes to group the records by
Summarising data by groups.

The grouping attribute(s) are usually included as part of the results, but they can be omitted.

<p>specifies attributes to group the records by<br>Summarising data by groups.</p><p>The grouping attribute(s) are usually included as part of the results, but they can be omitted.</p><p></p>
35
New cards

Group By Clause: Notes

each item in select list must be single val per group
means the result of a group by can only contain:
The grouping attributes

Constants (values that do not change)

Aggregate function results (from COUNT, MIN, MAX, SUM, AVG)

36
New cards

Group By and Having Clause

The HAVING clause is used with the GROUP BY clause to reduce the groups that appear in the query result.

similar to WHERE but WHERE filters induvidual rows and HAVING filters groups

37
New cards
term image

Step 1: FROM … WHERE

Step 2: GROUP BY

Step 3: SELECT … COUNT

Step 4: HAVING

Step 5: ORDER BY


refer to slides wk5 14-21

<p>Step 1: FROM … WHERE</p><p>Step 2: GROUP BY</p><p>Step 3: SELECT … COUNT</p><p>Step 4: HAVING</p><p>Step 5: ORDER BY</p><p><br>refer to slides wk5 14-21</p>
38
New cards

Nested Queries (or Subqueries)

results is a table
queries can be nested in another query
results of a subq can be assigned an alias name

A subquery can be used as a normal table in a query, e.g.:

A single column in SELECT

A table in FROM

A table in WHERE

39
New cards

Subquery in SELECT Clause

knowt flashcard image
40
New cards

Subqueries: EXISTS and NOT EXISTS

used for subq
produce simple true or false results

41
New cards

subq exists

True, if and only if there exists at least one row in the result returned by the subquery.

False, if subquery returns an empty result – zero rows

42
New cards

subq not exist

False, if there exists at least one row in the result returned by the subquery.

True, if subquery returns an empty result – zero rows.

43
New cards

Subqueries in WHERE Clause Using EXISTS

knowt flashcard image
44
New cards

PostgreSQL Date Operations

knowt flashcard image
45
New cards

Date Operations: Example Query

knowt flashcard image
46
New cards

Avoiding Complex Queries WITH Clause

assign an alias name to a temp query results
The named subquery can then be used anywhere in the main query as a temporary table.

WITH alias_name

AS (subquery statement)

main query statement;

47
New cards

WITH Clause: Example

knowt flashcard image
48
New cards

WINDOW Function

further simplify the with clause by using a window func OVER clause

SELECT Module_Code, Student_ID, Coursework_Mark,

AVG(Coursework_Mark) OVER (PARTITION BY Module_Code) AS Avg_Mark

FROM Registration;


this func performs the calc for each row in the window
similar calc to the aggregated but no row grouping into a single summary row

has effect of grouping while retaining each row individually in the results.

49
New cards

type of set operators

union
intersect
except

these ops automatically elimiates duplicates
to apply these ops tables must union compatible

50
New cards

dbms provides

Transaction support

Concurrency control services

Recovery services


it ensures that the db is reliable and remain in a consisten state

51
New cards

union compatible relation: defenition

two table are union compatible if:
ther have the same degree(n-no of cols) and domain(Ai) = domain(Bi)

so compatible means same no of cols and cols have same data type

52
New cards

set op example

knowt flashcard image
53
New cards

Queries on Multiple Tables: Aliases

SQL permits columns to have the same name provided they are in different tables

Two ways to remove any ambiguity in a multi-table query result:
-Prefix the attribute (column) with the required table name: staff.staffID
-Use aliases to simplify or shorten the length of the query. Common practice is to use the first letter of the table name: s.staffID

54
New cards

Queries on Multiple Tables: Steps

example wk5 l2 slide 13-16 ,

55
New cards

types of JOINs

JOIN clause is used to retrieve rows from two tables based on the linkage condition

JOIN( inner) - by default returns all rows that have a match in both tables
LEFT JOIN
RIGHT JOIN
FULL JOIN

56
New cards

LEFT JOIN

returns all rows from the left (first) table and the matched ones from the right (second) table. NULLs are returned for columns in the right side when there is no match

<p>returns all rows from the left (first) table and the matched ones from the right (second) table. NULLs are returned for columns in the right side when there is no match</p>
57
New cards

RIGHT JOIN

returns all rows from the right table and the matched ones from the left table. NULLs are returned for columns in the left side when there is no match.

<p>returns all rows from the right table and the matched ones from the left table. NULLs are returned for columns in the left side when there is no match.</p><p></p>
58
New cards

FULL JOIN

returns all rows from both tables whether there is a match or not.

59
New cards

INNER JOIN

knowt flashcard image
60
New cards

Queries on Multiple Tables: Example

19-25

61
New cards

Queries on Multiple Tables: Tip

To join 3 tables, you need two linkage conditions, i.e., 2 joins

To join 2 tables, you need one linkage condition, i.e., 1 join

one table:
-it depends
- if a self join is required: table has a relationship with itself and this need to be shown in query reults use a self join
- otherwise no join needed

62
New cards

self join query

table join to its self
useful for unary relationships - relationship with itself
or useful for checking if a row shares an attributes value with another row
may be viewed as a join of two copies of same table
atleast n copy must have alias name

63
New cards

Self-JOIN Queries: Example 1

check wk5 l2 slide 28 , 30-31

64
New cards

what are views

base tables - Tables created with CREATE TABLE are stored in the database


a view is a virtual table:
-A logical window on data from one or more tables.
-No data is retrieved when a view is created – simply stores the query definition.
-The ‘virtual table’ defined by a view is recreated each time the view is referenced.

views are dynamic: changes made to the base tables that affect the view are immediately reflected in the view.

<p>base tables - Tables created with CREATE TABLE are stored in the database</p><p><br>a view is a virtual table:<br>-A logical window on data from one or more tables.<br>-No data is retrieved when a view is created – simply stores the query definition.<br>-The ‘virtual table’ defined by a view is recreated each time the view is referenced.</p><p>views are dynamic: changes made to the base tables that affect the view are immediately reflected in the view.</p><p></p>
65
New cards

Views: Example 1

knowt flashcard image
66
New cards

Why Views

provide data independence from concrete data structure: if table structure is changed and not needed by view then view doesn’t change
allows users to customise their views of the base tabe appropriate for their needs
icrese security by restricting access to the db: proves powerful and flexible security mechanise by hiding part of the db from certan user
simplifies complex queries on the base table

67
New cards

Views uses

a view maybe used to filter or combine

68
New cards

filter - view use

restrict access to selected row or col of one or more table or views
horizontal view: restrict the users access to selected rows
vertical view: restricts a user’s access to selected cols
horizontal and vertical can be used in combo

69
New cards

combine -view use

simply a complex query
de-normalise - join tables split up during normalisation

70
New cards
<p>Views: Horizontal Views</p>

Views: Horizontal Views

Restricts access to selected rows from one or more tables, or views.
use where clause

71
New cards
<p>Views: Vertical Views</p>

Views: Vertical Views

Restrict access to selected columns from one or more tables, or views.

72
New cards

view example

refer to wk5 l2 slides 40-41

73
New cards