0% found this document useful (0 votes)
6 views14 pages

SQL JOIN

Ist the pdf of database which consist of join fungiform theiry

Uploaded by

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

SQL JOIN

Ist the pdf of database which consist of join fungiform theiry

Uploaded by

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

DML - Data Manipulation Language

DDL - Data Definition Language


DCL - Data Control Language
TCL - Transaction Control Language
DQL - Data Query Language

DDL
^^^
Create To create tables in the database.
Alter Alters the structure of the database.
Drop Delete tables from database.
Truncate Remove all records from a table, also release the space occupied by those
records

DML
^^^
Insert Inserts data into a table
Update Updates the existing data within a table.
Delete Deletes all records from a table, but not the space occupied by them.

DCL
^^^
Grant Grants permission to one or more users to perform specific tasks.
Revoke Withdraws the access permission given by the GRANT statement

TCL
^^^
Commit Saves any transaction into the database permanently.
Roll back Restores the database to last commit state.
Save point Temporarily save a transaction so that you can rollback

DQL
^^^
Select : It displays the records from the table.

===================================================================================
==========================================

DML
^^^
DELETE COMMAND
^^^^^^^^^^^^^^

The DELETE command permanently removes one or more records from the table. It
removes the entire row, not individual fields of the row, so no field argument is
needed.

The DELETE command is used as follows :

DELETE FROM table-name WHERE condition;

For example to delete the record whose admission number is 104 the command is given
as follows:

DELETE FROM Student WHERE Admno=104;


104 Abinandh M 18 Chennai
The following record is deleted from the Student table.

To delete all the rows of the table, the command is used as :

DELETE FROM Student

The table will be empty now and could be destroyed using the DROP command

UPDATE COMMAND
^^^^^^^^^^^^^^

The UPDATE command updates some or all data values in a database. It can update
one or more records in a table.

The UPDATE command specifies the rows to be changed using the WHERE clause and the
new data using the SET keyword.

The command is used as follows:

UPDATE <table-name> SET column-name = value, column-name = value,…


WHERE condition;

For example to update the following fields:

UPDATE Student SET Age = 20 WHERE Place = ῾Bangalore᾿;

The above command will change the age to 20 for those students whose place is
“Bangalore”

To update multiple fields, multiple field assignment can be specified with the SET
clause
separated by comma.

For example to update multiple fields in the Student table, the command is given
as:

UPDATE Student SET Age=18, Place = ‘Chennai’ WHERE Admno = 102;

-----------------------------------------------------------------------------------
----------------------------
DDL
^^^
ALTER COMMAND
^^^^^^^^^^^^^

The ALTER command is used to alter the table structure like adding a column,
renaming
the existing column, change the data type of any column or size of the column or
delete the
column from the table.
ALTER TABLE <table-name> ADD <column-name><data type><size>
ALTER TABLE Student ADD Address char;

To modify existing column of table, the ALTER TABLE command can be used with MODIFY
clause like wise:

ALTER TABLE <table-name> MODIFY<column-name><data type><size>;


ALTER TABLE Student MODIFY Address char (25)

The ALTER command can be used to rename an existing column in the following way :

ALTER TABLE dept ALTER COLUMN dob varchar(100);


exec sp_rename 'dept.cgpa','mark','column';

The ALTER command can also be used to remove a column or all columns, for example
to remove a particular column, the DROP COLUMN is used with the ALTER TABLE to
remove a particular field.

The command can be used as:


ALTER TABLE <table-name> DROP COLUMN <column-name>

To remove the column City from the Student table,

the command is used as :


ALTER TABLE Student DROP COLUMN City

TRUNCATE command
^^^^^^^^^^^^^^^^
The TRUNCATE command is used to delete all the rows from the table, the structure
remains and the space is freed from the table.

The syntax for TRUNCATE command is:


TRUNCATE TABLE table-name;

For example to delete all the records of the student table and delete the table the
SQL statement
is given as follows:

TRUNCATE TABLE Student;

The table Student is removed and the space is freed

DROP TABLE command


^^^^^^^^^^^^^^^^^^
The DROP TABLE command is used to remove a table from the database. If you
drop a table, all the rows in the table is deleted and the table structure is
removed from the
database. Once a table is dropped we cannot get it back, so be careful while using
DROP
TABLE command.

DELETE FROM Student;


