You are on page 1of 20

1. Explanation of point 2.

3 from Slide 12
In simple terms, the SQL query is used to find the names, loan numbers, and loan amounts of all
customers who have taken a loan from the bank.

Here's an explanation of the query using an example:

Suppose we have two tables in our database: "Borrower" and "Loan."

**Borrower Table:**
| Customer-Name | Loan-Number |
|---------------|----------------|
| John | 101 |
| Alice | 102 |
| Mary | 103 |

**Loan Table:**
| Loan-Number | Amount |
|--------------|---------|
| 101 | 5000 |
| 102 | 8000 |
| 104 | 3000 |

Now, let's break down the query:

```sql
SELECT Customer-Name, Borrower.Loan-Number, Amount
FROM Borrower, Loan
WHERE Borrower.Loan-Number = Loan.Loan-Number;
```

1. The `SELECT` clause specifies the columns we want to see in the result: "Customer-Name,"
"Borrower.Loan-Number," and "Amount."

2. The `FROM` clause mentions two tables, "Borrower" and "Loan," which we want to use in the
query.

3. The `WHERE` clause specifies the condition that the "Loan-Number" column in the
"Borrower" table must be equal to the "Loan-Number" column in the "Loan" table. This
condition is crucial for finding matching loans for customers.

4. The `SELECT` clause combines data from both tables using the specified condition in the
`WHERE` clause.
After executing the query, the database system will look for matching loan numbers in both
tables. It will then combine the "Customer-Name," "Loan-Number," and "Amount" columns
where the loan numbers match. The result will contain the details of all customers who have
loans from the bank, along with their respective loan numbers and loan amounts.

Using the provided example, the resulting output would be:

| Customer-Name | Loan-Number | Amount |


|---------------|----------------|---------|
| John | 101 | 5000 |
| Alice | 102 | 8000 |

In this output, we can see that John has a loan with loan number 101 and an amount of 5000,
while Alice has a loan with loan number 102 and an amount of 8000. Since there is no loan
number 103 in the "Loan" table, the customer Mary is not included in the result.

2. Explanation of point 2.4 from Slide 14


Given

SELECT borrower.customer-name, borrower.loan-number AS loan-id, loan.amount

FROM borrower, loan

WHERE borrower.loan-number = loan.loan-number;

This SQL statement retrieves information from two tables, "borrower" and "loan," using a
SELECT-FROM-WHERE query. Let's break down the SQL statement step-by-step to understand
what it does:

1. `SELECT customer-name, borrower.loan-number AS loan-id, amount`: This part of the query


specifies the columns that will be selected and returned in the result set. It includes three
columns: "customer-name," "borrower.loan-number" (which is renamed as "loan-id" in the
result set), and "amount."

2. `FROM borrower, loan`: This part indicates the tables involved in the query. It includes two
tables, "borrower" and "loan."

3. `WHERE borrower.loan-number = loan.loan-number`: The WHERE clause is used to specify the


condition for joining the two tables. It indicates that the rows should be combined where the
"loan-number" column in the "borrower" table is equal to the "loan-number" column in the
"loan" table. This condition establishes a relationship between the two tables, linking borrowers
to their respective loans.

