Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
20 views

SQL Notes

Uploaded by

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

SQL Notes

Uploaded by

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

SELECT - Extract data from a database

UPDATE- Update data in a database


DELETE- deletes data from a database
INSERT INTO- insert new data into a database
CREATE DATABASE- create a new database
ALTER DATABASE- modifies a database
CREATE TABLE- create a new tabke
ALTER TABLE- to modify the Table
DROP Table- delete the table
CREATE INDEX- CREATEs an Index (Search KEY)
DROP INDEX- deletes an index

ALTER TABLE Employee


ADD Address varchar(500)

(DDL)

To Create table

CREATE TABLE Person(


PersonId Int,
Firstname Varchar(255),
Lastname varchar(255),
Phoneno Int
);

Alter table, to add column

ALTER TABLE Person


Add DOB Date

To delete column

ALTER TABLE Person


DROP COLUMN phoneno

Rename column

ALTER TABLE Person


RENAME COLUMN DOb to Dateofbirth

Modifying the data type

ALTER TABLE Person


Alter COLUMN email Varchar(500);
Insert values (DML)

INSERT into Person(personid, firstname, lastname, dateofbirth, email)


VALUES (1, 'Amir', 'Hussain', '01/08/2000', 'shaikhamirhussain2000@gmail.com')

TO select all the values,

SELECT * FROM Person

Insert the data to the selective column

INSERT INTO Person(personid, firstname, lastname)


VALUES (2, 'Anupama', 'Singh')

The condition for the table.

SELECT * FROM Person WHERE personid = 2

When we need to check the null values

Select * from NXU_Employees


WHERE phone_no is null

When we need to check there is no null values

Select * from NXU_Employees


WHERE phone_no is not null

To ensure that the data is updated correctly so that we can roll back.

BEGIN trans

UPDATE NXU_Employee
SET phone_no = '9078942415'

Commit Trans

To update the particular row command,

UPDATE NXU_Employees
SET phone_no = '9971521402', email = 'anupamasingh@gmail.com'
where emp_id = 2

When I need to update multiple rows with same data,

Update NXU_Employees
SET phone_no = Null, email = Null
Where emp_id in (3,4,5)

To delete a query from a colum using where one condition,

Delete FROM NXU_Employees


WHERE emp_id = 5

To Sort it in Ascending order,

Select * from NXU_Employees


ORDER by last_name Ascend

To sort in Desc ord

Select * from NXU_Employees


ORDER by last_name DESC

To select Distinct values,

Select DISTINCT emp_id from NXU_Employees

AND and OR operators

Select * from NXU_Employees


Where emp_id = 2 and first_name = 'Ritu'
(Both conditions should match for the result)

Select * from NXU_Employees


Where emp_id = 2 and first_name = 'Ritu'
(Where one condition hsouldd match)
CREATE TABLE Cust_Order (
Order_ID INT,
Customber_ID INT,
Order_Date date);

INSERT INTO Cust_Order (Order_ID, Customber_ID, Order_Date)


VALUES (10308, 1, 1996-09-18)

CREATE TABLE Customer (


Customer_ID INT,
Customer_Name Varchar(255),
Contact_Name Varchar(255),
Country Varchar(255));

The select top clause is used to specify the number of records to returns

Select top 3 * from Customer where country = 'Mexico'

Aggregate functions

MIN()
- It returns the smallest values within the selected column

SELECT MIN(customer_id) from Customer


SELECT MIN(order_date) from Cust_Order
SELECT MIN(Numeric COulumn Name) from TableName

MAX()
- It returns the largest values within the selected column

SELECT MAX(customer_id) from Customer


SELECT MAX(order_date) from Cust_Order
SELECT MAX(Numeric COulumn Name) from TableName

COUNT()

- It returns the number of rows in a set

SELECT COUNT(customer_id) from Customer


SELECT COUNT(*) from Cust_Order
SELECT COUNT(Any COulumn Name or *) from TableName
SUM()

- It returns the total sum of numeric column

SELECT SUM(customer_id) from Customer


SELECT SUM(Numeric COulumn Name) from TableName

AVG()

- It returns the average value of the numeric column

SELECT AVG(customer_id) from Customer


SELECT AVG(Numeric COulumn Name) from TableName

To Select all the columns together use IN


IN Operator allows us to specify muliple values in Where clause.

SELECT * FROM Customer WHERE country IN ('Germany', 'Mexico', 'United States')

INSERT INTO Products (product_id, product_name, supplier_id, category_id, unit, price)


Values (5, 'Chef Antons Gumbo mix', 2, 2, 36, 21.35)

To change the datatypr to decimal

ALTER TABLE Products


ALTER Column price Decimal(10,2)

To Update a name with an Apostrophy, we need to use this command

UPDATE Products
Set product_name = ' Chef Anton''s Gumbo Mix' WHERE product_id = 5

