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

Database Next Theory Part

The document discusses various MySQL constraints including NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, and DEFAULT. It also discusses primary keys, foreign keys, transactions, joins including inner, outer, left and right joins, and aggregate and scalar functions in SQL.

Uploaded by

itikhed971
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Database Next Theory Part

The document discusses various MySQL constraints including NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, and DEFAULT. It also discusses primary keys, foreign keys, transactions, joins including inner, outer, left and right joins, and aggregate and scalar functions in SQL.

Uploaded by

itikhed971
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

MySQL CONSTRAINT

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.

MySQL CONSTRAINTs are:

 NOT NULL
 UNIQUE
 PRIMARY KEY
 FOREIGN KEY
 CHECK
 DEFAULT

What is a Primary Key in SQL?


A Primary key is a unique column we set in a table to easily identify and locate data in
queries. A table can have only one primary key.

The primary key column has a unique value and doesn’t store repeating values. A
Primary key can never take NULL values.

Syntax:-

CREATE TABLE tableName (


COL_NAME DATATYPE …,PRIMARY KEY (COLUMN 1)
);

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-

First table: STUDENT

S_Id LastName FirstName CITY

1 MAURYA AJEET ALLAHABAD

2 JAISWAL RATAN GHAZIABAD

3 ARORA SAUMYA MODINAGAR

Second table: ORDERS

O_Id OrderNo S_Id

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-

CREATE TABLE Orders


