Skip to main content

Inner join in sql server

INNER JOIN

Inner join responsible to returns rows which have a match in both tables.
See following example:-
CREATE TABLE #ORDER
(
orderId INT IDENTITY(1,1),
fName VARCHAR(400),
lName VARCHAR(400),
ShipAddress VARCHAR(1000),
dtCreate DATETIME
)

CREATE TABLE #ORDER_DETAILS
(
orderDetailsId INT IDENTITY(1,1),
productName VARCHAR(400),
pPrice DECIMAL(18,2),
iQTY INT,
orderId INT,
dtCreate DATETIME
)

INSERT INTO #ORDER(fName,lName,ShipAddress,dtCreate)
SELECT 'Dilip','SINGH','New Delhi',GETDATE()
UNION ALL
SELECT 'Nirmit','katiyar','Mumbai',GETDATE()
UNION ALL
SELECT 'Raj','Dongra','Jharkhand',GETDATE()
UNION ALL
SELECT 'Salim','safi','Muradnagar UP',GETDATE()


INSERT INTO #ORDER_DETAILS(productName,pPrice,iQTY,orderId,dtCreate)
SELECT 'Product 1', 180,3,1,GETDATE()
UNION ALL
SELECT 'Product 2', 120,1,2,GETDATE()
UNION ALL
SELECT 'Product 3', 100,1,3,GETDATE()
UNION ALL
SELECT 'Product 4', 40,2,4,GETDATE()
UNION ALL
SELECT 'Product 5', 90,1,5,GETDATE()
--INNER JOIN
SELECT ORD.fName,ORD.lName,ORD.ShipAddress,ORDTL.productName, ORDTL.iQTY,ORDTL.pPrice,ORD.dtCreate FROM #ORDER AS ORD
INNER JOIN #ORDER_DETAILS AS ORDTL ON
ORDTL.orderId=ORD.orderId


DROP TABLE #ORDER

DROP TABLE #ORDER_DETAILS


Result;
Here you can see 5 rows from #ORDER_DETAILS table is not showing

Comments

Popular posts from this blog

NOT NULL constraint in sql server

NOT NULL- This constraint is responsible for a column to confirm that a column cannot have a null value. Example- Following we create new table PRODUCT and add six columns where ID, SKU, TITLE, PRICE specify not to accept NULLs. CREATE TABLE PRODUCT ( ID INT NOT NULL, SKU VARCHAR ( 20 ) NOT NULL, TITLE VARCHAR ( 200 ) NOT NULL, PRICE MONEY NOT NULL, DISCRIPTION VARCHAR ( 2000 )   NULL, DTCREATE DATETIME NULL ) If PRODUCT table already created, then to add a NOT NULL constraints to SKU column we use following query.   ALTER TABLE PRODUCT   ALTER COLUMN SKU  VARCHAR ( 20 ) NOT NULL

Constraints in sql server

Constraints   - Constraints are the rules enforced on data columns on table. This ensures the accuracy and reliability of the data in the database. Constraints define some conditions that restricts the column to remain true while inserting or updating or deleting data in column. Constraints can be defined in two ways   1) The constraints can be specified immediately after the column definition. This is called column-level definition.   2) The constraints can be specified after all the columns are defined. This is called table-level definition.   Types of Constraints in SQL-Server NOT NULL - This constraint is responsible for a column to confirm that a column cannot have a null value. DEFAULT – This constraint provides a default value when specified non for this column. UNIQUE - This constraint insure that each row for the column has different value. PRIMARY KEY - Primary key constraint is a combination of a NOT NULL constraint and a UNIQUE constra