To add the Bit integer (True or False) (1,0)

ALTER TABLE Products


Add Is_Active bit

To select the unique values

Select DISTINCT supplier_id from Products


Like operator is used in where clause to search for specific pattern.

Select * from Products WHERE product_name LIKE '%Anton%'

Select * from Products WHERE product_name not LIKE '%Anton%'

Between operators is used to select values within a range.

Select * from Products WHERE price BETWEEN 20 and 30

Select * from Products WHERE price not BETWEEN 20 and 30

Alias

Alias is used to temporarily rename the column heading.

Select * FROM Cust_OrderSelect product_id as [Product ID],


product_name,
supplier_id,
category_id,
unit, price,
is_active
From Products

SQL Joins

Joins are used to combiune rows from two or more table.

Inner Joins

Returns all the rows which match in both tables

SELECT * from (Table A)


Inner JOIN (Table B)
ON A.(Key) = B.(Key)

SELECT * from Cust_Order as A


Inner JOIN Customer AS B
ON A.Customber_ID = B.Customer_ID
LEFT Joins

SELECT * from (Table A)


LEFT JOIN (Table B)
ON A.(Key) = B.(Key)

SELECT * from Cust_Order as A


Left JOIN Customer AS B
ON A.Customber_ID = B.Customer_ID

LEFT JOIN: Returns all the records from the left table and matching records from the right table.

RIGHT Joins

SELECT * from (Table A)


Right JOIN (Table B)
ON A.(Key) = B.(Key)

SELECT * from Cust_Order as A


Right JOIN Customer AS B
ON A.Customber_ID = B.Customer_ID

RIGHT JOIN: Returns all the records from the right table and matching records from the left table.

Left Outer Joint

SELECT * from (Table A)


Left JOIN (Table B)
ON A.(Key) = B.(Key)
WHERE B.Key is NUll

SELECT * from Customer as A


Left JOIN Cust_Order as B
on A.Customer_ID = B.Customber_ID
WHERE B.Customber_ID is NUll

LEFT OUTER JOIN


LEFT Outer JOIN: Returns all the records from the left table and excludes the matching records from
the right table.

RIGHT Outer JOIN

SELECT * from (Table A)


Right JOIN (Table B)
ON A.(Key) = B.(Key)
WHERE A.Key is NUll

SELECT * from Customer as A


RIght JOIN Cust_Order as B
on A.Customer_ID = B.Customber_ID
WHERE A.Customer_ID is Null

RIGHT Outer JOIN: Returns all the records from the right table and excludes matching records from
the left table.

Right Outer Join


Full Join

SELECT * from Customer as A


Full Outer JOIN Cust_Order as B
on A.Customer_ID = B.Customber_ID

Full JOIN: Returns all the records from the left table and the right table.

Full Join
FULL Outer Join

SELECT * from Customer as A


Full Outer JOIN Cust_Order as B
on A.Customer_ID = B.Customber_ID
WHERE A.Customer_ID is Null or B.Customber_ID is Null

Full Outer JOIN: Returns all the records from the left table and the right table and excludes the
matching records from both the tables.

Select Into statement - To select data from one table and insert into new table.

Select * into (new table) FROM (old table)


Select * into Gold_Customer FROM Customer

To enter specific rows,

Select customer_id, customer_name, country into Silver_Customer FROM Customer

For Specific conditions

Select customer_id, customer_name, country


INTO Platinum_Customer
FROM Silver_Customer
Where country = 'Mexico'

SQL Constraints

To specify rules for data in a table

Not Null - Indicate that a column cannot store null value.

Unique - Each row for the column should be unique.


For Single unique conditions

Create table Person_Not_Null (


P_ID INT NOT Null,
Last_Name Varchar(200) ,
First_Name Varchar(200) not Null,
Address Varchar(255),
city Varchar(255),
unique (P_ID)
)

For multiple unique conditions.

Create table Person_Not_Null (


P_ID INT NOT Null,
Last_Name Varchar(200) ,
First_Name Varchar(200) not Null,
Address Varchar(255),
city Varchar(255),
CONSTRAINT UC_P_ID unique (P_ID, last_name)
)

Note - UC_P_ID is user defined

To change a constraint on Alter table

Alter TABLE Customer


Add Unique(customer_id)

To drop a unique constraint

Alter TABLE Customer


DROP CONSTRAINT UCS

Primary Key - Combination of a not null and unique data

Primary Key for single column

CREATE TABLE person_foreign_key(


P_ID INT NOT Null,
Last_Name Varchar(200) ,
First_Name Varchar(200) not Null,
Address Varchar(255),
city Varchar(255),
PRIMARY KEY (p_id)
)

Primary Key Constraints on multiple columnns

Create table Person_Primary_Key (


P_ID INT NOT Null,
Last_Name Varchar(200) ,
First_Name Varchar(200) not Null,
Address Varchar(255),
city Varchar(255),
CONSTRAINT PK_Pid PRIMARY KEY (P_ID, first_name)
)