In summary, the SQL statement retrieves data from the "borrower" and "loan" tables and
combines them based on the common "loan-number" column. The result will include the
"customer-name," "loan-id" (borrower's loan number), and the "amount" of each loan, showing
the borrowers and their associated loan details. This type of query is commonly used to fetch
data that involves relationships between multiple tables in a relational database system.

Example:
Let's assume we have two tables: "borrower" and "loan." The "borrower" table contains
information about customers, and the "loan" table contains details about the loans they have
taken. The tables are structured as follows:

Table: borrower

| customer-name | loan-number |
|---------------|-------------|
| John Doe | 1001 |
| Jane Smith | 1002 |
| Michael Brown | 1003 |
| Emily Johnson | 1004 |

Table: loan

| loan-number | amount |
|-------------|--------|
| 1001 | 5000 |
| 1002 | 8000 |
| 1003 | 10000 |
| 1004 | 3000 |

Now, let's write the SQL query to retrieve the desired information:

```sql
SELECT borrower.customer-name, borrower.loan-number AS loan-id, loan.amount
FROM borrower, loan
WHERE borrower.loan-number = loan.loan-number;
```
Result:

| customer-name | loan-id | amount |


|---------------|---------|--------|
| John Doe | 1001 | 5000 |
| Jane Smith | 1002 | 8000 |
| Michael Brown | 1003 | 10000 |
| Emily Johnson | 1004 | 3000 |

The query fetches the "customer-name" from the "borrower" table, renames the
"borrower.loan-number" as "loan-id," and retrieves the corresponding "amount" from the
"loan" table, based on the condition that the "loan-number" in both tables match. The result set
shows the customer name, their loan ID, and the loan amount associated with each loan.

3. Explanation of point 2.5 from Slide 15 (Tuple Variables)


In the context of SQL, a "tuple variable" is also known as a "table alias" or "relation alias." It is a
way to provide a temporary and often shorter name to a table within an SQL query. Tuple
variables (table aliases) are defined in the FROM clause using the AS keyword. These aliases
allow us to reference the table by the given name (alias) throughout the rest of the query,
making the SQL code more concise and readable.

Let's explain tuple variables (table aliases) and their usage in SQL queries descriptively:

1. Defining Tuple Variables (Table Aliases):


In the FROM clause of an SQL query, you can use the AS keyword to define a table alias. The
general syntax is as follows:

```sql
SELECT column1, column2, ...
FROM table_name AS alias_name;
```

Here, "table_name" is the original table name, and "alias_name" is the alias you want to assign
to that table. The alias can be any valid identifier and is used as a shorthand reference to the
table within the query.

2. Using Tuple Variables (Table Aliases):


After defining the table alias in the FROM clause, you can refer to the table using the alias in the
rest of the query, particularly in the SELECT, JOIN, and WHERE clauses. This helps improve the
readability of complex queries that involve multiple tables.
Example:
Let's consider a scenario where we have two tables: "employees" and "departments." We want
to retrieve the names of employees along with their corresponding department names using
tuple variables (table aliases):

Table: employees

| emp_id | emp_name | department_id |


|--------|----------|---------------|
| 1 | John | 101 |
| 2 | Jane | 102 |
| 3 | Michael | 103 |
| 4 | Emily | 101 |

Table: departments

| department_id | department_name |
|---------------|-----------------|
| 101 | HR |
| 102 | Finance |
| 103 | IT |

SQL Query with Tuple Variables (Table Aliases):

```sql
SELECT emp.emp_name, dep.department_name
FROM employees AS emp
JOIN departments AS dep ON emp.department_id = dep.department_id;
```

Result:

| emp_name | department_name |
|----------|-----------------|
| John | HR |
| Jane | Finance |
| Michael | IT |
| Emily | HR |

Explanation of the Query:


In this example, we used "emp" as an alias for the "employees" table and "dep" as an alias for
the "departments" table. The SELECT clause references the columns "emp_name" and
"department_name" from the respective tables using their aliases. The JOIN clause combines
the two tables based on the "department_id" column. Throughout the query, we use the aliases
"emp" and "dep" to refer to the respective tables, making the SQL code more concise and easier
to understand.

Another Example:
Let's explain the SQL query step by step with a simple language explanation and an example:

**SQL Query:**
```sql
SELECT DISTINCT T.branch-name
FROM branch AS T, branch AS S
WHERE T.assets > S.assets AND S.branch-city = 'Brooklyn';
```

**Example:**

Consider the following "branch" table, which contains information about different bank
branches:

**Table: branch**
```
branch-name | branch-city | assets
---------------------------------
Branch A | New York | 50000
Branch B | Brooklyn | 60000
Branch C | Brooklyn | 75000
Branch D | New York | 80000
Branch E | Chicago | 90000
```

**SQL Query:**
```sql
SELECT DISTINCT T.branch-name
FROM branch AS T, branch AS S
WHERE T.assets > S.assets AND S.branch-city = 'Brooklyn';
```
**Explanation:**

1. `SELECT DISTINCT T.branch-name`: This part of the query selects the `branch-name` column
from the result set. The keyword `DISTINCT` ensures that we get only unique branch names in
the output.

2. `FROM branch AS T, branch AS S`: In this part, we are using table aliases to reference the
"branch" table twice. The first alias `T` represents the branch we want to find, and the second
alias `S` represents any branch located in Brooklyn that we are comparing with.

3. `WHERE T.assets > S.assets AND S.branch-city = 'Brooklyn'`: The `WHERE` clause filters the
rows in the result set based on the specified conditions. It checks that the `assets` of the branch
represented by `T` (the branch we want to find) are greater than the `assets` of any branch
represented by `S` (located in Brooklyn). This means we want to find branches with assets
greater than any branch in Brooklyn.

**Result of the SQL query:**


```
branch-name
-----------
Branch D
Branch E
```

**Explanation of the Result:**

The query has retrieved the `branch-name` of all branches that have greater assets than some
branch located in Brooklyn. Let's break it down:

- Branch D has assets of 80000, which are greater than the assets of both branches located in
Brooklyn (Branch B with 60000 assets and Branch C with 75000 assets).
- Branch E has assets of 90000, which are also greater than the assets of both branches located
in Brooklyn.

Therefore, the output includes the names of the branches that meet the condition specified in
the query, which is having greater assets than any branch located in Brooklyn.
4. Explanation of point 2.6 from Slide 16 (String Operations)
Pattern matching with the `LIKE` operator is a powerful feature in SQL that allows you to
perform searches and filter results based on specific patterns in strings. The two special
characters used in patterns are:

1. Percent `%`: The `%` character matches any sequence of characters, including an empty string
(zero or more occurrences). It is often used as a wildcard to represent any substring.

Examples:
- `'Perry%'` matches any string beginning with "Perry," such as "Perryville," "Perry Street," etc.
- `'%Perry'` matches any string ending with "Perry," like "John Perry," "Mr. Perry," etc.
- `'%Perry%'` matches any string containing "Perry" as a substring, such as "Perry's Place," "Hello
Perry World," etc.

2. Underscore `_`: The `_` character matches any single character. It is also used as a wildcard,
but it only represents a single character, not a sequence of characters.

Examples:
- `'---'` matches any string exactly three characters long, like "123," "ABC," etc.
- `'---%'` matches any string of at least three characters, such as "1234," "ABCD," etc.
- `'%---'` matches any string of at most three characters, like "12," "A," etc.

Let's explain these patterns descriptively and use relevant examples:

1. `'Perry%'`:
This pattern will match any string that starts with "Perry." For example, if we have a table with
the following data:

| full_name |
|-------------------|
| Perryville Adams |
| Perry Johnson |
| John Perry |
| Steve Perryson |

The query using `'Perry%'` will return the following rows:

| full_name |
|-------------------|
| Perryville Adams |
| Perry Johnson |
2. `'%Perry'`:
This pattern will match any string that ends with "Perry." Using the same table as above, the
query using `'%Perry'` will return the following rows:

| full_name |
|-------------------|
| John Perry |

3. `'%Perry%'`:
This pattern will match any string that contains "Perry" as a substring. Using the same table, the
query using `'%Perry%'` will return all the rows because every name contains "Perry"
somewhere in the string.

4. `'---'`:
This pattern will match any string that has exactly three characters. For example:

| name |
|-------|
| ABC |
| 123 |
| XYZ |

5. `'---%'`:
This pattern will match any string that has at least three characters. For example:

| name |
|---------|
| ABC |
| 123 |
| XYZ123 |

6. `'%---'`:
This pattern will match any string that has at most three characters. For example:

| name |
|--------|
| ABC |
| 123 |
| XY |
Overall, using the `LIKE` operator with patterns and the `%` and `_` wildcards allows for flexible
and powerful string matching capabilities in SQL queries.

In SQL, the operator that makes pattern matching case-insensitive is called the "ILIKE"
operator (in some database systems, it may be written as "ILIKE" or "LIKE" with the "i" option).
The "ILIKE" operator is typically used with the "WHERE" clause to search for specific patterns in
text columns without considering the case (uppercase or lowercase) of the characters.

Here's how the "ILIKE" operator works:

Let's say you have a table called "employees," and it has a column named "first_name" with
values like "John," "Mary," "jane," "Alex," etc.

If you want to find all employees whose first names contain the pattern "jo" regardless of
whether it's in uppercase or lowercase, you can use the "ILIKE" operator:

```sql
SELECT * FROM employees WHERE first_name ILIKE '%jo%';
```

This query will return all rows where the "first_name" contains the letters "jo," such as "John,"
"joseph," "Mary Jo," and so on, regardless of whether the letters are in uppercase or lowercase.

The "ILIKE" operator performs a case-insensitive search, meaning it treats all characters as if
they were in lowercase before comparing them. So, when you use "ILIKE," you don't have to
worry about the case of the letters in your pattern or the data in the column you are searching.

5. Explanation of point 2.6 from Slide 17 (String Operations)


Let's explain the SQL statements and concepts descriptively, and provide relevant examples:

1. Find the names of all customers whose street includes the substring "Main".

```sql
SELECT customer-name
FROM customer
WHERE customer-street LIKE '%Main%';
```

Explanation:
In this SQL query, we are selecting the "customer-name" from the "customer" table. The WHERE
clause uses the LIKE comparison operator with the pattern '%Main%', which matches any street
containing the substring "Main." The '%' wildcard on both sides of "Main" means that "Main"
can appear anywhere in the street name.

Example:
Consider the following "customer" table:

| customer-name | customer-street |
|---------------|---------------------------|
| John Doe | 123 Main Street |
| Jane Smith | 456 Elmwood Main Road |
| Michael Brown | 789 Maple Avenue |
| Emily Johnson | 10 Oakwood Drive |

The query using `'%Main%'` will return the following result:

| customer-name |
|---------------|
| John Doe |
| Jane Smith |

Explanation of the result:


The query retrieves the names of customers whose street includes the substring "Main." In this
example, both John Doe and Jane Smith have "Main" as part of their street names.

2. Escape character for LIKE comparison:

The escape character is used when you want to match the literal '%' or '_' characters in the
pattern instead of using them as wildcards. The escape character is specified using the ESCAPE
keyword.

```sql
SELECT column_name
FROM table_name
WHERE column_name LIKE 'pattern' ESCAPE 'escape_character';
```

- `LIKE 'Main\%' ESCAPE '\'` matches the string "Main%".


- `LIKE 'ab\%cd%' ESCAPE '\'` matches all strings beginning with "ab%cd".

Explanation:
In SQL, when you need to search for a literal '%' or '_' character in the pattern instead of using
them as wildcards, you can specify an escape character. In the example with `LIKE 'Main\%'
ESCAPE '\'`, the '\' character is specified as the escape character. It means that the '%' following
'Main' is not treated as a wildcard but as a literal character. So, it matches the string "Main%"
exactly.

Example:
Suppose we have the following data in a table:

| column_name |
|-------------|
| Main% |
| ab%cd-123 |
| xyz_main_45 |

If we use the escape character, the following queries will return the matching rows:

- `SELECT column_name FROM table_name WHERE column_name LIKE 'Main\%' ESCAPE '\';`

Result:

| column_name |
|-------------|
| Main% |

- `SELECT column_name FROM table_name WHERE column_name LIKE 'ab\%cd%' ESCAPE '\';`

Result:

| column_name |
|-------------|
| ab%cd-123 |

3. Patterns are case-sensitive:

In SQL, pattern matching with the LIKE operator is case-sensitive. It means that the pattern
'Main%' will only match strings that start with 'Main' in the exact case, such as "Main Street,"
but not "main road" or "MAIN AVENUE."

Example:
Consider the following "customer" table:

| customer-name | customer-street |
|---------------|---------------------------|
| John Doe | Main Street |
| Jane Smith | main road |
| Michael Brown | MAIN AVENUE |

If we use the LIKE comparison operator with the pattern 'Main%', the query will only match the
row with "Main Street" and exclude the others:

```sql
SELECT customer-name
FROM customer
WHERE customer-street LIKE 'Main%';
```

Result:

| customer-name |
|---------------|
| John Doe |

4. Searching for mismatches using NOT LIKE:

In SQL, you can use the NOT LIKE comparison operator to search for strings that do not match a
specific pattern. It's the opposite of the LIKE operator. The NOT LIKE operator excludes rows that
match the specified pattern.

Example:
Consider the following "customer" table:

| customer-name | customer-street |
|---------------|---------------------------|
| John Doe | Main Street |
| Jane Smith | Main Avenue |
| Michael Brown | Elmwood Road |
| Emily Johnson | Main Lane |

To find customers whose street does not include the substring "Main," we can use the NOT LIKE
operator:

```sql
SELECT customer-name
FROM customer
WHERE customer-street NOT LIKE '%Main%';
```

Result:

| customer-name |
|---------------|
| Michael Brown |

Explanation of the result:


The query retrieves the names of customers whose street does not include the substring
"Main." In this example, the names "Michael Brown" and "Emily Johnson" have streets that do
not contain "Main" as a substring.

6. Explanation of point 2.6 from Slide 18 (String Operations)


Let's explain the various string operations in SQL descriptively and provide relevant examples:

1. Concatenation (using "||"):


Concatenation in SQL is the process of combining two or more strings into a single string. In SQL,
the concatenation operator is represented by two vertical bars "||". When applied to strings, it
joins them together.

Example:

```sql
SELECT first_name || ' ' || last_name AS full_name
FROM employees;
```

Explanation:
In this example, we are concatenating the "first_name" and "last_name" columns from the
"employees" table, separated by a space. The result will give us the full name of each employee.

Example:
Table "employees":

| emp_id | first_name | last_name |


|--------|------------|-----------|
| 1 | John | Doe |
|2 | Jane | Smith |
|3 | Michael | Johnson |

The query will concatenate the "first_name" and "last_name" columns together with a space in
between, and it will create a new column named "full_name" that holds the combined values.

Result:

| full_name |
|-----------------|
| John Doe |
| Jane Smith |
| Michael Johnson |

Explanation:

- The operator `||` is used for string concatenation in SQL.


- The expression `first_name || ' ' || last_name` combines the values of "first_name" and
"last_name" columns with a space in between.
- The "AS full_name" part gives a new name "full_name" to the resulting concatenated column.

As a result, the query returns a list of full names by combining the first name and last name of
each employee in the "employees" table. The full names are presented in the "full_name"
column.

2. Extracting substrings:
SQL provides functions to extract substrings from a given string. The most commonly used
function is `SUBSTRING` (also known as `SUBSTR`), which allows you to extract a portion of a
string based on starting position and length.

Example:

```sql
SELECT SUBSTRING('Hello, World!', 1, 5) AS extracted_string;
```

Explanation:
In this example, the `SUBSTRING` function extracts a substring from the input string 'Hello,
World!' starting from position 1 and with a length of 5 characters. The result will be 'Hello'.

3. Converting from upper to lower case (and vice versa):


SQL provides functions to convert strings to upper case and lower case. The `UPPER` function
converts a string to uppercase, and the `LOWER` function converts it to lowercase.

Example:

```sql
SELECT UPPER('hello') AS uppercase_string, LOWER('WORLD') AS lowercase_string;
```

Explanation:
In this example, we use the `UPPER` function to convert 'hello' to 'HELLO' (uppercase) and the
`LOWER` function to convert 'WORLD' to 'world' (lowercase).

4. Finding string length:


SQL provides the `LENGTH` or `LEN` function (depending on the database) to find the length of a
string, which is the number of characters in the string.

Example:

```sql
SELECT LENGTH('Hello, World!') AS string_length;
```

Explanation:
In this example, the `LENGTH` function calculates the length of the input string 'Hello, World!',
which is 13 characters, including spaces and punctuation.

5. Similar to operation:
The `SIMILAR TO` operator in SQL provides more powerful pattern matching than the `LIKE`
operator. It allows you to use regular expressions to specify complex patterns for matching.

Example:

```sql
SELECT first_name
FROM employees
WHERE first_name SIMILAR TO 'Joh?n';
```

Explanation:
In this example, the `SIMILAR TO` operator is used to find all first names in the "employees"
table that match the pattern 'Joh?n', where the '?' represents a single character wildcard. It will
match names like 'John' and 'Joan'.

6. Escaping single quotes:


In SQL, if you need to include a single quote character within a string, you can escape it by using
two single quotes (''). The two single quotes are treated as a single quote within the string.

Example:

```sql
SELECT 'It''s right' AS quoted_string;
```

Explanation:
In this example, the string 'It''s right' includes the single quote character ' inside the string. The
two single quotes together ('') represent a single quote within the string, and the result will be
'It's right'.
7. Explanation of point 2.7 from Slide 19 (Ordering the Display of Tuples)

Let's explain the concept of ordering the display of tuples in SQL descriptively and provide relevant
examples:

1. Ordering the Display of Tuples using ORDER BY Clause:

The ORDER BY clause in SQL is used to sort the result of a query in a specified order. By default, the
tuples in the query result are returned in an unspecified order. However, by using the ORDER BY
clause, you can arrange the tuples in ascending or descending order based on one or more columns.
The ORDER BY clause is typically the last clause in an SQL query.

Syntax:

```sql

SELECT column1, column2, ...

FROM table_name

ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;

```

Explanation:
- `column1, column2, ...`: The columns you want to select and display in the result set.

- `table_name`: The table from which you are fetching the data.

- `ORDER BY`: The clause used to specify the order of the result set.

- `ASC`: The ascending order keyword (default if not specified). It sorts the result in ascending order.

- `DESC`: The descending order keyword. It sorts the result in descending order.

2. Example - Listing Customer Names in Alphabetic Order for Loans in Perryridge Branch:

Suppose we have two tables: "borrower" and "loan." The "borrower" table contains information
about customers, and the "loan" table contains details about loans. We want to retrieve the names
of all customers who have a loan in the "Perryridge" branch, sorted in alphabetical order.

Table: borrower

| customer-name | loan-number |

|---------------|-------------|

| John Doe | 1001 |

| Jane Smith | 1002 |

| Michael Brown | 1003 |

| Emily Johnson | 1004 |

Table: loan

| loan-number | branch-name |

|-------------|-------------|

| 1001 | Perryridge |

| 1002 | Elmwood |

| 1003 | Perryridge |
| 1004 | Maple |

SQL Query:

```sql

SELECT DISTINCT customer-name

FROM borrower, loan

WHERE borrower.loan-number = loan.loan-number AND branch-name = 'Perryridge'

ORDER BY customer-name;

```

Result:

| customer-name |

|---------------|

| Emily Johnson |

| John Doe |

Explanation of the Result:

The query retrieves the distinct customer names from the "borrower" table for customers who have
a loan in the "Perryridge" branch. The result is ordered in alphabetical order based on the
"customer-name" column. Emily Johnson appears before John Doe in the sorted result.

3. Using DESC for Descending Order:

You can specify "DESC" after the column name in the ORDER BY clause to sort the result in
descending order. If not specified, the default order is ascending (ASC).

Example:
Consider the same tables as above, and we want to list customer names in descending order of their
names for loans in the "Perryridge" branch.

SQL Query:

```sql

SELECT DISTINCT customer-name

FROM borrower, loan

WHERE borrower.loan-number = loan.loan-number AND branch-name = 'Perryridge'

ORDER BY customer-name DESC;

```

Result:

| customer-name |

|---------------|

| John Doe |

| Emily Johnson |

Explanation of the Result:

The query produces the same customer names as before, but this time they are ordered in
descending alphabetical order based on the "customer-name" column. John Doe appears before
Emily Johnson in the sorted result.

You might also like