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

SQL Complete Course

SQL Complete course

Uploaded by

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

SQL Complete Course

SQL Complete course

Uploaded by

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

SQL COMPLETE COURSE DETAILS

C : CREATE

R: READ

U: UPDATE

D: DELETE

TYPES OF DATABASE

RELATIONAL : (RDBMS) DATA STORED IN ONE OR MORE TABLES, TABLES HAVE ROWS AND COLUMNS
AND HAVE UNIQUE KEYS

EG: SQL, ORACLE, POSTGRESQL

(NON SQL) NON REALATIONAL: stored in traditional table, key value stores

WHY SQL?

1.PROCESSING SPEED

2.MINIMAL REQUIREMENT CODING

3.EASIER DATA MANIPULATION

4.RECTRICTED ACCESS

*[LEARN ABOUT TYPES OF DATA TYPES AND NUMERIC DATATYPES AND DATE TYPES]*

CRUD OPERATIONS:
DDL: DML: DCL: TCL:

DATA DEFINITION DATA MANAGEMENT DATA CONTROL TRANSACTION CONTROL


LANGUAGE LANGUAGE LANGUAGE LANGUAGE

 CREATE NEW  INSERT DATA  GRANT: GIVE  COMMIT:


DATABASE OR INTO THE TABLE ACCESS SAVES THE WORK
TABLE PRIVILAGE TO THE DONE
 UPDATE EXISTING DATABASE
 ALTER THE DATA INTO THE  ROLLBACK:
STRUCTURE OF THE TABLE  REVOKE: WRESTORES TO
DATABASE(ADDING A WITHDRAWS THE LAST
COLUMN) PRIVILAGE COMMIT
 DELETE SPECIFIC
 DROP OBJECTS FROM RECORD IN THE  SAVEPOINT:
THE DATABASE TABLE IDENTIFY A POINT
IN THE
TRANSACTION TO
 TRUNCATE: TO WHICH YOU CAN
REMOVE ALL THE ROLL BACK LATER
RECORDS FROM THE
TABLE BUT NOT THE
TABLE.

PRIMARY KEY

ROLL NO NAME STREAM


1 RAJ ENGINEERING
2 SAI MEDICINE
3 SAI SOFTWARE
4 SAILAJA ARTS
5 GOLI COMMUNICATIONS
6 FRANCEYYY SOCIOLOGY
*PRIMARY KEY IS ALWAYS  WE CAN HAVE MANY
UNIQUE UNIQUE KEYS.

WHILE CREATING A TABLE WE


HAVE TO MENTION WHICH ONE
NEED TO BE A PRIMARY KEY
EG: CREATE TABLE
STUDENT_DETAILS
(
ROLL_NO INTEGER,
NAME VARCHAR(20),
STREAM VARCHAR(20),
PRIMARY KEY (ROLL)
);

AUTOINCREMENT: Automatically fill the details by giving starting key and the identity command

Eg: CREATE TABLE STUDENT_DETAILS


(
ROLL INTEGER identity(1,1) not null , ---- autoincrement starting with 1 and will
automate by +1.. here we can give identity as 2,3,4,etc eg: ROLL INTEGER
identity(1,2)
Eg: ROLL INTEGER
identity(1,3)
SUBJECT VARCHAR(200) not null,
MARKS DECIMAL(10,2),
FULL_MARKS INTEGER,
ADDRESS_ID VARCHAR(100),
PHONE_NO BIGINT,
NAME VARCHAR(20),
PRIMARY KEY(ROLL)
);

SURROGATE KEY: ANY RANDOM ID FOR PRIMARY KEY

NATURAL KEY: CHOOSING KEY WHICH HAS REAL PURPOSE

FOREIGN KEY: THE KEY THAT IS IN ANOTHER TABLE WHICH IS THE REASIN WE ARE JOINING THE TABLE.

EG: JOIN ORDERS ON SALES.ID = ORDERS.ID

HERE ID IS THE FOREIGN KEY.

COMPOSITE KEY: GIVING MORE THAN 1 PRIMARY KEY IS CALLED COMPOSITE KEY.

EG: CREATE TABLE STUDENT_DETAILS


(CREATE TABLE STUDENT_DETAILS

ROLL_NO INTEGER,

NAME VARCHAR(20),

STREAM VARCHAR(20),

PRIMARY KEY (ROLL)

);

WITH ABOVE QUERY YOU CAN CREATE A TABLE AND INSERT VALUES

ALTER TABLE STUDENT_DETAILS ADD PHONE_N0 BIGINT----(DDL) THIS IS USED TO ADD MORE
COLUMNS
TRUNCATE TABLE STUDENT_DETAILS;----(DML) THIS WILL DELETE THE VALUES OF THE TABLE
BUT NOT THE TABLE.

