0% found this document useful (0 votes)
10 views21 pages

Placement

Uploaded by

basaf54408
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)
10 views21 pages

Placement

Uploaded by

basaf54408
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/ 21

DATABASE: A database is a collection of related data which represents some aspect

of the real world.

DBMS: DBMS (Database Management System) is software used to create, manage, and
organize databases.

RDBMS (Relational Database Management System) - is a DBMS based on the concept of


tables (also called relations). Data is organized into tables (also known as
relations) with rows (records) and columns (attributes). Eg - MySQL, PostgreSQL,
Oracle etc.

ER diagram or Entity Relationship diagram is a conceptual model that gives the


graphical representation of the logical structure of the database.

A query refers to a request for information from a database. It is a command or


statement written in a database query language, such as SQL (Structured Query
Language), used to retrieve, insert, update, or delete data in a database.

DBMS
RDBMS
----------------------------------------------------------------------------
------------------------------------------------------------------------------
DBMS stores data as file. RDBMS
stores data in tabular form.

Data elements need to access individually.


Multiple data elements can be accessed at the same time.

No relationship between data. Data


is stored in the form of tables which are related to each other.

Normalization is not present.


Normalization is present.

DBMS does not support distributed database. RDBMS


supports distributed database.

It deals with small quantity of data. It


deals with large amount of data.

It is used for small organization and deal with small data. It is


used to handle large amount of data.

Security is less More


security measures provided.

It supports single user. It


supports multiple users.

Data fetching is slower for the large amount of data. Data


fetching is fast because of relational approach.

Low software and hardware necessities.


Higher software and hardware necessities.

Examples: XML, Window Registry, Forxpro, dbaseIIIplus etc.


Examples: MySQL, PostgreSQL, SQL Server, Oracle, Microsoft Access etc.

-----------------------------------------------------------------------------------
-------------------------------------------------------------------------

SQL
NOSQL
----------------------------------------------------------------------------
----------------------------------------------------------------------------

RELATIONAL DATABASE MANAGEMENT SYSTEM (RDBMS)


Non-relational or distributed database system.

These databases have fixed or static or predefined schema


They have a dynamic schema

These databases are not suited for hierarchical data storage.


These databases are best suited for hierarchical data storage.

These databases are best suited for complex queries


These databases are not so good for complex queries

Vertically Scalable
Horizontally scalable

Follows ACID property


Follows CAP(consistency, availability, partition tolerance)

Examples: MySQL, PostgreSQL, Oracle, MS-SQL Server, etc


Examples: MongoDB, HBase, Neo4j, Cassandra, etc

-----------------------------------------------------------------------------------
-------------------------------------------------------------------------

Vertical Scaling:
When new resources are added to the existing system to meet the expectation, it is
known as vertical scaling.

Vertical scaling involves adding more power (CPU, RAM, storage, etc.) to an
existing machine.

Consider a rack of servers and resources that comprises the existing system. (as
shown in the figure). Now when the existing system fails to meet the expected
needs, and the expected needs can be met by just adding resources, this is
considered vertical scaling. Vertical scaling is based on the idea of adding more
power(CPU, RAM) to existing systems, basically adding more resources.
Vertical scaling is not only easy but also cheaper than Horizontal Scaling. It also
requires less time to be fixed.

Horizontal Scaling:

When new server racks are added to the existing system to meet the higher
expectation, it is known as horizontal scaling.

Horizontal scaling involves adding more machines or nodes to a system.

Consider a rack of servers and resources that comprises the existing system. (as
shown in the figure). Now when the existing system fails to meet the expected
needs, and the expected needs cannot be met by just adding resources, we need to
add completely new servers. This is considered horizontal scaling. Horizontal
scaling is based on the idea of adding more machines to our pool of resources.
Horizontal scaling is difficult and also costlier than Vertical Scaling. It also
requires more time to be fixed.

-----------------------------------------------------------------------------------
-------------------------------------------------------------------------

SQL (Structured Query Language) is a programming language used to interact with


relational databases.

It is used to perform CRUD operations :


Create
Read
Update
Delete

SQL DATATYPES:

CHAR - string(0-255), can store characters of fixed length - CHAR(50)