(

O_Id int PRIMAY KEY,

Order_No int,,

S_Id int FOREIGN KEY REFERENCES persons (S_Id)

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.

Types of Joins in SQL


There are mainly four types of joins that you need to understand. They are:

 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

2 New York 50000

3 Boston 65000

4 San Diego 75000

1.Inner Join

An Inner Join returns only the rows in both tables that match the join condition.

Syntax of Theta Join


SELECT table1.column1, table2.column2

FROM table1

INNER JOIN table2


ON table1.columnX operator table2.columnY;

Example
Query:

SELECT Table1.Name, Table2.Address

FROM Table1

INNER JOIN Table2

ON Table1.Age > Table2.Salary;

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.

Left Outer Join


A Left Outer Join in DBMS returns all the rows from the left table and the matching
rows from the right table. If there is no match, NULL values are returned for the
missing rows.
Syntax of Left Outer Join
SELECT table1.column1, table2.column2

FROM table1

LEFT JOIN table2

ON table1.columnX = table2.columnY;

Example of Left Outer Join


Again Considering the above two tables:

Query:
To perform a Left Outer Join, we can join the two tables on the ID column.

SELECT Table1.Name, Table2.Address

FROM Table1

LEFT JOIN Table2

ON Table1.ID = Table2.ID;

Output:
This query would return the following result:
Name Address

Alice NULL

Bob New York

Charlie Boston

Right Outer Join


A Right Outer Join returns all the rows from the right table and the matching rows
from the left table. If there is no match, NULL values are returned for the missing
rows.

Syntax of Right Outer Join


SELECT table1.column1, table2.column2

FROM table1

RIGHT JOIN table2


ON table1.columnX = table2.columnY;

Example of Right Outer Join


Consider the above two tables:

Query:
To perform a Right Outer Join, we can join the two tables on the ID column.

SELECT Table1.Name, Table2.Address

FROM Table1

RIGHT JOIN Table2

ON Table1.ID = Table2.ID;

Output:
This query would return the following result:

Name Address

Bob New York

Charlie Boston

NULL San Diego

Full Outer Join


A Full Outer Join returns all the rows from both tables and NULL values for the
missing rows.
Syntax of Full Outer Join
SELECT table1.column1, table2.column2

FROM table1

FULL OUTER JOIN table2

ON table1.columnX = table2.columnY;

Example of Full Outer Join


Considering the above-mentioned two tables i.e., Table1 and Table2:

Query:
To perform a Full Outer Join, we can join the two tables on the ID column.

SELECT Table1.Name, Table2.Address

FROM Table1

FULL OUTER JOIN Table2

ON Table1.ID = Table2.ID;

Output:
This query would return the following result:
Name Address

Alice NULL

Bob New York

Charlie Boston

NULL San Diego

SQL | Functions (Aggregate and Scalar Functions)


SQL has many built-in functions for performing calculations on data.

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:

SELECT AVG(column_name) FROM table_name;

Queries:

 Computing average marks of students.

SELECT AVG(MARKS) AS AvgMarks FROM Students;

Output:

AvgMarks

80

 Computing average age of students.


SELECT AVG(AGE) AS AvgAge FROM Students;

Output:

AvgAge

19.4

COUNT(): It is used to count the number of rows returned in a SELECT statement.

It can’t be used in MS ACCESS.

Syntax:

SELECT COUNT(column_name) FROM table_name;

Queries:

 Computing total number of students.

SELECT COUNT(*) AS NumStudents FROM Students;

Output:

NumStudents

 Computing number of students with unique/distinct age.


SELECT COUNT(DISTINCT AGE) AS NumStudents FROM Students;

Output:

NumStudents

FIRST(): The FIRST() function returns the first value of the selected column.

Syntax:

SELECT FIRST(column_name) FROM table_name;

Queries:

 Fetching marks of first student from the Students table.

SELECT FIRST(MARKS) AS MarksFirst FROM Students;

Output:

MarksFirst

90

 Fetching age of first student from the Students table.

SELECT FIRST(AGE) AS AgeFirst FROM Students;


Output:

AgeFirst

19

LAST(): The LAST() function returns the last value of the selected column. It can

be used only in MS ACCESS.

Syntax:

SELECT LAST(column_name) FROM table_name;

Queries:

 Fetching marks of last student from the Students table.

SELECT LAST(MARKS) AS MarksLast FROM Students;

Output:

MarksLast

85

 Fetching age of last student from the Students table.

SELECT LAST(AGE) AS AgeLast FROM Students;


Output:

AgeLast

18

MAX(): The MAX() function returns the maximum value of the selected column.

Syntax:

SELECT MAX(column_name) FROM table_name;

Queries:

 Fetching maximum marks among students from the Students table.

SELECT MAX(MARKS) AS MaxMarks FROM Students;

Output:

MaxMarks

95

 Fetching max age among students from the Students table.

SELECT MAX(AGE) AS MaxAge FROM Students;

Output:
MaxAge

21

MIN(): The MIN() function returns the minimum value of the selected column.

Syntax:

SELECT MIN(column_name) FROM table_name;

Queries:

 Fetching minimum marks among students from the Students table.

SELECT MIN(MARKS) AS MinMarks FROM Students;

Output:

MinMarks

50

 Fetching minimum age among students from the Students table.

SELECT MIN(AGE) AS MinAge FROM Students;

Output:
MinAge

18

SUM(): The SUM() function returns the sum of all the values of the selected

column.

Syntax:

SELECT SUM(column_name) FROM table_name;

Queries:

 Fetching summation of total marks among students from the Students table.

SELECT SUM(MARKS) AS TotalMarks FROM Students;

Output:

TotalMarks

400

 Fetching summation of total age among students from the Students table.

SELECT SUM(AGE) AS TotalAge FROM Students;

Output:
TotalAge

97

Scalar Functions

UCASE(): It converts the value of a field to uppercase.

Syntax:

SELECT UCASE(column_name) FROM table_name;

Queries:

 Converting names of students from the table Students to uppercase.

SELECT UCASE(NAME) FROM Students;

Output:

NAME

HARSH

SURESH

PRATIK
NAME

DHANRAJ

RAM

LCASE(): It converts the value of a field to lowercase.

Syntax:

SELECT LCASE(column_name) FROM table_name;

Queries:

 Converting names of students from the table Students to lowercase.

SELECT LCASE(NAME) FROM Students;

Output:

NAME

harsh

suresh
NAME

pratik

dhanraj

ram

MID(): The MID() function extracts texts from the text field.

Syntax:

SELECT MID(column_name,start,length) AS some_name FROM table_name;

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.

SELECT MID(NAME,1,4) FROM Students;

Output:

NAME
NAME

HARS

SURE

PRAT

DHAN

RAM

LEN(): The LEN() function returns the length of the value in a text field.

Syntax:

SELECT LENGTH(column_name) FROM table_name;

Queries:

 Fetching length of names of students from Students table.

SELECT LENGTH(NAME) FROM Students;

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:

SELECT ROUND(column_name,decimals) FROM table_name;

decimals- number of decimals to be fetched.


Queries:

 Fetching maximum marks among students from the Students table.

SELECT ROUND(MARKS,0) FROM table_name;

Output:

MARKS

90

50

80

95

85

NOW(): The NOW() function returns the current system date and time.

Syntax:

SELECT NOW() FROM table_name;

Queries:
 Fetching current system time.

SELECT NAME, NOW() AS DateTime FROM Students;

Output:

NAME DateTime

HARSH 1/13/2017 1:30:11 PM

SURESH 1/13/2017 1:30:11 PM

PRATIK 1/13/2017 1:30:11 PM

DHANRAJ 1/13/2017 1:30:11 PM

RAM 1/13/2017 1:30:11 PM

FORMAT(): The FORMAT() function is used to format how a field is to be

displayed.

Syntax:

SELECT FORMAT(column_name,format) FROM table_name;

Queries:
 Formatting current date as ‘YYYY-MM-DD’.

SELECT NAME, FORMAT(Now(),'YYYY-MM-DD') AS Date FROM Students;

Output:

NAME Date

HARSH 2017-01-13

SURESH 2017-01-13

PRATIK 2017-01-13

DHANRAJ 2017-01-13

RAM 2017-01-13

What are Clauses in SQL?


Clauses in SQL are similar to conditionals in high-level languages.

SQL being a query language requires a method to apply constraints on the data and
for this we use Clauses.

Types of SQL Clause


1. WHERE Clause in SQL
It is an integral part of any query and allows us to apply constraints on the query
output.
Syntax:
SELECT * FROM tableName WHERE condition;

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 -

1.SELECT * FROM CUSTOMER ORDER BY NAME;

2.SELECT * FROM CUSTOMER ORDER BY NAME DESC;

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-

SELECT COMPANY, COUNT(*) FROM PRODUCT_MAST GROUP BY COMPANY

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-

SELECT column FROM table_name WHERE conditions GROUP BY column ;

Example:

SELECT COMPANY, COUNT(*) FROM PRODUCT_MAST GROUP BY COMPANY;

SQL Subquery
An SQL Subquery, is a SELECT query within another query.

SQL has many built-in functions for performing calculations on data.

What is subquery in SQL?

A subquery is a SQL query nested inside a larger query.

 A subquery may occur in :

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.

You can use a subquery in a SELECT, INSERT, DELETE, or UPDATE statement to


perform the following tasks:

 Compare an expression to the result of the query.

 Determine if an expression is included in the results of the query.

 Check whether the query selects any rows.

SQL Subqueries Example :

We have the following two tables 'student' and 'marks' with common field 'StudentID'.

Student Marks

1.SELECT * FROM `marks`WHERE studentid = 'V002';

Query result:

2.SELECT student.studentid, student.name, marks.total_marks


FROM student , marks
WHERE student.studentid = marks.studentid
AND marks.total_marks > 80;

Query result:
3. Finding Second Highest Salary

Consider below simple table:

Name Salary

Aman 100000

Shubham 1000000

Naveen 40000

Nishant 500000

select * from employee where salary=(select Max(salary) from employee);

You might also like