DROP TABLE STUDENT_DETAILS; ----- TO DELETE COMPLETE TABLE.--- DDL

CONVERT FUNCTION: SELECT CONVERT(varchar(7),total_price)from sailaja_orders


Used for converting

SQL OPERATORS:
ARTHEMATIC OPERATIONS

+ ADD
- SUBRACT
* MULTIPLY
/ DIVIDE
% MODULO

BITWISE OPEARTIONS

& BITWISE AND


| BITWISE OR
^ BITWISE EXCLUSIVE OR

COMPARISION OPERATORS

= EQUAL TO
> GREATER THAN
< LESS THAN
>= GREATER THAN OR EQUAL TO
<= LESS THAN OR EQUAL TO
<> NOT EQUAL TO

COMPOUND OPERATORS

+= ADD EQUALS
-= SUBTRACT EQUALS
*= MULTIPLY EQUALS
/= DIVIDE EQUALS
%= MODULO EQUALS
&= BITWISE AND EQUALS
^-= BITWISE EXCLUSIVE EQUALS
\*= BITWISE OR EQUALS
LOGICAL OPERATORS AGGREGATE AND QUERY
ALL OPERATORS
AND BETWEEN
ANY IS NULL: EMPTY
BETWEEN NOT NULL: NOT EMPTY
EXISTS DISTINCT : NO DUPLICATES
IN AVG : AVERAGE FUNCTION
LIKE COUNT: COUNTIN NO. OF ENTRYS
NOT MAX: MAXIMUM
OR MIN: MINIMUM
SOME SUM: AGGREAGATE VALUE
LIMIT

STRING FUNCTIONS:

Char_length, length, charindex,concat,


left&right,replace,reverse,substr,substring,trim,upper,lower,t
rim,itrim,rtrim,concat_ws, DIF

WILDCARD: “LIKE”---

%: ZERO OR MULTIPLE CHARACTERS (WE CAN USE * ALSO IN% PLACE)

_: ONE CHARACTER( WE CAN USE ? ALSO IN PLACE OF _)

__: 2 CHARACTERS

Eg: select* from students where student_name like ‘rob%’ OR ‘%OB%’

LIKE Operator Description

WHERE Finds any values that start with "a"


CustomerName LIKE 'a
%'

WHERE Finds any values that end with "a"


CustomerName LIKE
'%a'
WHERE Finds any values that have "or" in any position
CustomerName LIKE
'%or%'

WHERE Finds any values that have "r" in the second position
CustomerName LIKE
'_r%'

WHERE Finds any values that start with "a" and are at least 2
CustomerName LIKE characters in length
'a_%'

WHERE Finds any values that start with "a" and are at least 3
CustomerName LIKE characters in length
'a__%'

WHERE ContactName Finds any values that start with "a" and ends with "o"
LIKE 'a%o'

Symbol Description Example

* Represents zero or more bl* finds bl, black, blue, and


characters blob

? Represents a single h?t finds hot, hat, and hit


character

[] Represents any single h[oa]t finds hot and hat, but


character within the
brackets not hit

! Represents any character h[!oa]t finds hit, but not hot


not in the brackets and hat

- Represents any single c[a-b]t finds cat and cbt


character within the
specified range

# Represents any single 2#5 finds 205, 215, 225,


numeric character 235, 245, 255, 265, 275,
285, and 295

Symbol Description Example

% Represents zero or more bl% finds bl, black, blue, and


characters blob

_ Represents a single h_t finds hot, hat, and hit


character

[] Represents any single h[oa]t finds hot and hat, but


character within the not hit
brackets

^ Represents any character h[^oa]t finds hit, but not hot


not in the brackets and hat
- Represents any single c[a-b]t finds cat and cbt
character within the
specified range

LIKE Operator Description

WHERE CustomerName LIKE Finds any values that starts with "a"
'a%'

WHERE CustomerName LIKE Finds any values that ends with "a"
'%a'

WHERE CustomerName LIKE Finds any values that have "or" in any position
'%or%'

WHERE CustomerName LIKE Finds any values that have "r" in the second position
'_r%'

WHERE CustomerName LIKE Finds any values that starts with "a" and are at least
'a__%' 3 characters in length

WHERE ContactName LIKE 'a Finds any values that starts with "a" and ends with
%o' "o"
 SELECT TOP 3 MARKS FROM STUDENTS ------ FILTERING BASED ON THE NO. OF ENTRIES WE
WHERE MARKS>95
 ORDER BY ASC /DESC ------- THIS WILL GIVE IN ASC/DESC ORDER.
 SELECT NAME, LEN(NAME) AS LEN_NAME FROM STUDENT_DETAILS----- THIS TO FIND
