0% found this document useful (0 votes)
3 views

Untitled documentasdf

Uploaded by

Gokulakrishnan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Untitled documentasdf

Uploaded by

Gokulakrishnan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

In SQL, a key is a set of attributes that uniquely identifies a row in a table

and establishes relationships between tables. There are several types of keys:

Primary Key (PK): A column or set of columns that uniquely identifies each row
in a table. A primary key cannot contain null values and must be unique.
Example: CREATE TABLE Employee (ID int PRIMARY KEY, Name varchar(50),
...).

Candidate Key (CK): A column or set of columns that could potentially be used
as a primary key. A candidate key is unique and cannot contain null values, but
it may not be the most efficient choice for a primary key.

Alternate Key (AK): A column or set of columns that provides a unique


identifier for a row, but is not the primary key. Alternate keys can contain
null values.

Foreign Key (FK): A column or set of columns in a table that references the
primary key of another table. Foreign keys establish relationships between
tables.

Composite Key: A key that consists of multiple columns. Composite keys can be
used as primary keys or foreign keys.

Surrogate Key: A unique identifier column that is not based on any meaningful
attribute of the table. Surrogate keys are often used as primary keys when
there is no natural candidate key.
Different Types of Keys in SQL
Key Type Characteristics Purpose

Super key Can contain redundant Uniquely identifies tuples in a table


attributes

Candidate Contains only necessary Identifies tuples uniquely, subset of super


key attributes key

Primary key Unique and non-null Uniquely identifies tuples in the table

Alternate – Not chosen as primary key


key

Composite More than one attribute Identifies tuples uniquely


key

Foreign key Linked to primary key in Maintains referential integrity, establishes


another table relationships

Join 🎯🎯
Joins are used to combine rows from two or more tables based on a related column
between them.

INNER JOIN: Selects records that have matching values in both tables.
sql
SELECT employees.name, orders.order_id
FROM employees
INNER JOIN orders ON employees.id = orders.employee_id;

LEFT JOIN: Selects all records from the left table, and the matched records from
the right table.
sql
SELECT employees.name, orders.order_id
FROM employees
LEFT JOIN orders ON employees.id = orders.employee_id;

RIGHT JOIN: Selects all records from the right table, and the matched records
from the left table.
sql
SELECT employees.name, orders.order_id
FROM employees
RIGHT JOIN orders ON employees.id = orders.employee_id;

FULL JOIN: Selects all records when there is a match in either left or right table.
sql
SELECT employees.name, orders.order_id
FROM employees
FULL JOIN orders ON employees.id = orders.employee_id;

I hope these explanations and examples help! Let me know if you need more details or
have any other questions.

Set Operations 🎯🎯
Set operations combine the results of two or more queries. Common set operations
include UNION, INTERSECT, and EXCEPT:

UNION: Combines the results of two queries and removes duplicate rows.
sql
SELECT name FROM employees
UNION
SELECT name FROM managers;

UNION ALL: Combines the results of two queries and includes all duplicates.
sql
SELECT name FROM employees
UNION ALL
SELECT name FROM managers;

INTERSECT: Returns only the rows that are common to both queries.
sql
SELECT name FROM employees
INTERSECT
SELECT name FROM managers;

EXCEPT (or MINUS): Returns the rows from the first query that are not present in
the second query.
sql
SELECT name FROM employees
EXCEPT

● SELECT name FROM managers;

Aggregate Functions 🎯🎯
Aggregate functions perform calculations on a set of values and return a single value.
Common aggregate functions include COUNT, SUM, AVG, MIN, and MAX:

COUNT: Returns the number of rows.


sql
SELECT COUNT(*) FROM employees;


SUM: Returns the total sum of a numeric column.
sql
SELECT SUM(salary) FROM employees;

AVG: Returns the average value of a numeric column.


sql
SELECT AVG(salary) FROM employees;

MIN: Returns the minimum value in a column.


sql
SELECT MIN(salary) FROM employees;


● MAX: Returns the maximum value in a column.
sql
SELECT MAX(salary) FROM employees;

Nested Subqueries or Correlated Subqueries 🎯🎯


Nested Subqueries: A subquery is a query within another query. It can be used to
perform more complex operations.

Example: Find employees who have the highest salary.


sql
SELECT name
FROM employees
WHERE salary = (SELECT MAX(salary) FROM employees);

Correlated Subqueries: A correlated subquery is a subquery that references a column


from the outer query. It is evaluated once for each row processed by the outer
query.
Example: Find employees who earn more than the average salary in their department.
sql
SELECT name, department_id, salary
FROM employees e1
WHERE salary > (SELECT AVG(salary)
FROM employees e2
WHERE e1.department_id = e2.department_id);

These explanations and examples should help you understand the concepts better! Let
me know if you have any further questions or need more details.

Absolutely! Here's a concise explanation of the different Normal Forms (1NF, 2NF,
3NF, and BCNF) in database design:

### 1NF (First Normal Form) 🎯🎯


**Definition:** A table is in 1NF if:
1. All columns contain atomic (indivisible) values.
2. Each column contains values of a single type.
3. Each column has a unique name.
4. The order in which data is stored does not matter.

**Example:**
```sql
CREATE TABLE students (
student_id INT,
name VARCHAR(100),
course VARCHAR(100)
);
```

### 2NF (Second Normal Form) 🎯🎯


**Definition:** A table is in 2NF if:
1. It is in 1NF.
2. All non-key attributes are fully functionally dependent on the primary key.