VARCHAR - string(0-255), can store characters up to given length - VARCHAR(50)
BLOB - string(0-65535), can store binary large object - BLOB(1000) Ex: Images,
Videos, Documents, Audio and other multimedia files.
INT - integer( -2,147,483,648 to 2,147,483,647 ) - INT
TINYINT - integer(-128 to 127) - TINYINT
BIGINT - integer( -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 ) -
BIGINT
BIT - can store x-bit values. x can range from 1 to 64 - BIT(2)
FLOAT - Decimal number - with precision to 23 digits - FLOAT
DOUBLE - Decimal number - with 24 to 53 digits - DOUBLE
BOOLEAN - Boolean values 0 or 1 - BOOLEAN
DATE - date in format of YYYY-MM-DD ranging from 1000-01-01 to 9999-12-31 - DATE
TIME - HH:MM:SS - TIME
YEAR - year in 4 digits format ranging from 1901 to 2155 - YEAR
CHAR: It's a fixed-length character data type. When you define a column as
CHAR(10), for example, it will always occupy 10 characters of storage, regardless
of the actual length of the data stored in it. If you store a shorter string, it
will be padded with spaces to fill the fixed length.

VARCHAR: It's a variable-length character data type. It stores only the characters
you provide plus the overhead required to store the length of the string. For
example, if you define a column as VARCHAR(10) and store the string "Hello", it
will only take up 5 characters of storage, plus some additional bytes to store the
length of the string.

In a CHAR(10) column: "Hello" would occupy 10 bytes because CHAR columns allocate a
fixed amount of space, padding shorter strings with spaces to fill the allocated
space. So, "Hello" would be stored as "Hello " (with six trailing spaces).

In a VARCHAR(10) column: "Hello" would occupy 6 bytes (5 bytes for the characters
"Hello" plus 1 byte to store the length of the string).

-----------------------------------------------------------------------------------
-------------------------------------------------------------------------

1. DQL (Data Query Language) : Used to retrieve data from databases. (SELECT)
2. DDL (Data Definition Language) : Used to define the structure of the database
schema and create, alter, and delete database objects like tables, indexes, etc.
(CREATE, ALTER, RENAME, DROP, TRUNCATE) (CARDT)
3. DML (Data Manipulation Language): Used to manipulate the data within the
database objects of the database. (DELETE, UPDATE, INSERT) (DUI)
4. DCL (Data Control Language): Used to grant & revoke permissions. (GRANT, REVOKE)
5. TCL (Transaction Control Language): Used to manage transactions. (COMMIT, START
TRANSACTIONS, SAVEPOINT, ROLLBACK) (CSSR)

-----------------------------------------------------------------------------------
-------------------------------------------------------------------------

1. SELECT is a fundamental SQL (Structured Query Language) statement used to


retrieve data from a database. It is part of the Data Manipulation Language (DML)
and is used extensively for querying databases to retrieve specific information.

SYNTAX:

SELECT column1, column2, ...


FROM table_name
WHERE condition;

-----------------------------------------------------------------------------------
-------------------------------------------------------------------------

2. CREATE is a SQL (Structured Query Language) statement used to create database


objects, such as tables, indexes, views, or procedures.
SYNTAX:

CREATE TABLE table_name (


column1 datatype,
column2 datatype,
...
CONSTRAINT constraint_name PRIMARY KEY (column_name)
);

CREATE INDEX index_name


ON table_name (column1, column2, ...);

EXAMPLE:

CREATE TABLE employees (


employee_id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
email VARCHAR(100),
department_id INT
);

CREATE INDEX idx_lastname


ON employees (last_name);

-----------------------------------------------------------------------------------
-------------------------------------------------------------------------

3. ALTER is a SQL (Structured Query Language) statement used to modify the


structure of existing database objects, such as tables, views, or procedures.

SYNTAX:

ALTER TABLE table_name


ADD column_name datatype;

ALTER TABLE table_name


DROP COLUMN column_name;

ALTER TABLE old_table_name


RENAME TO new_table_name;

ALTER TABLE table_name


RENAME COLUMN old_column_name TO new_column_name;

EXAMPLE:

ALTER TABLE employees


ADD hire_date DATE;
ALTER TABLE employees
DROP COLUMN hire_date;