Once all the rows are deleted, the table can be deleted by DROP TABLE command in
the
following way:

DROP TABLE table-name

ALTER TABLE dept ALTER COLUMN dob varchar(100);

exec sp_rename 'dept.cgpa','mark','column';

===================================================================================
=======================

WHERE clause
^^^^^^^^^^^^

The WHERE clause is used to filter the records. It helps to extract only those
records
which satisfy a given condition. For example in the student table, to display the
list of students
of age18 and above in alphabetical order of their names, the command is given as
below:

SELECT * FROM Student WHERE Age>=18 ORDER BY Name

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

ORDER BY clause
^^^^^^^^^^^^^^^^^^

The ORDER BY clause in SQL is used to sort the data in either ascending or
descending
based on one or more columns.

1. By default ORDER BY sorts the data in ascending order.


2. We can use the keyword DESC to sort the data in descending order and the keyword
ASC
to sort in ascending order.

The ORDER BY clause is used as :

SELECT <column-name>[,<column-name>,….] FROM <table-name>ORDER


BY <column1>,<column2>,…ASC| DESC

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

GROUP BY clause
^^^^^^^^^^^^^^^

The GROUP BY clause is used with the SELECT statement to group the students on
rows or columns having identical values or divide the table in to groups.

For example to know


the number of male students or female students of a class, the GROUP BY clause may
be
used. It is mostly used in conjunction with aggregate functions to produce summary
reports
from the database.

The syntax for the GROUP BY clause is

SELECT <column-names> FROM <table-name> GROUP BY <column-name>HAVING


condition]

SELECT Gender FROM Student GROUP BY Gender


SELECT Gender, count(*) FROM Student GROUP BY Gender
-----------------------------------------------------------------------------------
-----

HAVING clause
^^^^^^^^^^^^^

The HAVING clause can be used along with GROUP BY clause in the SELECT statement
to place condition on groups and can include aggregate functions on them.

For example to
count the number of Male and Female students having age greater than or equal to
18.

SELECT Gender , FROM Student GROUP BY Gender HAVING count(*)> = 18

===================================================================================
====================

MIN() - returns the smallest value within the selected column


MAX() - returns the largest value within the selected column
COUNT() - returns the number of rows in a set
SUM() - returns the total sum of a numerical column
AVG() - returns the average value of a numerical column

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

The SQL MIN() and MAX() Functions

The MIN() function returns the smallest value of the selected column.
The MAX() function returns the largest value of the selected column.

SELECT MIN(Price)
FROM Products;

SELECT MAX(Price)
FROM Products;

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

The SQL COUNT() Function


The COUNT() function returns the number of rows that matches a specified criterion.

SELECT COUNT(*)
FROM Products

SELECT COUNT(ProductName)
FROM Products;

SELECT COUNT(DISTINCT Price)


FROM Products;

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

The SQL SUM() Function

The SUM() function returns the total sum of a numeric column.

SELECT SUM(Quantity)
FROM OrderDetails;

SELECT SUM(Quantity)
FROM OrderDetails
WHERE ProductId = 11

SELECT SUM(Quantity * 10)


FROM OrderDetails;

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

The SQL AVG() Function

The AVG() function returns the average value of a numeric column.

SELECT AVG(Price)
FROM Products;

SELECT AVG(Price)
FROM Products
WHERE CategoryID = 1;

===================================================================================
=========================

ASCII (American Standard Code for Information Interchange.)-It is used to get the
ascii code for Specified
--Character.

Select ASCII('A')
Select ASCII('S')

--Character: It is used to get the character for Specified Integer

Select Char(97)
Select Char(115)
--Character Index: It is used to get the position of selected character.

Select CharIndex('L','saran')
Select CharIndex('O','saro')

--Lower: It is used to convert the data's into Small Alphabets.

Select Lower('jai')
Select Lower('Athletic is a Profession and Fitness is a Passion')

--Upper: It is used to convert the data's into Capital Alphabets.

Select Upper('bala')
Select Upper('bala Profession is Athletic')

--LTRIM: It is used to remove the Spaces from starting of the Word.

Select LTRIM('soundar')
Select LTRIM('soundar Passion is Fitness')

--RTRIM: It is used to remove the Spaces from End of the Word.

Select RTRIM('shree ')


Select RTRIM('shree is a leading Keyboard Player in India ')