Primary Key Constrains on alter table

Alter table Person_Primary_Key


ADD PRIMARY KEY (P_ID)

Primary key constrains on multiple columns.

Alter table Person_Primary_Key


ADD CONSTRAINT PK_Pid PRIMARY KEY (P_ID, first_name)

To remove primary key constraints.

Alter table Person_Primary_Key


DROP CONSTRAINT PK_Pid

Table A - It has 6 columns and millions of records.


A1 - Primary Key, A2, A3, A4, A5, A6

Table B - We will add 4 columns here whch is for table A


B1 - Primary Key, A7, A8, A9, A10, A1(As a Foreign Key)

Table C - We will add 2 columns which is for table B.


C1(Primary Key), A11, A12, B1 (Foreign Key)

Foreign Key – In one table points to a primary key in another table

Foreign Key

CREATE TABLE Order_Foreign_Key(


O_ID INT NOT Null,
Order_No Varchar(200),
Person_Id Int,
PRIMARY KEY (O_id),
FOREIGN KEY (person_Id) references person_foreign_key (p_id)
)

Default - Specifies a default value for a column


Get default date

Create table Person_default(


P_ID INT NOT Null,
Last_Name Varchar(200) ,
First_Name Varchar(200) not Null,
Address Varchar(255),
city Varchar(255),
Updated_Date date default getdate()
)

Check - Ensures that the value in column meets a specific condition.

CREATE Table Person_Check(


P_Id INT Identity(1,1),
Name Varchar(100),
Email Varchar(100),
Phone_Number Varchar(100),
Age Int,
Check (Age>= 18),
PRIMARY Key (P_ID))Cust_Order

Auto increment

CREATE Table NXU_Contacts(


Contact_Id INT Identity(1,1),
Name Varchar(100),
Email Varchar(100),
Phone_Number Varchar(100),
PRIMARY Key (Contact_ID))

View

Virtual table based on result side.

Create VIEW Customer_Order_CommonData as


SELECT * from Cust_Order as A
Inner JOIN Customer AS B
ON A.Customber_ID = B.Customer_ID

Exists Operator – This is used to test for the existence of any record in sub querry.

Select customer_name from Customer


where exists (SELECT order_id from Cust_Order where Cust_Order.Customber_ID =
Customer.Customer_ID)
if Exists (Select 'X' from Customer where country = 'Germany')
Begin
Select 1
End

if Exists (Select 'X' from Customer where country = 'Germany')


Begin
Select 1
End

Else

Begin
Select 2
End

Any Operator – It returns a Boolean value as a result.


(Returns True if any of the sub query meet the conditions)

Select customer_id from Customer where customer_id = Any


(Select customber_id from Cust_Order where order_id = 10309)

All Operator – It returns true if all of the sub query value meets the conditions.

Select customer_id from Customer where customer_id = all


(Select customber_id from Cust_Order)

Not Operator – Not in

SELECT * FROM Customer where country not in ('Mexico')

Not = operator ! =

SELECT * FROM Customer where country ! = 'Mexico'

SELECT * FROM Customer where customber_id ! > 36

Not Like

SELECT * FROM Customer where customer_name not LIKE '%Ana%'

Not Between

Select * from Customer where customer_id not BETWEEN 30 and 40

Between
Select * from Customer where customer_id BETWEEN 30 and 40

Comments

Any text start with -- operator will not be executed.

-- Select * from Customer where customer_id not BETWEEN 30 and 40

M SQL Operator

Arithmetic operators

Add (+)
Subtract (-)
Multiply (*)
Divide (/)
Modulo (%)

Bitwise Operators
And (&)
OR (|)
Bitwise exclusive or (^)

Comparison Operators

Equal to (=)
Greater than (>)
Less than (<)
Greater than or Equal to (>=)
Less than or Equal to (<=)
Not Equal to (!=) (<>)

Group by

The statement groups rows that have the same value into summary rows.

Find the number of customers in each country.

This is often used with the aggregate (Count(), min(), max(), SUM(), Avg() function.)

Select count(customer_id), country from Customer


GROUP By country

Case (Like IF Else statement)

This goes through conditions and returns a value when the first condition is met.

Select order_id, quantity,


Case when quantity > 10 then 'The quantity is greater than 10'
When quantity = 10 then 'Quantity is 10'
Else 'Quantity is under 10'
End as quantitytext
From Cust_Order
When case will be 0, the show No when case will be 1, then show Yes.

Null Function

Select customer_id, customer_name, isNull (is_active, 0) As is_active


FROM Customer

Having

Having clause was added to SQL because the where keyword cannot be used with aggregate function.

Select Count(customer_id), country FROM Customer


GROUP By country
HAVING COUNT(customer_id) = 2

Union
Store Procedures

You might also like