**Example:**
```sql
CREATE TABLE students (
student_id INT PRIMARY KEY,
name VARCHAR(100)
);

CREATE TABLE enrollments (


student_id INT,
course VARCHAR(100),
PRIMARY KEY (student_id, course),
FOREIGN KEY (student_id) REFERENCES students(student_id)
);
```

### 3NF (Third Normal Form) 🎯🎯


**Definition:** A table is in 3NF if:
1. It is in 2NF.
2. All the attributes are functionally dependent only on the primary key.

**Example:**
```sql
CREATE TABLE students (
student_id INT PRIMARY KEY,
name VARCHAR(100)
);

CREATE TABLE courses (


course_id INT PRIMARY KEY,
course_name VARCHAR(100)
);

CREATE TABLE enrollments (


student_id INT,
course_id INT,
PRIMARY KEY (student_id, course_id),
FOREIGN KEY (student_id) REFERENCES students(student_id),
FOREIGN KEY (course_id) REFERENCES courses(course_id)
);
```

### BCNF (Boyce-Codd Normal Form) 🎯🎯🎯🎯


**Definition:** A table is in BCNF if:
1. It is in 3NF.
2. For every functional dependency (A → B), A should be a super key.

**Example:**
```sql
CREATE TABLE professors (
professor_id INT PRIMARY KEY,
professor_name VARCHAR(100)
);

CREATE TABLE courses (


course_id INT PRIMARY KEY,
course_name VARCHAR(100),
professor_id INT,
FOREIGN KEY (professor_id) REFERENCES professors(professor_id)
);

CREATE TABLE students (


student_id INT PRIMARY KEY,
name VARCHAR(100)
);

CREATE TABLE enrollments (


student_id INT,
course_id INT,
PRIMARY KEY (student_id, course_id),
FOREIGN KEY (student_id) REFERENCES students(student_id),
FOREIGN KEY (course_id) REFERENCES courses(course_id)
);
```

I hope these explanations and examples help you understand the different normal
forms and their purposes in database design! Let me know if you have any further
questions or need more details.

Sure! Here's a concise explanation of Fourth Normal Form (4NF) and Fifth Normal
Form (5NF) in database design:

### 4NF (Fourth Normal Form)

**Definition:** A table is in 4NF if:


1. It is in Boyce-Codd Normal Form (BCNF).
2. It has no multi-valued dependencies.

**Explanation:**
- A multi-valued dependency occurs when one attribute in a table determines another
attribute, and both are independent of all other attributes.
- In 4NF, a table should not have more than one multi-valued dependency.

**Example:**
Consider a table where a student can have multiple skills and enroll in multiple
courses.

Before 4NF:
```sql
CREATE TABLE student_skills_courses (
student_id INT,
skill VARCHAR(100),
course VARCHAR(100),
PRIMARY KEY (student_id, skill, course)
);
```

To achieve 4NF, we need to split the table into two tables to remove the
multi-valued dependencies:

After 4NF:
```sql
CREATE TABLE student_skills (
student_id INT,
skill VARCHAR(100),
PRIMARY KEY (student_id, skill)
);

CREATE TABLE student_courses (


student_id INT,
course VARCHAR(100),
PRIMARY KEY (student_id, course)
);
```

### 5NF (Fifth Normal Form)

**Definition:** A table is in 5NF if:


1. It is in 4NF.
2. It has no join dependencies that are not implied by candidate keys.

**Explanation:**
- A join dependency occurs when a table can be reconstructed from multiple tables.
- In 5NF, a table should be decomposed into smaller tables to eliminate redundancy
and anomalies while ensuring it can be accurately reconstructed.

**Example:**
Consider a table where projects are associated with both employees and tasks.

Before 5NF:
```sql
CREATE TABLE project_employee_task (
project_id INT,
employee_id INT,
task_id INT,
PRIMARY KEY (project_id, employee_id, task_id)
);
```

To achieve 5NF, we decompose the table into three tables to eliminate join
dependencies:

After 5NF:
sql
CREATE TABLE project_employee (
project_id INT,
employee_id INT,
PRIMARY KEY (project_id, employee_id)
);

CREATE TABLE project_task (


project_id INT,
task_id INT,
PRIMARY KEY (project_id, task_id)
);

CREATE TABLE employee_task (


employee_id INT,
task_id INT,
PRIMARY KEY (employee_id, task_id)
);
```

I hope these explanations help you understand 4NF and 5NF better! If you have any
further questions or need more detailed examples, feel free to ask.
Trigger in sql example and write an example with it

A trigger in SQL is a stored procedure that is automatically executed in response to


specific events on a particular table or view. Triggers can be used for tasks such as
enforcing business rules, validating data, or updating related tables.

Example Trigger

Let's create a trigger that automatically updates the last_updated column of the
employees table whenever a row is updated.

Step 1: Create the Table

First, let's create a table with the necessary columns:

sql
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(100),
position VARCHAR(100),
salary DECIMAL(10, 2),
last_updated TIMESTAMP
);

Step 2: Create the Trigger

Now, let's create the trigger:

sql
CREATE TRIGGER update_last_updated
BEFORE UPDATE ON employees
FOR EACH ROW
BEGIN
SET NEW.last_updated = NOW();
END;

Step 3: Update Data


When we update a row in the employees table, the last_updated column will
automatically be updated to the current timestamp:

sql
UPDATE employees
SET salary = 65000.00
WHERE id = 1;

You might also like