--Reverse: It is used to reversing the string.

Select Reverse('kamal')
Select Reverse('Athletic')

--Replicate: It is used to Repeat the number of times Specified Data.

Select Replicate('soundar Passion is Fitness ',2)

--Left: It is used to get Left part of the Data with Specified Number of Character.

Select Left('Athletic',3)

--Right: It is used to get Right part of the


Data with Specified Number of Character.

Select Right('Keyboard Player',6)

--Replace: It is used change the character fromone to another.

Select Replace('Queries','e','i')

--Len: It is used to get the length of Specified String.

Select Len('Computer')
===========================================================================

NUMERIC FUNCTION
^^^^^^^^^^^^^^^^

ABS: Returns the absolute value of a number


SELECT Abs(-243.5) AS AbsNum;

ACOS: Returns the arc cosine of a number


SELECT ACOS(0.25);

ASIN: Returns the arc sine of a number


SELECT ASIN(0.25);

ATAN: Returns the arc tangent of a number


SELECT ATAN(2.5);

ATN2: Returns the arc tangent of two numbers


SELECT ATN2(0.50, 1);

AVG: Returns the average value of an expression


SELECT AVG(Price) AS AveragePrice FROM Products;

CEILING:Returns the smallest integer value that is >= a number


SELECT CEILING(25.75) AS CeilValue;

FLOOR Returns the largest integer value that is <= to a number


SELECT FLOOR(25.75) AS FloorValue;

COUNT: Returns the number of records returned by a select query


SELECT COUNT(ProductID) AS NumberOfProducts FROM Products;

MAX Returns the maximum value in a set of values


SELECT MAX(Price) AS LargestPrice FROM Products;

MIN Returns the minimum value in a set of values


SELECT MIN(Price) AS SmallestPrice FROM Products;

PI Returns the value of PI


SELECT PI();

POWER Returns the value of a number raised to the power of another number
SELECT POWER(4, 2);

ROUND Rounds a number to a specified number of decimal places


SELECT ROUND(235.415, 2) AS RoundValue;

SQUARE Returns the square of a number


SELECT SQUARE(64);

SQRT Returns the square root of a number


SELECT SQRT(64)

===================================================================================
===========================
SQL Constraints
^^^^^^^^^^^^^^^

NOT NULL - Ensures that a column cannot have a NULL value


UNIQUE - Ensures that all values in a column are different
PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each
row in a table
FOREIGN KEY - Prevents actions that would destroy links between tables
CHECK - Ensures that the values in a column satisfies a specific
condition
DEFAULT - Sets a default value for a column if no value is specified

NOT NULL
^^^^^^^^
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);

ALTER TABLE Persons


ALTER COLUMN Age int NOT NULL;
-----------------------------------------------------------------

UNIQUE
^^^^^^

CREATE TABLE Persons (


ID int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);

OR

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT UC_Person UNIQUE (ID,LastName)
);

ALTER TABLE Persons


ADD UNIQUE (ID);

ALTER TABLE Persons


DROP CONSTRAINT UC_Person;

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

PRIMARY KEY
^^^^^^^^^^^
CREATE TABLE Persons (
ID int NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);

OR

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT PK_Person PRIMARY KEY (ID,LastName)
);

ALTER TABLE Persons


ADD PRIMARY KEY (ID);

ALTER TABLE Persons


DROP CONSTRAINT PK_Person;

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

FOREIGN KEY
^^^^^^^^^^^
CREATE TABLE Orders (
OrderID int NOT NULL PRIMARY KEY,
OrderNumber int NOT NULL,
PersonID int FOREIGN KEY REFERENCES Persons(PersonID)
);

OR

CREATE TABLE Orders (


OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
CONSTRAINT FK_PersonOrder FOREIGN KEY (PersonID)
REFERENCES Persons(PersonID)
);

ALTER TABLE Orders


ADD CONSTRAINT FK_PersonOrder
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);

ALTER TABLE Orders


DROP CONSTRAINT FK_PersonOrder;

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

CHECK CONSTRAINT
^^^^^^^^^^^^^^^^

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int CHECK (Age>=18)
);

OR

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255),
CONSTRAINT CHK_Person CHECK (Age>=18 AND City='Sandnes')
);

ALTER TABLE Persons


ADD CONSTRAINT CHK_PersonAge CHECK (Age>=18 AND City='Sandnes');

