Database Next Theory Part
Database Next Theory Part
MySQL CONSTRAINT is used to define rules to allow or restrict what values can be
stored in columns. MySQL CONSTRAINTS are used to limit the type of data that can be
inserted into a table.
MySQL CONSTRAINTS can be classified into two types - column level and table level.
NOT NULL
UNIQUE
PRIMARY KEY
FOREIGN KEY
CHECK
DEFAULT
The primary key column has a unique value and doesn’t store repeating values. A
Primary key can never take NULL values.
Syntax:-
Example-
CREATE TABLE Emp(
emp_id varchar(5) NOT NULL,
name varchar(50),
location varchar(50),
experience int,
PRIMARY KEY(emp_id));
SQL FOREIGN KEY
In the relational databases, a foreign key is a field or a column that is used to establish a link
between two tables.
In simple words you can say that, a foreign key in one table used to point primary key in another
table.
Example-
1 99586465 2
2 78466588 2
3 22354846 3
4 57698656 1
o The "S_Id" column in the "Students" table is the PRIMARY KEY in the "Students" table.
o The "S_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders" table
QUERY EXAMPLE-
Order_No int,,
What is a transaction?
In the context of databases and data storage systems, a transaction is any operation that is treated
as a single unit of work, which either completes fully or does not complete at all, and leaves the
storage system in a consistent state.
What are Joins in DBMS?
A join is a way to combine data from two or more tables based on a common column.
For example, let’s say we have two tables: Customers and Orders. The Customers
table contains information about each customer, including their name, address, and
email address. The Orders table contains information about each order, including the
order date, product name, and quantity.
To combine data from these two tables, we can join them on the customer ID column,
which is common to both tables. By doing so, we can retrieve information about each
customer’s orders in a single query.
INNER JOIN
FULL JOIN
LEFT JOIN
RIGHT JOIN
Example-
Table1:
ID Name Age
1 Alice 23
2 Bob 28
3 Charlie 32
Table2:
ID Address Salary
3 Boston 65000
1.Inner Join
An Inner Join returns only the rows in both tables that match the join condition.
FROM table1
Example
Query:
FROM Table1
Output:
This query would return the following result:
Name Address
Here we get an empty table as a result because not a single entry is following the
condition specified in the join
2.Outer Join
An Outer Join in DBMS returns all the rows from one table and the matching rows
from the other table. If there is no match, NULL values are returned for the missing
rows.
FROM table1
ON table1.columnX = table2.columnY;
Query:
To perform a Left Outer Join, we can join the two tables on the ID column.
FROM Table1
ON Table1.ID = Table2.ID;
Output:
This query would return the following result:
Name Address
Alice NULL
Charlie Boston
FROM table1
Query:
To perform a Right Outer Join, we can join the two tables on the ID column.
FROM Table1
ON Table1.ID = Table2.ID;
Output:
This query would return the following result:
Name Address
Charlie Boston
FROM table1
ON table1.columnX = table2.columnY;
Query:
To perform a Full Outer Join, we can join the two tables on the ID column.
FROM Table1
ON Table1.ID = Table2.ID;
Output:
This query would return the following result:
Name Address
Alice NULL
Charlie Boston
1. Aggregate functions:
These functions are used to do operations from the values of the column and a
single value is returned.
1. AVG()
2. COUNT()
3. FIRST()
4. LAST()
5. MAX()
6. MIN()
7. SUM()
2. Scalar functions:
These functions are based on user input, these too returns single value.
1. UCASE()
2. LCASE()
3. MID()
4. LEN()
5. ROUND()
6. NOW()
7. FORMAT()
Students-Table
Aggregate Functions
AVG(): It returns the average value after calculating from values in a numeric
column.
Syntax:
Queries:
Output:
AvgMarks
80
Output:
AvgAge
19.4
Syntax:
Queries:
Output:
NumStudents
Output:
NumStudents
FIRST(): The FIRST() function returns the first value of the selected column.
Syntax:
Queries:
Output:
MarksFirst
90
AgeFirst
19
LAST(): The LAST() function returns the last value of the selected column. It can
Syntax:
Queries:
Output:
MarksLast
85
AgeLast
18
MAX(): The MAX() function returns the maximum value of the selected column.
Syntax:
Queries:
Output:
MaxMarks
95
Output:
MaxAge
21
MIN(): The MIN() function returns the minimum value of the selected column.
Syntax:
Queries:
Output:
MinMarks
50
Output:
MinAge
18
SUM(): The SUM() function returns the sum of all the values of the selected
column.
Syntax:
Queries:
Fetching summation of total marks among students from the Students table.
Output:
TotalMarks
400
Fetching summation of total age among students from the Students table.
Output:
TotalAge
97
Scalar Functions
Syntax:
Queries:
Output:
NAME
HARSH
SURESH
PRATIK
NAME
DHANRAJ
RAM
Syntax:
Queries:
Output:
NAME
harsh
suresh
NAME
pratik
dhanraj
ram
MID(): The MID() function extracts texts from the text field.
Syntax:
specifying length is optional here, and start signifies start position ( starting from 1 )
Queries:
Fetching first four characters of names of students from the Students table.
Output:
NAME
NAME
HARS
SURE
PRAT
DHAN
RAM
LEN(): The LEN() function returns the length of the value in a text field.
Syntax:
Queries:
Output:
NAME
ROUND(): The ROUND() function is used to round a numeric field to the number
of decimals specified.NOTE: Many database systems have adopted the IEEE 754
standard for arithmetic operations, which says that when any numeric .5 is rounded
it results to the nearest even integer i.e, 5.5 and 6.5 both gets rounded off to 6.
Syntax:
Output:
MARKS
90
50
80
95
85
NOW(): The NOW() function returns the current system date and time.
Syntax:
Queries:
Fetching current system time.
Output:
NAME DateTime
displayed.
Syntax:
Queries:
Formatting current date as ‘YYYY-MM-DD’.
Output:
NAME Date
HARSH 2017-01-13
SURESH 2017-01-13
PRATIK 2017-01-13
DHANRAJ 2017-01-13
RAM 2017-01-13
SQL being a query language requires a method to apply constraints on the data and
for this we use Clauses.
Example: Let us now find the employees with an experience of more than 5 years.
Query:
SELECT * FROM DataFlair WHERE experience > 5;
2.ORDER BY
o The ORDER BY clause sorts the result-set in ascending or descending order.
o It sorts the records in ascending order by default. DESC keyword is used to sort the records in
descending order.
Example -
3.HAVING
o HAVING clause is used to specify a search condition for a group or an aggregate.
o Having is used in a GROUP BY clause. If you are not using GROUP BY clause then you can use
HAVING function like a WHERE clause.
Example-
HAVING COUNT(*)>2;
4.GROUP BY
o SQL GROUP BY statement is used to arrange identical data into groups. The GROUP
BY statement is used with the SQL SELECT statement.
o The GROUP BY statement follows the WHERE clause in a SELECT statement and
precedes the ORDER BY clause.
o The GROUP BY statement is used with aggregation function.
Syntax-
Example:
SQL Subquery
An SQL Subquery, is a SELECT query within another query.
o - A SELECT clause
o - A FROM clause
o - A WHERE clause
The subquery can be nested inside a SELECT, INSERT, UPDATE, or DELETE statement or
inside another subquery.
A subquery is usually added within the WHERE Clause of another SQL SELECT statement.
You can use the comparison operators, such as >, <, or =. The comparison operator can also be a
multiple-row operator, such as IN, ANY, or ALL.
A subquery is also called an inner query or inner select, while the statement containing a
subquery is also called an outer query or outer select.
The inner query executes first before its parent query so that the results of an inner query can be
passed to the outer query.
We have the following two tables 'student' and 'marks' with common field 'StudentID'.
Student Marks
Query result:
Query result:
3. Finding Second Highest Salary
Name Salary
Aman 100000
Shubham 1000000
Naveen 40000
Nishant 500000