-----------------------------------------------------------------------------------
-------------------------------------------------------------------------

4. The DROP command is part of the Data Definition Language (DDL) in SQL
(Structured Query Language) and is used to eliminate existing database objects.
Once a database object is dropped, it is permanently removed from the database,
along with any associated data or metadata.

SYNTAX:

DROP TABLE table_name;

DROP INDEX index_name;

DROP VIEW view_name;

ALTER TABLE table_name


DROP CONSTRAINT constraint_name;

DROP PROCEDURE procedure_name;

-----------------------------------------------------------------------------------
-------------------------------------------------------------------------

5. INSERT is a SQL (Structured Query Language) statement used to add new records or
rows into a database table.

SYNTAX:

INSERT INTO table_name (column1, column2, ...)


VALUES (value1, value2, ...);

EXAMPLE:

INSERT INTO employees (first_name, last_name, age)


VALUES ('Jane', 'Smith', 25),
('Mike', 'Johnson', 35),
('Emily', 'Brown', 28);

-----------------------------------------------------------------------------------
-------------------------------------------------------------------------

6. UPDATE is a SQL (Structured Query Language) statement used to modify existing


records in a database table.

SYNTAX:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

EXAMPLE:

UPDATE employees
SET age = 31, salary = 50000
WHERE employee_id = 1001;

-----------------------------------------------------------------------------------
-------------------------------------------------------------------------

7. GRANT is a SQL (Structured Query Language) statement used to grant specific


privileges or permissions to database objects, such as tables, views, procedures,
or sequences, to database users or roles.

SYNTAX:

GRANT privileges
ON object
TO user_or_role;

EXAMPLE:

GRANT SELECT, INSERT, UPDATE


ON employees
TO user1;

-----------------------------------------------------------------------------------
-------------------------------------------------------------------------

8. REVOKE is a SQL (Structured Query Language) statement used to revoke previously


granted privileges or permissions from database objects, such as tables, views,
procedures, or sequences, that were given to users or roles.

SYNTAX:

REVOKE privileges
ON object
FROM user_or_role;

EXAMPLE:

REVOKE SELECT, INSERT, UPDATE


ON employees
FROM user1;

-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
9. COMMIT is a command used to permanently save the changes made during a
transaction. It is part of the ACID (Atomicity, Consistency, Isolation, Durability)
properties of database transactions, where "D" stands for Durability.

When you execute a COMMIT statement, all the changes made within the current
transaction are made permanent and visible to other users or transactions. Once
committed, the changes cannot be rolled back or undone.

SYNTAX:
COMMIT;

-----------------------------------------------------------------------------------
-------------------------------------------------------------------------

10. ROLLBACK is a command used to undo the changes made during a transaction that
has not yet been committed. It allows you to revert the database back to its state
before the transaction began, effectively canceling or discarding any modifications
made within that transaction.

SYNTAX:
ROLLBACK;

EXAMPLE:

BEGIN TRANSACTION;

UPDATE accounts
SET balance = balance - 100
WHERE account_id = 123;

INSERT INTO transaction_log (account_id, amount)


VALUES (123, -100);

ROLLBACK;

In this example, if an error occurred after the UPDATE statement but before the
INSERT statement, executing the ROLLBACK statement would undo the changes made by
the UPDATE operation, restoring the balance of the accounts table for account_id =
123 to its original value.

-----------------------------------------------------------------------------------
-------------------------------------------------------------------------

11. START TRANSACTION is a command used to initiate a new transaction explicitly.


The START TRANSACTION command marks the beginning of a new transaction, defining a
boundary within which a series of operations will be executed as an atomic unit.

SYNTAX:
START TRANSACTION;
EXAMPLE:

START TRANSACTION;

UPDATE accounts
SET balance = balance - 100
WHERE account_id = 123;

INSERT INTO transaction_log (account_id, amount)


VALUES (123, -100);

COMMIT;

-----------------------------------------------------------------------------------
-------------------------------------------------------------------------

12. A savepoint is a point within a transaction where you can mark a specific point
of progress. It allows you to set a named marker within a transaction so that you
can later roll back to that point if needed. Savepoints provide a way to implement
nested transactions or to perform partial rollbacks within a larger transaction.

SYNTAX:

SAVEPOINT savepoint_name;