THE LENGTH OF THE CHARACTERS.
 AS IS ALIAS FOR GIVING NAME. LIKE NEW NAME.
 SELECT CHARINDEX('A','SAILAJA')--- THIS IS CHARACTER INDEX WHIH SHOWS THE
INDEX COUNT OF ALPHABET IN GIVEN CHARACTER.
 SELECT CONCAT('SAILAJA',' ','MAGGIDI') AS FULL_NAME ---- TO CONCATE

 SELECT *FROM STUDENT_DETAILS ------ TO SELECT THE NAME THAT STARTS WITH
LETTER S
WHERE LEFT(NAME,1) IN('S')
 SELECT *FROM STUDENT_DETAILS ------TO SELECT THE NAME THAT ENDS WITH
LETTER UWHERE LEFT(NAME,1) IN('U')
 SELECT *FROM STUDENT_DETAILS
WHERE LEFT(NAME,1) IN('A','E','I','O','U') AND RIGHT(NAME,1)
IN ('A','E','I','O','U') --------TO START AND END WITH AEIOU. HERE ‘IN’
FUNCTIONS IS TO CHECK THE GIVEN CHARACTER IS PRESENT IN THE TABLE OR NOT.

 select replace(NAME,'ai','ha') from STUDENT_DETAILS ---- TO REPLACE THE


CHARACTERS WE WANT
 select name, REVERSE(name) from STUDENT_DETAILS--- this reverses the
characters.
 select SUBSTRING(name,1,4)first_3_charcters from STUDENT_DETAILS ---strtng
from 1st letter to 4th letter is printed and first_3_charcters is alias. We
can give alias without as in this way. But for substrn we need to know the
no. of characters.
 select TRIM(NAME,1) AS T_N FROM STUDENT_DETAILS---- THIS TRIMS THE LETTERS
WE WANT
 select LEFT(Rtrim(NAME),1)L_T ---LEFT TRIM OF CHARACTERS FROM NAMES
from STUDENT_DETAILS
 select RIGHT(Ltrim(NAME),1)L_T
from STUDENT_DETAILS ----- RIGHT TRIM OF CHARACTERS FROM NAMES
 SELECT UPPER('ok')----- writes in upper case
 SELECT lower('OK')------ writes in lower case
 SELECT CONCAT_WS(' ',FIRST_NAME,LAST_NAME) FROM NAMES---- BY GIVING
QUOTATIONS IN FIRST REMAINING FUNCTION WILL RUN
 SELECT * FROM Orders WHERE SALES>1000 LIMIT 3 ---SHOWS THE OUTPUT WITH 3
ENTRIES

DATE TIME FUNCTIONS

CAST,YEAR,MONTH,DAY,TIME,DATEADD,DATEDIFF,DATEPART
 SELECT
GETDATE()CURRENT_,DAY(GETDATE())DAY_,MONTH(GETDATE())MONTH_,YEAR(GETDATE())
YEAR_;
 SELECT CAST( 11.9 AS VARCHAR(300)); -- USED TO CHANGE THE DATATYPE.
 SELECT CAST(GETDATE() AS TIME); --- THIS GIVES TIME
 SELECT DATEADD(YEAR,1, GETDATE()) ---- TO KNOW EXCATLY AFTER 1 YEAR.

MATHEMATICAL FUNCTIONS

CEIL, FLOOR, POWER, ROUND

 SELECT POWER(5678,2); ----- FIRST NO. DENOTES BASE NUMBER AND SECOND
DENOTES THE POWER
 SELECT ROUND(35678.3456,2)----- HERE IM TAKING 2 I.3 I WANT 2 VALUES AS
DECIMAL.
 SELECT FLOOR(25.75) -----OUTPUT(25)--- CLOSEST INTEGER.IT HAS 2 CONDITIONS
i.e NO>25.75 OR NEAREST TO 25.75
 SELECT CEILING(25.75)----OUTPUT(26)---- HERE NO<25.75 OR NEAREST INTEGER

AGGREGATE FUNCTION

GROUP BY AND HAVING CLAUSE


AVG,COUNT.LISTAGG,MAX,MIN

 GROUP BY: GROUPING THE SIMILAR DATA IN THE GIVEN TABLE and this works with aggregate
functions only.

select max(phone_no) from students


group by country; ----- group by working with aggregate
function max

 HAVING: THIS FUNCTION WORKS AFTER GROUP BY AND WITH AGGREGATE VALUES ONLY. It
should be worked only with group clause. And with aggregate only.
SELECT SUM(Sales)TOTAL_SALES
from Orders
group by Region
having sum(sales)>1000;

 COUNT: COUNTING SELECT COUNT(*) FROM ORDERS


 AVERAGE : SELECT avg(sales) from Orders
 MAX: SELECT MAX(sales) from Orders
 MIN: SELECT MAX(sales) from Orders

In sql null is not equal to null.