ALTER TABLE Persons


DROP CONSTRAINT CHK_PersonAge;

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

DEFAULT Constraint
^^^^^^^^^^^^^^^^^^

CREATE TABLE Student


(
Admno integer PRIMARY KEY,
Name char(20)NOT NULL,
Gender char(1),
Age integer DEFAULT 17, → (Default Constraint)
Place char(10),
);

CREATE TABLE Orders (


ID int NOT NULL,
OrderNumber int NOT NULL,
OrderDate date DEFAULT GETDATE()
);

ALTER TABLE student


ADD CONSTRAINT df_age
DEFAULT '17' FOR age;

ALTER TABLE Persons


ALTER COLUMN City DROP DEFAULT;

===================================================================================
===============================
SQL JOIN
^^^^^^^^

SELECT Order.Order_id, Customer.Custo_Name, Order.Order_Date


FROM Order
JOIN Customer ON Order.Custo_id=Customer.Custo_id;
-----------------------------------------------------------------------------------
-------
Different Types of SQL JOINs
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

(INNER) JOIN: Returns records that have matching values in both tables

LEFT JOIN: Returns all records from the left table, and the matched
records from the right table

RIGHT JOIN: Returns all records from the right table, and the matched
records from the left table

FULL JOIN: Returns all records when there is a match in either left or
right table

-----------------------------------------------------------------------------------
-------
INNER JOIN
^^^^^^^^^^

SELECT Proid, item_Name, Cat_Name


FROM Pro
INNER JOIN Categ ON Pro.Cat_id = Categ.Cat_id;

SELECT Pro.Proid, Pro.Pro_Name, Categ.Cate_Name


FROM Products
INNER JOIN Categ ON Pro.Cat_id = Categ.cat_id;

THREE TABLE:
^^^^^^^^^^^
SELECT Order.Order_id, Customer.Custo_Name, Categ.Cate_Name
FROM ((Order
INNER JOIN Customer ON Order.Custo_id = Customer.Customer_id)
INNER JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID);

-----------------------------------------------------------------------------------
-----------------------------
SQL LEFT JOIN
^^^^^^^^^^^^^

SELECT Customers.CustomerName, Orders.OrderID


FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
ORDER BY Customers.CustomerName;

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

SQL RIGHT JOIN


^^^^^^^^^^^^^^

SELECT Orders.OrderID, Employees.LastName, Employees.FirstName


FROM Orders
RIGHT JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
ORDER BY Orders.OrderID;
-----------------------------------------------------------------------------------
-----------------------------
SQL FULL OUTER JOIN
^^^^^^^^^^^^^^^^^^^

SELECT Customers.CustomerName, Orders.OrderID


FROM Customers
FULL OUTER JOIN Orders ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;

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

Stored Procedure
^^^^^^^^^^^^^^^^

=> A stored procedure is a prepared SQL code that you can save,
so the code can be reused over and over again.

=> So if you have an SQL query that you write over and over again,
save it as a stored procedure, and then just call it to execute it.

CREATE PROCEDURE pro


AS
SELECT * FROM item GO

EXEC pro;

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

CREATE PROCEDURE pro @model varchar(30)


AS
SELECT * FROM item WHERE model = @model

EXEC pro @model = 'tata';

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

CREATE PROCEDURE pros @model varchar(30), @varient varchar(10)


AS
SELECT * FROM item WHERE model = @model AND varient = @varient
GO;

EXEC pro @model = 'tata', @varient = 'Duster';


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

Triggers in SQL
^^^^^^^^^^^^^^^

=> A trigger is a set of SQL statements that reside in system memory with unique
names. It is a specialized category of stored procedure
that is called automatically when a database server event occurs.
=> A trigger is called a special procedure because it cannot be called directly
like a stored procedure.
The key distinction between the trigger and procedure is that a trigger is called
automatically
when a data modification event occurs against a table.

create Trigger
^^^^^^^^^^^^^^

create trigger trig_dept1


on dept

after insert

as
begin

insert into dbo1


select id , 'ins' , GETDATE()

from inserted

end

Alter Trigger
^^^^^^^^^^^^^

alter trigger trig_dbo


on dept
after insert , delete
as
begin
insert into dbo1
select id , 'ins' , GETDATE()
from inserted

union all

select id , 'del' ,GETDATE()


from deleted
end

You might also like