ROLLBACK TO SAVEPOINT savepoint_name;

RELEASE SAVEPOINT savepoint_name;

EXAMPLE:

START TRANSACTION;

-- Perform some database operations


INSERT INTO orders (customer_id, amount) VALUES (1, 100);
SAVEPOINT before_payment;

-- Perform more operations


UPDATE customers SET balance = balance - 100 WHERE customer_id = 1;

-- Check if payment was successful


IF payment_failed THEN
ROLLBACK TO SAVEPOINT before_payment; -- Roll back to savepoint if payment
failed
END IF;

-- Commit the transaction


COMMIT;
-----------------------------------------------------------------------------------
-------------------------------------------------------------------------

DIFFERENCE BETWEEN DELETE AND TRUNCATE:

1.DELETE:
- `DELETE` is a DML (Data Manipulation Language) command used to remove specific
rows from a table based on a condition.
- It allows you to specify a condition using a `WHERE` clause to delete only
certain rows that meet the condition. If you omit the `WHERE` clause, it will
delete all rows from the table.
- `DELETE` generates an entry for each deleted row in the transaction log,
making it possible to roll back the changes using a transaction rollback if
necessary.
- It is slower compared to `TRUNCATE`, especially for large tables, because it
processes each row individually.

SYNTAX:
DELETE FROM table_name WHERE condition;

2.TRUNCATE:
- `TRUNCATE` is a DDL (Data Definition Language) command used to remove all rows
from a table without logging individual row deletions.
- Unlike `DELETE`, it doesn't require specifying a condition; it removes all
rows from the table.
- `TRUNCATE` resets any associated identity columns or sequences to their
initial values.
- It's faster and more efficient than `DELETE`, especially for large tables,
because it deallocates data pages rather than removing individual rows.
- `TRUNCATE` doesn't generate entries in the transaction log for each deleted
row, making it non-rollbackable.

SYNTAX:
TRUNCATE TABLE table_name;

-----------------------------------------------------------------------------------
-------------------------------------------------------------------------

KEYS:
1.Primary Key (PK):
- A primary key is a column or a set of columns in a table that uniquely
identifies each row. It must contain unique values and cannot contain NULL values.
There can only be one primary key in a table.
- Example: In a table of employees, an "Employee ID" column might serve as the
primary key.

2.Super Key:
- A super key is a set of one or more columns that uniquely identifies each row
in a table. It can contain more columns than necessary to uniquely identify rows.
- Example: In a table of employees, a combination of "Employee ID" and "Social
Security Number" might form a super key.

3.Foreign Key (FK):


- A foreign key is a column or a set of columns in a table that establishes a
relationship between two tables. It refers to the primary key of another table,
creating a link between them.
- Example: In a table of orders, a "Customer ID" column might serve as a foreign
key linking to the "Customer ID" primary key column in a table of customers.

4.Alternate Key:
- An alternate key is a candidate key that is not selected as the primary key.
In other words, it is a unique column or set of columns that could serve as the
primary key but is not chosen as such.
- Example: In a table of students, both "Student ID" and "Social Security
Number" might be candidate keys, but only one is chosen as the primary key, while
the other becomes an alternate key.

5.Candidate Key:
- A candidate key is a column or a set of columns in a table that can uniquely
identify each row. It means that each candidate key could potentially serve as the
primary key.
- Example: In a table of employees, both "Employee ID" and "Email Address" might
be candidate keys, as each uniquely identifies employees.

6.Composite Key:
- A composite key is a primary key composed of multiple columns. Together, these
columns uniquely identify each row in the table.
- Example: In a table of sales, a composite key might consist of "Order ID" and
"Product ID" columns, ensuring that each combination of order and product is
unique.

7.Unique Key:
- A unique key is a column or a set of columns in a table that ensures the
values stored in the column(s) are unique across the table. Unlike the primary key,
it can contain NULL values (except in SQL Server).
- Example: In a table of email subscribers, the "Email Address" column might
have a unique key constraint to ensure that no two subscribers have the same email
address.

Difference between composite and super key:


Composite Key:
A composite key is a specific type of key used as a primary key in a relational
database. It consists of multiple columns that, when combined, uniquely identify
each row in the table.
The purpose of a composite key is to ensure uniqueness by considering the combined
values of multiple columns.
Composite keys are typically used when no single column can uniquely identify rows
in the table.
Super Key:
A super key is a broader concept that encompasses any set of one or more columns
that uniquely identifies each row in a table.
Unlike a composite key, a super key may include additional columns beyond those
strictly required for uniqueness.
While a super key could be used as a primary key, it might contain more columns
than necessary. It can also include candidate keys and composite keys.

-----------------------------------------------------------------------------------
-------------------------------------------------------------------------

ACID Properties:
1. Atomicity –
- This property ensures that either the transaction occurs completely or it does
not occur at all.
- In other words, it ensures that no transaction occurs partially.
2. Consistency –
- This property ensures that integrity constraints are maintained.
- In other words, it ensures that the database remains consistent before and
after the transaction.
3. Isolation –
- This property ensures that multiple transactions can occur simultaneously
without causing any inconsistency.
- The resultant state of the system after executing all the transactions is the
same as the state that would be achieved if the transactions were executed serially
one after the other.
4. Durability –
- This property ensures that all the changes made by a transaction after its
successful execution are written successfully to the disk.
- It also ensures that these changes exist permanently and are never lost even
if there occurs a failure of any kind.

-----------------------------------------------------------------------------------
-------------------------------------------------------------------------

DATA QUERIES:

1. WHERE:
The WHERE clause is used to filter records

SYNTAX:
SELECT column1, column2, ... FROM table_name WHERE condition;

EXAMPLE:
SELECT * FROM Customers WHERE Country='Mexico';

-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
2. OPERATORS USED:

= : Equal
> : Greater than
< : Less than
>= : Greater than or equal
<= : Less than or equal
<> or != : Not equal.

-----------------------------------------------------------------------------------
-------------------------------------------------------------------------

3. AND, OR and NOT:


- The WHERE clause can be combined with AND, OR, and NOT operators.
- The AND and OR operators are used to filter records based on more than one
condition:
- The AND operator displays a record if all the conditions separated by AND are
TRUE.
- The OR operator displays a record if any of the conditions separated by OR is
TRUE.
- The NOT operator displays a record if the condition(s) is NOT TRUE.

SYNTAX:

SELECT column1, column2, ... FROM table_name WHERE condition1 AND condition2 AND
condition3 ...;

SELECT column1, column2, ... FROM table_name WHERE condition1 OR condition2 OR


condition3 ...;

SELECT column1, column2, ... FROM table_name WHERE NOT condition;

EXAMPLE:

SELECT * FROM Customers WHERE Country=’India’ AND City=’Japan’;

SELECT * FROM Customers WHERE Country=’America’ AND (City=’India’ OR City=’Korea’);

-----------------------------------------------------------------------------------
-------------------------------------------------------------------------

4. DISTINCT:

Removes duplicate rows from query results.

SYNTAX:
SELECT DISTINCT column1, column2 FROM table_name;

-----------------------------------------------------------------------------------
-------------------------------------------------------------------------
5. LIKE:

The LIKE operator is used in a WHERE clause to search for a specified pattern in a
column.

There are two wildcards often used in conjunction with the LIKE operator:
- The percent sign (%) represents zero, one, or multiple characters
- The underscore sign (_) represents one, single character

EXAMPLE:

SELECT * FROM employees

WHERE CustomerName LIKE 'a%'


- Finds any values that start with "a"

WHERE CustomerName LIKE '%a'


- Finds any values that end with "a"

WHERE CustomerName LIKE '%or%'


- Finds any values that have "or" in any position

WHERE CustomerName LIKE '_r%'


- Finds any values that have "r" in the second position

WHERE CustomerName LIKE 'a_%'


- Finds any values that start with "a" and are at least 2 characters in length

WHERE CustomerName LIKE 'a__%'


- Finds any values that start with "a" and are at least 3 characters in length

WHERE ContactName LIKE 'a%o'


- Finds any values that start with "a" and ends with "o"

-----------------------------------------------------------------------------------
-------------------------------------------------------------------------

6. IN:

Filters results based on a list of values in the WHERE clause.

EXAMPLE:

SELECT * FROM products WHERE category_id IN (1, 2, 3);