JOINS IN SQL
Left join
Right join
Inner join
Cross join
Self join
Full outer join

 LEFT JOIN(LEFT OUTER JOIN): ALL ENTRIES FROM LEFT TABLE IS


PRESENTED WITH MATCHING FACTORS FROM THE RIGHT TABLE
(COMMON FACTOR)it includes null values
SELECT * FROM returns R
LEFT JOIN Orders O
ON R.Order_ID= O.Order_ID ----- HERE LEFT JOINED BY returns TABLE AND
ALL RECORDS ARE DISPLAYED.
What comes left of join is left table

 RIGHT JOIN(RIGHT OUTER JOIN): ALL ENTRIES FROM RIGHT TABLE


IS PRESENTED WITH MATCHING FACTORS FROM THE LEFT TABLE
(COMMON FACTOR) it includes null values

SELECT * FROM returns r


right JOIN Orders o
ON r.Order_ID = o.Order_ID ---- HERE right JOINED BY orders TABLE AND
ALL RECORDS ARE DISPLAYED
What comes right of join is right table

 Inner join: It matches the common factors by eliminating


the nulls
SELECT * FROM returns r
inner JOIN Orders
ON r.Order_ID = o.Order_ID --- matching values of both
tables with all entries from both tables without including nulls

 Full join(FULL OUTER JOIN): gives both matching and


unmatching records from both the table.
SELECT * FROM returns r
full outer JOIN Orders o
ON r.Order_ID = o.Order_ID

 Self join: It is a subset of other joins


select* from employee emp inner join employee man on emp.manager_id=
man.emp_name

 CROSS JOIN: JOINS EVERY ROW WITH OTHER TABLE


select c.cust_first_name, o.order_date from customers c
cross join orders o

ORDER OF EXECUTION
FROM AND JOINS
WHERE
GROUP BY
HAVING
SELECT
DISTINCT
ORDER BY
LIMIT/OFFSET

CASE: The CASE expression goes through conditions and returns a value when the first
condition is met (like an if-then-else statement). So, once a condition is true, it will stop
reading and return the result. If no conditions are true, it returns the value in the ELSE
clause.

EG:
select
case
when Sales>10000 then 'gain'
when Sales between 10000 and 5000 then 'ok'
else 'loss'
end as 'status'
,*
from Orders
WE CAN add joins also below…

ANALYTICAL FUNCTIONS ADVANCED SQL


 RANK: This function will assign the number to each row within the partition of an
output. It
assigns the rank to each row as one plus the previous row rank.

Eg: SELECT * , RANK() OVER (ORDER BY Sales desc) rnk from Orders

 DENSE RANK : The DENSE_RANK() is a window function that assigns ranks to rows in
partitions with no gaps in the ranking values. If two or more rows in each partition have
the same values, they receive the same rank. The next row has the rank increased by
one.

Eg: SELECT * , DENSERANK() OVER (ORDER BY Sales desc) DENSE_RNK from


Orders

 ROW NUMBER: The Row_Number() function can provide a unique sequential number
for each row within the result set for a given SQL query.

EG: SELECT * , ROW NUMBER() OVER (ORDER BY Sales desc) ROW_NUM from
Orders

 PARTITION BY : This divides the rows or query result set into small partitions

SELECT *,RANK() OVER(PARTITION BY Region order by Sales desc)emp_rank from


Orders

 ROW BWTWEEN : It specifies a fixed number of rows that precede or follow the current row
regardless of their value.

select *, sum(Sales) over(order by Order_ID rows between 1 preceding and 1


following) total_sales_t_y_nxtday
from Orders where Order_ID is not null

 PIVOT TABLE: PIVOT rotates a table-valued expression by turning the unique values from
one column in the expression into multiple columns in the output. And PIVOT runs
aggregations where they're required on any remaining column values that are wanted in
the final output.
EG: select * from
(select b.order_id, concat(a.cust_first_name,' ',a.cust_last_name)full_name from
customers a
inner join orders b on a.cust_id=b.cust_id)a
pivot(count(order_id) for full_name in (['sriraj Rangu' ],['sailaja maggidi'],
['james camaroon'])
)pivot_table;

OR

ELECT* from
(select order_id, cust_id from orders)a
pivot(
count(order_id) for cust_id in ([1],[4],[6])
)pivot_table;

CTE: COMMON TABLE EXPRESSION


What is CTE in SQL?
CTE was introduced in SQL Server 2005, the common table expression (CTE) is a
temporary named result set that you can reference within a SELECT, INSERT,
UPDATE, or DELETE statement. You can also use a CTE in a CREATE view, as part of
the view's SELECT query.

CTE IS THE SUBSET OF THE DATA WE HAD AND WE CAN USE IN MANY TIMES TO SOLVE OUR
QUERIES. It is a temporary table extracting from main table

You might also like