>> 4 Categories
## DDL - Data Definition Language - Used to define format and type i.e. structure of objects.
-- CREATE, ALTER, DROP, TRUNCATE, COMMENT, RENAME
## DML - Data Manipulation Language - Used to manipulate data stored in tables.
-- SELECT, INSERT, UPDATE, DELETE, MERGE, CALL, EXPLAIN PLAN, LOCK TABLE
## DCL - Data Control Language - Used to define roles, permissions, referential integrities and other security features.
-- GRANT, REVOKE
## TCL - Transactional Control Language - Used to manage transactions happening in database.
-- COMMIT, ROLLBACK, SAVEPOINT, SET TRANSACTION
>> Objects
>> General
>> Tables - Objects which will stay permanently in database. Contains columns and rows.
- -- Access the View
- -- Access the Synonym
>> Programmabilty
-- Functions - Used to define custom functions which will be used as part of SQL statements. Ex. SUM, DATEDIFF, LEN etc.
- RETURNS INT
- -- Access the Function
- -- Access the SP
- EXEC SP1
- -- Trigger to insert an entry to history table when anything changes in Emp1 table
- ON Emp1
- (:old.ID,
- :old.FirstName,
- :old.LastName,
- :old.Salary);
- END;
-- Rules - Specifying rules to a column in a table. i.e. Age column should be between 15 to 60.
- --To validate data entry for Salary field
- CREATE RULE SalaryRule
>> Security
-- Users - Associated users to a DB.
-- Roles - Roles for a DB. roles can be assigned to schemas to achieve security
-- Schemas - We can say, Container of objects. Schemas will have associated user and role. But user will not be direct owner of objects.
>> Indexes - To speed up the performance of DB.
-- Clustered Index - Comprises actual rows of data
-- Non-Clustered Index - Comprises pointers key columns data and pointers to actual row data.
>> Cursors - Temperary area of system memory which holds the result record set for the query. But at a time one row only can be processed from active set. Programmers use this active set to process each rows in their procedures.
>> Commands and Functions
## CREATE - Used to create objects
## ALTER - Used to alter the structure of objects
- -- Adding an column
## RENAME - Used to rename objects.
- SP_RENAME 'Emp1', 'Emp111'
- SELECT * FROM Emp1
## CALL/EXEC- Used to call stored procedures
## EXPLAIN PLAN - Used to see execution plan while querying any objects
## LOCK TABLE - Used to lock a whole table. Programmers use this while a trasaction need to access many rows multiple times as whole table locking will reduce time.
## GRANT - Used to provide permissions for users, roles, schemas etc.
## REVOKE - Used to remove permissions for users, roles, schemas etc.
## COMMIT - To end the transaction; We can't ROLLBACK the transaction after COMMIT, as COMMIT ends the TRAN. Also COMMIT releases savepoints.
## ROLLBACK - Used to rolll back the previous transaction.
- --********* ROLL BACK ********
- -- 1. DELETE -----------------
- BEGIN TRANSACTION
- --Rollback the Delete
- ROLLBACK TRANSACTION
- -- 2. DROP -----------------
- BEGIN TRANSACTION
- --Rollback the DROP
- ROLLBACK TRANSACTION
- -- 3. TRUNCATE -----------------
- BEGIN TRANSACTION
- TRUNCATE TABLE Emp3
- --Rollback the TRUNCATE
- ROLLBACK TRANSACTION
- -- But if you end/finish the txn using COMMIT, you can't rollback ----
- BEGIN TRANSACTION
- TRUNCATE TABLE Emp3
- COMMIT TRANSACTION
- -- RollBack Won't work now as I Commits the txn
- ROLLBACK TRANSACTION
- --SAVEPOINTS to RollBack
- BEGIN TRANSACTION
- SAVE TRANSACTION POINT1
- SAVE TRANSACTION POINT2
- --Rollback to the SAVEPOINT;
- ROLLBACK TRAN POINT1
## Joins - Used to get records from multiple objects with relalationships
>> INNER JOIN
- --Using WHERE
-- LEFT OUTER JOIN
-- RIGHT OUTER JOIN
-- FULL OUTER JOIN
- -- CROSS JOIN - Combines each row in 1st table with each row in 2nd table; So (1st TableRowsCount x 2nd TableRowsCount) will be result rows.
- -- SELF JOIN or NATUAL JOIN - Joining same tabel with different aliases using INNER JOIN.
## UNION - Used to combine results of multiple SELECT quries with OR operation
- -- UNIONS -- Combine 2 or more Select Statements with OR; Need same No. Of Columns, DataType and order for all Select Statements
- -- UNION will return distinct rows only
- -- UNION ALL will return all rows including duplicate
## Constraints
-- NOT NULL
-- DEFAULT
-- UNIQUE
-- PRIMARY key
-- FOREIGN key
-- CHECK
-- INDEX
UNIQUE:
1) Unique Key is nothing but it is uniquely identified each roe in Table.
2) Unique Key Does not Allows Duplicate values but allows only one Null value.
3) Primary key is default Non- Clustered indexes
NOT NULL:
1) NOT NULL constraint wont allow null values.
2) Any column can be added this constraint.
PRIMARY KEY: = UNIQUE + NOT NULL
1) Primary key is nothing but it is uniquely identified each roe in Table.
2) Primary key Does not Allows Duplicate values and Null values.
3) Primary key is default Clustered indexes
4) One table can have only one Primary key.
-- Aggregate - SUM, AVERAGE, COUNT, MIN, MAX
-- Logical - AND, OR, NOT
-- Clauses/Operators - WHERE, GROUP BY, ORDER BY, HAVING, FROM, IN, LIKE, DISTINCT, BETWEEN, TOP
** HAVING - only for SELECT statements; Mostly used with GROUP BY; If used without GROUP BY, just act as WHERE
- HAVING is WHERE for Group of rows; WHERE is for individual rows
- -- GROUP BY
- -- HAVING vs WHERE
- FROM Emp1 INNER JOIN Emp2
- -- ORDER BY
- -- LIKE
- -- IN
- -- AND / OR
- -- MIN / MAX / COUNT / SUM
- -- DISTINCT
- -- BETWEEN
-- WildCards - %, _, [charlist], [!charlist] or [^charlist]
- SELECT * FROM Emp1 WHERE Emp1.FirstName LIKE 'Shan%'
- SELECT * FROM Emp1 WHERE Emp1.LastName LIKE '_el' -- _indicate any single char
- SELECT * FROM Emp1 WHERE Emp1.FirstName LIKE 'Shan[abm]%'
- SELECT * FROM Emp1 WHERE Emp1.FirstName LIKE 'Shan[^ma]%' -- OR ---
- SELECT * FROM Emp1 WHERE Emp1.FirstName LIKE 'Shan![ma]%'
Most Interviewers will ask these questions.
1. How to identify duplicate rows?
- -- ************* Find Duplicate Rows *****************
- WITH TEMP AS
- (
- SELECT
- ROW_NUMBER() OVER(PARTITION BY FirstName ORDER BY FirstName) AS RN,
- FirstName,
- LastName,
- Salary
- FROM Emp1
- )
- SELECT * FROM TEMP WHERE RN > 1
- --PARTITION BY refers based on which column, SQL engine need to find duplicates
- SELECT * FROM TEMP WHERE RN = 1 --Records without duplicates
- ----------------------------------- Method:1 -----------------------------------------
- --1st Max Salary:
- SELECT MAX(Salary) FROM Emp1
- --2nd Max Salary:
- SELECT MAX(Salary) FROM Emp1 WHERE Salary < (SELECT MAX(Salary) FROM Emp1)
- --3rd Max Salary:
- SELECT MAX(Salary) FROM Emp1 WHERE Salary < (SELECT MAX(Salary) FROM Emp1 WHERE Salary < (SELECT MAX(Salary) FROM Emp1))
- --and so on...
- ----------------------------------- Method:2 -----------------------------------------
- --Form a dynamic sub table with row numbers after ordering by salary and select by row number.
- --Nth Max Salary:
- SELECT FirstName, LastName, Salary FROM
- (SELECT ROW_NUMBER() OVER(ORDER BY Salary DESC) AS RN, FirstName, LastName, Salary FROM Emp1) AS E
- WHERE RN = N
Comments
Post a Comment