-----------------------------------------------------------------------------------
-------------------------------------------------------------------------

7. BETWEEN:
Filters results within a specified range in the WHERE clause.

EXAMPLE:

SELECT * FROM orders WHERE order_date BETWEEN '2023-01-01' AND '2023-06-30';

-----------------------------------------------------------------------------------
-------------------------------------------------------------------------

8. IS NULL:

Checks for NULL values in the WHERE clause.

EXAMPLE:

SELECT * FROM customers WHERE email IS NULL;

-----------------------------------------------------------------------------------
-------------------------------------------------------------------------

9. AS:

Renames columns or expressions in query results.

EXAMPLE:

SELECT first_name AS "First Name", last_name AS "Last Name" FROM employees;

-----------------------------------------------------------------------------------
-------------------------------------------------------------------------

10. ORDER BY:

The ORDER BY clause allows you to sort the result set of a query based on one or
more columns.

Syntax: SELECT column1, column2 FROM table_name ORDER BY column1 [ASC|DESC];

EXAMPLE:

SELECT product_name, price FROM products ORDER BY price DESC;

SELECT first_name, last_name FROM employees ORDER BY last_name, first_name;

SELECT column_name FROM table_name ORDER BY column_name NULLS LAST;

SELECT product_name, price FROM products ORDER BY 2 DESC, 1 ASC;

-----------------------------------------------------------------------------------
-------------------------------------------------------------------------

11. GROUP BY:

The GROUP BY clause follows the SELECT statement and is used to group rows based on
specified columns.

Syntax: SELECT column1, aggregate_function(column2) FROM table_name GROUP BY


column1;

EXAMPLE:

SELECT department, gender, AVG(salary) FROM employees GROUP BY department, gender;

SELECT department, AVG(salary) FROM employees GROUP BY department HAVING


AVG(salary) > 50000;

SELECT department, COUNT(*) FROM employees GROUP BY department ORDER BY COUNT(*)


DESC;

Common Aggregate Functions:


- COUNT():
Counts the number of rows in a group or result set.
- SUM():
Calculates the sum of numeric values in a group or result set.
- AVG():
Computes the average of numeric values in a group or result set.
- MAX():
Finds the maximum value in a group or result set.
- MIN():
Retrieves the minimum value in a group or result set.

-----------------------------------------------------------------------------------
-------------------------------------------------------------------------

JOINS:

1) Inner Join:

An inner join combines data from two or more tables based on a specified condition,
known as the join condition.
The result of an inner join includes only the rows where the join condition is met
in all participating tables.
It essentially filters out non-matching rows and returns only the rows that have
matching values in both tables.

SYNTAX:

SELECT columns
FROM table1
INNER JOIN table2
ON table1.column = table2.column;

EXAMPLE:
SELECT Customers.CustomerName, Orders.Product
FROM Customers
INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID;

-----------------------------------------------------------------------------------
-------------------------------------------------------------------------

2) Outer Join
Outer joins combine data from two or more tables based on a specified condition,
just like inner joins.
However, unlike inner joins, outer joins also include rows that do not have
matching values in both tables.
Outer joins are particularly useful when you want to include data from one table
even if there is no corresponding match in the other table.

i) Left Outer Join (Left Join):


A left outer join returns all the rows from the left table and the matching rows
from the right table.
If there is no match in the right table, the result will still include the left
table's row with NULL values in the right table's columns.

EXAMPLE:
SELECT Customers.CustomerName, Orders.Product
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID;

ii) Right Outer Join (Right Join):


A right outer join is similar to a left outer join, but it returns all rows from
the right table and the matching rows from the left table.
If there is no match in the left table, the result will still include the right
table's row with NULL values in the left table's columns.

EXAMPLE:
SELECT Customers.CustomerName, Orders.Product
FROM Customers
RIGHT JOIN Orders ON Customers.CustomerID = Orders.CustomerID;

iii) Full Outer Join (Full Join):


A full outer join returns all rows from both the left and right tables, including
matches and non-matches.
If there's no match, NULL values appear in columns from the table where there's no
corresponding value.
EXAMPLE:

SELECT Customers.CustomerName, Orders.Product


FROM Customers
FULL OUTER JOIN Orders ON Customers.CustomerID = Orders.CustomerID;

-----------------------------------------------------------------------------------
-------------------------------------------------------------------------

3) Cross Join

A cross join, also known as a Cartesian product, is a type of join operation in a


Database Management System (DBMS) that combines every row from one table with every
row from another table.
Unlike other join types, a cross join does not require a specific condition to
match rows between the tables.
Instead, it generates a result set that contains all possible combinations of rows
from both tables.
Cross joins can lead to a large result set, especially when the participating
tables have many rows.

SYNTAX:
SELECT columns
FROM table1
CROSS JOIN table2;

-----------------------------------------------------------------------------------
-------------------------------------------------------------------------

4) Self Join

A self join involves joining a table with itself.


This technique is useful when a table contains hierarchical or related data and you
need to compare or analyse rows within the same table.
Self joins are commonly used to find relationships, hierarchies, or patterns within
a single table.
In a self join, you treat the table as if it were two separate tables, referring to
them with different aliases.

SYNTAX:

SELECT columns
FROM table1 AS alias1
JOIN table1 AS alias2 ON alias1.column = alias2.column;

-----------------------------------------------------------------------------------
-------------------------------------------------------------------------

CONSTRAINTS IN SQL:
1. NOT NULL:
--- ----
Applied only on the column level
By default, any column can have a NULL values
It restricts the columns in a table from having NULL values

Example:
CREATE TABLE Student
(
Student_ID INT NOT NULL,
Roll_No INT NOT NULL,
Name VARCHAR (100)
);

2. UNIQUE:
------
This applies on both table and column level
It ensures that the column has only unique values

Example:
CREATE TABLE Student
(
Student_ID INT UNIQUE,
Roll_No INT UNIQUE,
Name VARCHAR (100)
);

3. DEFAULT:
-------
This applies on both table and column level
It provides a default value for a column if no value is assigned

Example:
CREATE TABLE Product
(
Product_ID VARCHAR (50) NOT NULL,
Product_Name VARCHAR (50) UNIQUE,
Country of Origin VARCHAR (70) DEFAULT ‘India’
);

4. CHECK:
-----
This applies on both table and column level
It is used to restrict the value of a column between a range
It is similar to data validation in Excel

Example:
CREATE TABLE Student
(
Name VARCHAR(100) NOT NULL,
Age INT(2) CHECK (Age >= 21)
);

5. PRIMARY KEY:
------- ---
This applies on both table and column level
The primary Key constraint is a combination of both UNIQUE and NOT NULL
constraints.
It helps to retrieve query results from the table.
Only one PRIMARY KEY can be created per table

Example:
CREATE TABLE Employee
(
Employee ID INT PRIMARY KEY,
Employee Name VARCHAR (55),
Department VARCHAR (55) NOT NULL
);

6. FOREIGN KEY:
------- ---
This applies on both table and column level
It is used to relate two or more tables and prevents the operation that destroys
the link between the tables.
A foreign key can be a primary key if the table is connected by a one-to-one
relationship, not a one-to-many relationship.
Multiple foreign keys can be created per table

Example:
CREATE TABLE Order
(
Order ID INT PRIMARY KEY,
Product ID INT REFERENCES Products (ID)
);

-----------------------------------------------------------------------------------
-------------------------------------------------------------------------

SELECT NTH HIGHEST SALARY:


SELECT DISTINCT age
FROM customers c1
WHERE 1 = (
SELECT COUNT(DISTINCT age)
FROM customers c2
WHERE c2.age >= c1.age
)

SELECT DISTINCT salary


FROM employees
ORDER BY salary DESC
LIMIT n-1, 1;

where n is the rank that you are required to specify


-----------------------------------------------------------------------------------
-------------------------------------------------------------------------

TO COPY DATA FROM ONE TABLE TO ANOTHER:

INSERT INTO employees


SELECT * FROM customers;

-----------------------------------------------------------------------------------
-------------------------------------------------------------------------

TO CREATE A NEW TABLE FROM AN OLDER TABLE THAT IS TO CREATE A DUPLICATE TABLE:

CREATE TABLE EMPLOYEES AS


SELECT * FROM CUSTOMERS;

-----------------------------------------------------------------------------------
-------------------------------------------------------------------------

You might also like