πΉ DDL | πΈ SCL | πΉ DML | πΈ DQL | πΉ DCL | πΈ TCL | πΉ SFL | |
---|---|---|---|---|---|---|---|
CREATE | USE | INSERT | SELECT | GRANT | COMMIT | CONCAT | REPLACE |
ALTER | UPDATE | WILDCARDS | REVOKE | ROLLBACK | SUBSTRING | LEFT/RIGHT | |
DROP | DELETE | AGGREGATES | SAVEPOINT | CHAR_LENGTH | REVERSE | ||
TRUNCATE | CLAUSES | TRANSACTIONS | LETTER_CASE | REPLICATE | |||
JOINS | TRIM | FORMAT |
- The objective of the SQL report is to understand all the Basic SQL-Server Queries/Scripts as well as all kind of String Functions.
- SQL Server
-
Creating a Database
FSA
-
Creating two Tables
Student
andExams
-
Applying all
categories
of SQL Commands-
${\color{blue}DDL}$ : Defines Database structures. -
${\color{blue}DML}$ : Manipulates Data. -
${\color{blue}DQL}$ : Queries and Retrieves data. -
${\color{blue}DCL}$ : Manages access Permissions. -
${\color{blue}TCL}$ : Controls Transactions. -
${\color{blue}SFL}$ : Returns a single value. -
${\color{blue}WFL}$ : Returns a value based on a set of rows.
-
-
${\color{red}DDL}$ (Data Definition Language)
: It changes the structure of the table like creating a table, deleting a table, altering a table, etc. All the command of DDL are auto-committed that means it permanently save all the changes in the database.- CREATE
[Define DATA TYPES, CONSTRAINTS here]
- ALTER
(Rename/Add/Drop)
- DROP
- TRUNCATE
- CREATE
-
${\color{red}DML}$ (Data Manipulation Language)
: DML commands are used to modify the database. The command of DML is not auto-committed that means it can't permanently save all the changes in the database. They can be rollback.- INSERT
- UPDATE
- DELETE
-
${\color{red}DQL}$ (Data Query Language)
: DQL is used to fetch the data from the database.- SELECT
[mostly OPERATORS used here]
- CLAUSES
[WHERE, GROUP BY, HAVING, ORDER BY, LIMIT/TOP]
- JOINS
[JOIN, LEFT JOIN, RIGHT JOIN, FULL JOIN, SELF JOIN, CROSS JOIN, UNION, UNION ALL, INTERSECT]
- SELECT
-
${\color{red}DCL}$ (Data Control Language)
: DCL commands are used to Grant and Revoke (take back) authority from any database user.- GRANT
- REVOKE
-
${\color{red}TCL}$ (Transaction Control Language)
: TCL commands can only use with DML commands like INSERT, DELETE and UPDATE only.- EGIN TRANSACTION
- COMMIT
- ROLLBACK
- SAVEPOINT
-
${\color{red}SFL}$ (Scalar Functions Library)
: SFL commands are used to return a single value based on the input provided.- STRING FUNCTIONS
[CONCAT, SUBSTRING, CHARINDEX, PATINDEX, CHAR LENGTH, LETTER CASE, TRIM, REPLACE, LEFT/RIGHT, REVERSE, REPLICATE, FORMAT]
- MATHEMATICAL FUNCTIONS
[ABS, ROUND, SQRT, CEILING, FLOOR, POWER, EXP, LOG]
- DATE FUNCTIONS
[GETDATE, YEAR, MONTH, DAY, DATEADD, DATEDIFF]
- CONVERSION FUNCTIONS
[CAST, CONVERT, TRY_CAST, TRY_CONVERT]
- LOGICAL FUNCTIONS
[COALESCE, ISNULL]
- STRING FUNCTIONS
-
${\color{red}WFL}$ (Windows Functions Library)
: WFL commands are used to return a value based on a set of rows related to the current row.- AGGREGATE FUNCTIONS
[COUNT, AVG, SUM, MIN, MAX]
- RANKING FUNCTIONS
[ROW_NUMBER, DENSE_RANK, RANK, NTILE]
- ANALYTIC FUNCTIONS
[CUME_DIST, PERCENT_RANK, FIRST_VALUE, LAST_VALUE, LAG, LEAD]
- AGGREGATE FUNCTIONS
Table: STUDENT
+-------------+-----------+-----------------+--------+-----------------+---------+----------------+-------+-----+------------+
| Adm_No | DOJ | Stud_Name | Gender | Guardian_Name | Address | Contact_Number | Class | Fee | Monitor_ID |
+-------------+-----------+-----------------+--------+-----------------+---------+----------------+-------+-----+------------+
| ROSE00023 | 10/1/2021 | Abu Talha | M | Md Fareed | Delhi | 7903077297 | 10 | 400 | NULL |
| ROSE00024 | 10/1/2021 | Abu Salesh | M | Md Fareed | Delhi | 7903077297 | 8 | 450 | ROSE00023 |
| ROSE00040 | 10/1/2021 | Md Neyamul | M | Md Shamsuddin | Chennai | 9661194838 | 7 | 350 | ROSE00023 |
| ROSE00041 | 6/8/2021 | Ruba Parveen | F | Md Parwez | Delhi | 9693461570 | 5 | 275 | ROSE00023 |
| ROSE00058 | 10/2/2021 | Md Muntazeem | M | Md Naimuddin | Pune | 8292149189 | 10 | 325 | ROSE00023 |
| ROSE00102 | 10/29/2021| Mantasha Khatoon| F | Hasnain | Noida | 9709148101 | 6 | 250 | ROSE00144 |
| ROSE00144 | 12/1/2021 | Arju Kumar | M | Ranjit Kumar Sah| Mumbai | 6206863026 | 8 | 300 | ROSE00058 |
| ROSE00145 | 12/1/2021 | Roji Kumari | F | Ranjit Kumar Sah| Mumbai | 6206863026 | 7 | 300 | ROSE00144 |
| ROSE00172 | 12/4/2021 | Md Azfar | M | Md Mushtaque | Sikkim | 7631041561 | 10 | 300 | ROSE00058 |
| ROSE00331 | 2/3/2023 | Juveria Khatoon | F | Saud Alam | Chennai | 7330859950 | 8 | 300 | ROSE00058 |
| ROSE00335 | 9/4/2023 | Manish Kumar | M | Ranjan Kumar | Noida | 9060609777 | 9 | 350 | ROSE00058 |
| ROSE00041 | 6/8/2021 | Ruba Parveen | F | Md Parwez | Delhi | 9693461570 | 5 | 275 | ROSE00144 |
+-------------+-----------+-----------------+--------+-----------------+---------+----------------+-------+-----+------------+
Table: EXAMS
+------------+--------------+--------------+----------------+------------+
| Adm_No | Subject_Code | Subject_Name | Marks_Obtained | Exam_Date |
+------------+--------------+--------------+----------------+------------+
| ROSE00001 | SUB004 | S.St. | 73 | 12/11/2021 |
| ROSE00015 | SUB002 | Science | 66 | 12/13/2021 |
| ROSE00023 | SUB003 | English | 95 | 12/09/2021 |
| ROSE00024 | SUB001 | Mathematics | 86 | 12/10/2021 |
| ROSE00040 | SUB002 | Science | 80 | 12/08/2021 |
| ROSE00041 | SUB002 | Science | 78 | 12/02/2021 |
| ROSE00050 | SUB003 | English | 56 | 12/14/2021 |
| ROSE00051 | SUB001 | Mathematics | 67 | 12/15/2021 |
| ROSE00058 | SUB001 | Mathematics | 90 | 12/07/2021 |
| ROSE00065 | SUB002 | Science | 81 | 12/16/2021 |
| ROSE00102 | SUB001 | Mathematics | 85 | 12/01/2021 |
| ROSE00108 | SUB005 | Computer | NULL | NULL |
| ROSE00144 | SUB002 | Science | 74 | 12/05/2021 |
| ROSE00145 | SUB003 | English | 89 | 12/06/2021 |
| ROSE00172 | SUB003 | English | 92 | 12/03/2021 |
| ROSE00331 | SUB001 | Mathematics | 88 | 12/04/2021 |
+------------+--------------+--------------+----------------+------------+
π Home
+---------------------------------------------------------------------------------------------------------------------------------+
| Specifically it comes under SCL (Session Control Language). It is used to select a specific Database to work with in a session. |
+---------------------------------------------------------------------------------------------------------------------------------+
USE FSA;
π Home
+----------------------------------------------------------------------------------------------------------------------------------+
| A schema is like a container for Database objects (tables) that can contain multiple relational tables for a project/department. |
| A database might have multiple schemas |
+----------------------------------------------------------------------------------------------------------------------------------+
CREATE SCHEMA INSTITUTE;
CREATE TABLE INSTITUTE.RESULT (
Adm_No VARCHAR(20) PRIMARY KEY,
Tot_Marks INT,
Grade VARCHAR(30)
);
ALTER SCHEMA INSTITUTE TRANSFER dbo.Student; -- dbo.student means student table in current database (dbo) transferring to schema 'Institute'
ALTER SCHEMA INSTITUTE TRANSFER HR.Student; -- HR.student means student table in Old schema (HR) transferring to New schema 'Institute' in current database
π Home
+--------------------------------------------------------------------------+
| It is used to Create new Databases, Tables, Constraints, Views, Indexes. |
+--------------------------------------------------------------------------+
CREATE DATABASE FSA;
CREATE TABLE STUDENT (
Adm_No VARCHAR(20) PRIMARY KEY,
DOJ DATE,
Stud_Name VARCHAR(50),
Gender CHAR(10),
Guardian_Name VARCHAR(50),
Address VARCHAR(150),
Contact_Number BIGINT,
Class INT,
Fee DECIMAL(10, 2)
);
- SQL
CONSTRAINTS
are used to specifyrules
for the data in a table. Constraints are used tolimit
the type of data that can go into a table.
CREATE TABLE STUDENT (
Adm_No VARCHAR(10) PRIMARY KEY, -- PRIMARY KEY constraint (takes by default NOT NULL) constraint on Admission number
DOJ DATE NOT NULL, -- Date of Joining, NOT NULL constraint
Stud_Name VARCHAR(50) NOT NULL, -- Student Name, NOT NULL constraint
Gender CHAR(1) CHECK (Gender IN ('M', 'F')), -- CHECK constraint ensuring Gender is either 'M' or 'F'
Guardian_Name VARCHAR(50) NOT NULL, -- Guardian Name, NOT NULL constraint
Address VARCHAR(100), -- Address
Contact_Number VARCHAR(15), -- Contact Number
Class INT CHECK (Class BETWEEN 1 AND 12), -- CHECK constraint ensuring Class is between 1 and 12
Fee DECIMAL(10, 2) CHECK (Fee > 0) -- CHECK constraint ensuring Fee is positive
Class_Time time(10) DEFAULT '07:05:00' NOT NULL -- DEFAULT with NOT NULL, 2 constraint, IF USER DOESN'T INSERT ANY VALUE IN Class_Time, WILL AUTOMATICALLY TAKE Default Time '07:05:00'
);
- SQL
VIEWS
are simplified data access, minimize the Query. It is also known asVirtual Table
orQuery Table
because it does not store the rows and columns on the disk. It can lead to performance issues because it is not actual table
CREATE VIEW Class10_Students AS
SELECT Adm_No, Stud_Name, Gender, Guardian_Name, Contact_Number, Fee
FROM STUDENT
WHERE Class = 10;
- Query to check the
VIEWS
in a Table
SELECT * FROM Class10_Students;
- An Index in SQL is like a table of contents in a book. It helps SQL Server quickly locate and retrieve the data from a table without having to scan the entire table.
CREATE INDEX idx_StudName
ON STUDENT (Stud_Name);
- Query to check the
INDEXES
in a Table
EXEC sp_helpindex 'STUDENT';
- Without an Index (Left side): SQL Server
searches the whole table
(slow). - With an Index (Right side): SQL Server
jumps directly to the rows
you're looking for (fast).
π Home
+---------------------------------------------------------------------------------------+
| It is used to Alter (change) the structure of the Table and the name of the Database. |
+---------------------------------------------------------------------------------------+
ALTER DATABASE FSA
Modify Name = FSA_new;
EXEC sp_rename 'Students', 'Student';
EXEC sp_rename 'student.Contact_No', 'Contact_Number';
ALTER TABLE STUDENT
ADD Email VARCHAR(100);
ALTER TABLE STUDENT
ALTER COLUMN Contact_Number VARCHAR(20);
πΉ Modify a column (change length of data type)
VARCHAR(50) to 'VARCHAR(100)' for Stud_Name
column
ALTER TABLE STUDENT
ALTER COLUMN Stud_Name VARCHAR(100);
ALTER TABLE STUDENT
DROP COLUMN Email;
ALTER TABLE STUDENT
ADD CONSTRAINT DF_Fee DEFAULT 300 FOR Fee;
π Home
+-----------------------------------------------------------------------+
| It is used to Delete/Remove the objects from the Database completely. |
+-----------------------------------------------------------------------+
DROP DATABASE FSA;
DROP SCHEMA HR;
DROP TABLE STUDENT;
ALTER TABLE STUDENT
DROP COLUMN Email;
DROP VIEW Class10_Students;
DROP INDEX idx_StudName ON STUDENT; -- Syntax: Index_Name ON Table_Name
Drop Index Student.idx_StudName; -- Syntax: Table_Name.Index_Name
π Home
+-----------------------------------------------------------------------------------------------------------------------+
| It is used to Remove/Delete all records (rows) from a table, but the table structure (Column names/headings) remains. |
+-----------------------------------------------------------------------------------------------------------------------+
TRUNCATE TABLE STUDENT;
π Home
+-------------------------------------------------+
| It is used to Add new data/values into a table. |
+-------------------------------------------------+
- 'Column names'
must match the order
of the values. - 'Dates' should be provided in
YYYY-MM-DD
format. - The 'Adm_No' is the
primary key
and must beunique
for each row.
INSERT INTO STUDENT (Adm_No, DOJ, Stud_Name, Gender, Guardian_Name, Address, Contact_Number, Class, Fee)
VALUES ('ROSE00023', '2021-10-01', 'Abu Talha', 'M', 'Md Fareed', 'Khiripaghar', '7903077297', 10, 400);
INSERT INTO STUDENT (Adm_No, DOJ, Stud_Name, Gender, Guardian_Name, Address, Contact_Number, Class, Fee)
VALUES
('ROSE00023', '2021-10-01', 'Abu Talha', 'M', 'Md Fareed', 'Khiripaghar', '7903077297', 10, 400),
('ROSE00024', '2021-10-01', 'Abu Salesh', 'M', 'Md Fareed', 'Khiripaghar', '7903077297', 8, 450),
('ROSE00040', '2021-10-01', 'Md Neyamul', 'M', 'Md Shamsuddin', 'Gauripur', '9661194838', 7, 350),
('ROSE00041', '2021-06-08', 'Ruba Parveen', 'F', 'Md Parwez', 'Khiripaghar', '9693461570', 5, 275),
('ROSE00058', '2021-10-02', 'Md Muntazeem', 'M', 'Md Naimuddin', 'Rajapur', '8292149189', 10, 325),
('ROSE00102', '2021-10-29', 'Mantasha Khatoon', 'F', 'Hasnain', 'Nayadih', '9709148101', 6, 250),
('ROSE00144', '2021-12-01', 'Arju Kumar', 'M', 'Ranjit Kumar Sah', 'Chilmil', '6206863026', 8, 300),
('ROSE00145', '2021-12-01', 'Roji Kumari', 'F', 'Ranjit Kumar Sah', 'Chilmil', '6206863026', 7, 300),
('ROSE00172', '2021-12-04', 'Md Azfar', 'M', 'Md Mushtaque', 'Maghota', '7631041561', 10, 300),
('ROSE00331', '2023-02-03', 'Juveria Khatoon', 'F', 'Saud Alam', 'Chihar', '7330859950', 8, 300);
π Home
+-----------------------------------------------------------+
| It is used to Modify existing data/values within a table. |
+-----------------------------------------------------------+
- The
WHERE
clause ensures that only the specified row (e.g., Adm_No = 'ROSE00023') is updated. - Without
WHERE
, all rows in the table would be updated!
UPDATE STUDENT
SET Class = 9
WHERE Adm_No = 'ROSE00040';
πΈ Update (SET) Multiple (same) values/same Column
(Gender) in a Table 'Student' if Column has NULL values
UPDATE STUDENT
SET Gender = 'M'
Where Gender IS NULL;
πΈ Update (SET) Multiple (different) values/same row
(Stud_Name, Fee and DOJ) in a Table 'Student'
UPDATE STUDENT
SET Stud_Name = 'Abu Talha Khan', Fee = 450, DOJ = '2021-10-04'
WHERE Adm_No = 'ROSE00023';
UPDATE STUDENT
SET Gender = 'Fem'
WHERE Adm_No IN ('ROSE00145', 'ROSE00331', 'ROSE00041');
πΈ Update (SET with CASE, ELSE, END) Multiple (different) values/different Column
(FEE) in a Table 'Student'
- for
ELSE
statement when we keep the same column name (i.e. "Fee") asSET
statement, then Rest columnsvalue remain same
UPDATE STUDENT
SET Fee = CASE
WHEN Adm_No='ROSE00024' THEN 450
WHEN Adm_No='ROSE00041' THEN 275
WHEN Adm_No='ROSE00058' THEN 325
WHEN Adm_No='ROSE00102' THEN 250
WHEN Adm_No='ROSE00023' THEN 400
WHEN Adm_No='ROSE00040' THEN 350
ELSE Fee -- for ELSE statement when we keep the same column name (i.e. "Fee") as SET statement, then Rest columns value remain same
END;
πΈ Update (SET with CASE, ELSE, END) Multiple (different) values/different Column
(FEE) in a Table 'Student'
- for
ELSE
statement when we keep any value (i.e. "199") different fromSET
statement, then Rest columns take thedefault value "199"
UPDATE STUDENT
SET Fee = CASE
WHEN Adm_No='ROSE00024' THEN 450
WHEN Adm_No='ROSE00041' THEN 275
WHEN Adm_No='ROSE00058' THEN 325
WHEN Adm_No='ROSE00102' THEN 250
WHEN Adm_No='ROSE00023' THEN 400
WHEN Adm_No='ROSE00040' THEN 350
ELSE 199 -- for ELSE statement when we keep any value (i.e. "199") different from SET statement, then Rest columns take the default value "199"
END;
π Home
+-----------------------------------------+
| It is used to Remove data from a table. |
+-----------------------------------------+
- WHERE clause specifies which rows to delete (e.g., rows with Adm_No = 'ROSE00023').
- If you omit the WHERE clause, all rows in the table will be deleted!
DELETE FROM STUDENT
WHERE Adm_No = 'ROSE00023'; -- One Primary-Key Value
- The
IN
operator allows you to match multiple values in a column. - This query will delete
Both rows
where Adm_No is either 'ROSE00023' or 'ROSE00024'.
DELETE FROM STUDENT
WHERE Adm_No IN ('ROSE00023', 'ROSE00024'); -- Multiple Primary-Key Values by using "IN" operator
DELETE FROM STUDENT
WHERE Class = 10; -- One Non-Key Value
π Home
+---------------------------------------------------------------------------------------------+
| It is a precompiled SQL code stored in the database, that can be executed as a single unit. |
| If any SQL query need to write again and again then same can be saved as Stored Procedure. |
+---------------------------------------------------------------------------------------------+
CREATE PROCEDURE StudentInfo
AS -- BEGIN and END are used to define the start and end of the executable block within a stored procedure,
BEGIN -- allowing multiple SQL statements to be grouped together.
SELECT * FROM Student;
END;
GO -- 'GO' is not an actual SQL command, It is a part of SSMS which indicates end of Batch (group of commands) in SSMS
π Home
+------------------------------------------------------------+
| It is used to Retrieve/Fetch data from one or more tables. |
+------------------------------------------------------------+
SELECT Getdate() AS [Current Date and Time]; -- To check Current DATE and TIME
SELECT Sysdatetime() AS [Current Date and Time]; -- To check Current DATE and TIME
SELECT Cast(Getdate() AS Date) AS [Current Date]; -- To check Current DATE only
SELECT Cast(Sysdatetime() AS Date) AS [Current Date]; -- To check Current DATE only
SELECT * FROM sys.databases;
SELECT * FROM sys.tables;
SELECT * FROM STUDENT;
SELECT * FROM EXAMS;
SELECT * FROM INSTITUTE.EXAMS; -- Select Records from Schema (Institute), Table (Exams) = Schema.Table
SELECT * FROM FSA.INSTITUTE.EXAMS; -- Select Records from Database (FSA), Schema (Institute), Table (Exams) = Database.Schema.Table
SELECT Adm_No, Stud_Name, Class, Fee
FROM EXAMS;
SELECT Stud_Name, Fee, Fee + 50 AS Increased_Fee
FROM STUDENT; -- Addition (+): Increase the FEE by 50 for each student
SELECT Stud_Name, Fee, Fee - 100 AS Reduced_Fee
FROM STUDENT; -- Subtraction (-): Decrease 100 from the Fee for each student
SELECT Stud_Name, Fee, Fee * 2 AS Doubled_Fee
FROM STUDENT; -- Multiplication (*): Multiply the Fee by 2 for each student
SELECT Stud_Name, Fee, Fee / 2 AS Halved_Fee
FROM STUDENT; -- Division (/): Divide the Fee by 2 for each student
SELECT Stud_Name, Fee, Fee % 100 AS Remainder_Fee
FROM STUDENT; -- Modulus (%): Find the remainder when Fee is divided by 100
SELECT * FROM STUDENT
WHERE Class = 10; -- Return all records from STUDENT Table for 10th Class
SELECT * FROM STUDENT
WHERE Class <> 5; -- Return all records from STUDENT Table for all classes EXCEPT 5th Class [Class not equal to (<> or !=) 5]
SELECT * FROM STUDENT
WHERE Fee >= 350; -- Return all records from STUDENT Table for those whose Fee more than or equal to 350
SELECT * FROM STUDENT
WHERE Fee !> 350; -- Return all records from STUDENT Table for those whose Fee not more than 350
πΈ Select Records with Conditions by Logical Operators
: AND, OR, NOT, IN, BETWEEN, LIKE, ANY/SOME, ALL, IS NULL
SELECT * FROM STUDENT
WHERE Fee > 300 AND Class = 8; -- Return all records from STUDENT Table for 8th Class whose Fee more than 300
SELECT * FROM STUDENT
WHERE Class = 10 OR Class = 9; -- Return all records from STUDENT Table for 8th Class whose Fee more than 300
SELECT * FROM STUDENT
WHERE NOT Fee > 350 AND Gender = 'F'; -- Return all records from STUDENT Table whose fee not more than 350 for Females
SELECT * FROM STUDENT
WHERE DOJ BETWEEN '2021-10-01' AND '2021-12-04'; -- Return all records from STUDENT Table who joined between date range
SELECT * FROM STUDENT
WHERE Stud_Name LIKE 'Ru%' OR Stud_Name LIKE '%oon'; -- Used 'WILDCARD %' here
SELECT * FROM EXAMS
WHERE Subject_Name IN('Science', 'English', 'Computer') AND Marks_Obtained > 90; -- Return all records from EXAMS Table who get marks above 90 IN Science, English and Computer
SELECT * FROM STUDENT
WHERE Fee > ANY (SELECT Fee FROM STUDENT WHERE Class = 8); -- Find students whose Fee is greater than ANY student in Class 8
SELECT * FROM STUDENT -- ANY=SOME: SOME is functionally equivalent to ANY in SQL
WHERE Fee = SOME (SELECT Fee FROM STUDENT WHERE Class = 8); -- Find students whose Fee is equal to SOME student in Class 8
SELECT * FROM STUDENT
WHERE Fee > ALL (SELECT Fee FROM STUDENT WHERE Class = 8); -- Find students whose Fee is greater than ALL students in Class 8
SELECT Stud_Name FROM STUDENT -- Find students whose Fee is greater than ALL students in Class 8
WHERE EXISTS (SELECT * FROM STUDENT WHERE Class = 10); -- If an entry EXISTS, it returns the student's name
SELECT * FROM EXAMS
WHERE Marks_Obtained IS NULL; -- Find students whose Marks_Obtained IS NULL (if any such values exist)
SELECT * FROM EXAMS
WHERE Marks_Obtained > (SELECT AVG(Marks_Obtained) FROM EXAMS); -- Return all records greater than average marks
SELECT * FROM STUDENT
ORDER BY Stud_Name ASC;
SELECT * FROM STUDENT
ORDER BY Class DESC;
π Home
+------------------------------------------------------------------------+
| It is used to search for patterns with LIKE clause within string data. |
+------------------------------------------------------------------------+
SELECT * FROM STUDENT
WHERE Guardian_Name LIKE 'M%'; -- Return all records from STUDENT Table where Guardian Name STARTS with letter 'M'
SELECT * FROM EXAMS
WHERE Subject_Name LIKE '%e'; -- Return all records from EXAMS Table where Subject Name ENDS with letter 'e'
SELECT * FROM EXAMS
WHERE Subject_Name LIKE 'M%s'; -- Return all records from EXAMS Table where Subject name STARTS with letter 'M' and ENDS with letter 's'
SELECT * FROM EXAMS
WHERE Addres LIKE '%ur%'; -- Return all records from EXAMS Table where Addres CONTAINS phrase 'ur'
SELECT * FROM STUDENT
WHERE Addres LIKE '_hilmil'; -- Return all records from STUDENT Table where Addres STARTS with ANY ONE character, FOLLOWED "hilmil"
SELECT * FROM EXAMS
WHERE Subject_Name LIKE 'Englis_'; -- Return all records from EXAMS Table where subject name STARTS with "Englis", ENDS with ANY ONE character
SELECT * FROM EXAMS -- Return all records from EXAMS Table where subject name STARTS with ANY 2 characters....
WHERE Subject_Name LIKE '__gl___'; -- FOLLOWED by "gl" and ENDS with ANY 3 characters
SELECT * FROM EXAMS -- Return all records from EXAMS Table where subject code starts with "S"....
WHERE Subject_Code LIKE 'S__002'; -- followed by any 2 characters and ends with '002'
SELECT * FROM STUDENT
WHERE Addres LIKE '_a%'; -- Return all records from STUDENT Table where addres starts with any one character, 'a' at 2nd position
SELECT * FROM STUDENT
WHERE Addres LIKE '[a-g]%'; -- Return all records from STUDENT Table where Addres starts with any one letter "from 'a' to 'g'" (a,b,c,d,e,f OR g)
SELECT * FROM STUDENT
WHERE Stud_Name LIKE 'A[nr]%' -- Matches names starting with "An" or "Ar"
SELECT * FROM STUDENT
WHERE Guardian_Name LIKE '[rhs]%'; -- Return all records from STUDENT Table where Guardian Name STARTS with letter 'r' or 'h' or 's'
SELECT * FROM STUDENT
WHERE Guardian_Name LIKE '[^rhs]%'; -- Return all records from STUDENT Table where Guardian Name NOT STARTS with letter 'r' or 'h' or 's'
π Home
+----------------------------------------------------------------------------------+
| It is used to perform a calculation on multiple rows and returns a single value. |
| It is commonly used to summarize or analyze data. |
+----------------------------------------------------------------------------------+
SELECT COUNT(*) AS TotalStudents
FROM STUDENT; -- Count the total number of records/rows from student table
SELECT SUM(Fee) AS TotalFees
FROM STUDENT; -- Calculate the total fees of all students from student table
SELECT AVG(Fee) AS AverageFee
FROM STUDENT; -- Calculate the average fee of students from student table
SELECT MIN(Fee) AS MinimumFee
FROM STUDENT; -- Find the minimum fee paid by a student from student table
SELECT MAX(Fee) AS MinimumFee
FROM STUDENT; -- Find the maximum fee paid by a student from student table
SELECT Class, COUNT(*) AS NumberOfStudents
FROM STUDENT
GROUP BY Class
HAVING COUNT(*) > 2; -- Find classes with more than 2 students
π Home
+------------------------------------------------------------------------+
| It is used to specify conditions or actions to be applied to the data. |
| Clauses help to filter, group, sort, or limit the results of a query. |
+------------------------------------------------------------------------+
WHERE
clause:Filter rows
based on a condition before grouping.
SELECT * FROM STUDENT
WHERE Class = 8; -- Retrieve all students in Class 8
ORDER BY
clause:Sort
the result set.
SELECT * FROM STUDENT
ORDER BY Stud_Name ASC; -- Retrieve all students sorted by Stud_Name in ascending order
SELECT * FROM STUDENT
WHERE Gender = 'M'
ORDER BY Stud_Name ASC; -- Retrieve all male students sorted by Stud_Name in ascending order
GROUP BY
clause:Group rows
based on one or more columns.
SELECT Class, SUM(Fee) AS [Total Fee by Class]
FROM STUDENT
GROUP BY Class; -- Sum the fee of students in each class
SELECT Class, SUM(Fee) AS [Total Fee by Class]
FROM STUDENT
WHERE Fee > 300 -- Filters rows where Fee is greater than 300
GROUP BY Class
ORDER BY Class DESC; -- Sum the fee of students in each class whose fee more than 300 sorted by Class in Descending order
HAVING
clause:Filter groups
after Grouping to filter results on Aggregation.
SELECT Class, COUNT(*) AS NumberOfStudents
FROM STUDENT
GROUP BY Class
HAVING COUNT(*) > 2; -- Find classes with more than 2 students
SELECT Class, SUM(Fee) AS [Total Fee by Class]
FROM STUDENT
GROUP BY Class
HAVING SUM(Fee) > 500 -- Filters groups where the total Fee is greater than 500
ORDER BY Class DESC;
TOP
clause:Limit
the number of rows returned.
SELECT TOP 5 * FROM STUDENT
ORDER BY Fee DESC; -- Retrieve the top 5 students by Fee in descending order
SELECT TOP 5 Adm_No, Stud_Name FROM STUDENT
ORDER BY Fee DESC; -- Retrieve the top 5 students table Adm_No and Stud_Name columns by Fee in descending order
SELECT Adm_No, Marks_Obtained FROM EXAMS
ORDER BY Marks_Obtained DESC
OFFSET 3 ROWS -- Skip (Offset) 1st 3 rows and then return next 5 rows
FETCH NEXT 5 ROWS ONLY; -- Retrieve the top 5 EXAMS table Adm_No and Marks_Obtained columns by Marks_Obtained in descending order
DISTINCT
clause: Selectunique
values only.
SELECT DISTINCT Class FROM STUDENT; -- Retrieve the distinct/unique classes of students
SELECT DISTINCT Class FROM STUDENT
WHERE Fee > 300; -- Retrieve the distinct classes/unique of students where student fee more than 300
JOIN
clause: Combines rows from two or more tables.
SELECT S.*, E.Subject_Name, E.Marks_Obtained -- Fetch all columns (*) from Student Table and Subject & Marks obtained from Exams Table
FROM STUDENT S
INNER JOIN EXAMS E
ON S.Adm_No = E.Adm_No;
π Home
+---------------------------------------------------------------------------------------------+
| It is used to combine rows from two or more tables, based on a related column between them. |
+---------------------------------------------------------------------------------------------+
(INNER) JOIN
: Returns records that have only MATCHING (Common) VALUES IN BOTH TABLES.
SELECT S.Adm_No, S.Stud_Name, E.Subject_Name, E.Marks_Obtained
FROM STUDENT S
INNER JOIN EXAMS E
ON S.Adm_No = E.Adm_No; -- Returns the Admission No., student names along with the subjects and marks they obtained in the exams
SELECT S.Adm_No, S.Stud_Name, E.Subject_Name, E.Marks_Obtained
FROM STUDENT S
JOIN EXAMS E -- JOIN or Inner JOIN works similarly
ON S.Adm_No = E.Adm_No
WHERE S.Class = 10; -- Returns the students of class 10 and their respective exam marks
SELECT S.Adm_No, S.Stud_Name, E.Subject_Name, E.Marks_Obtained
FROM STUDENT S
INNER JOIN EXAMS E
ON S.Adm_No = E.Adm_No
WHERE E.Marks_Obtained > 85; -- Fetches students who scored more than 85 marks in any exam
LEFT (OUTER) JOIN
: Returns all records from the LEFT TABLE, and the matched records from the RIGHT TABLE.
SELECT S.Adm_No, S.Stud_Name, E.Subject_Name, E.Marks_Obtained
FROM STUDENT S
LEFT JOIN EXAMS E
ON S.Adm_No = E.Adm_No; -- Fetches all students, including those who may not have appeared in any exams
SELECT S.Adm_No, S.Stud_Name, E.Subject_Name, E.Marks_Obtained
FROM STUDENT S
LEFT OUTER JOIN EXAMS E -- LEFT OUTER JOIN acts as similar to LEFT JOIN
ON S.Adm_No = E.Adm_No;
RIGHT (OUTER) JOIN
: Returns all records from the RIGHT TABLE, and the matched records from the LEFT TABLE.
SELECT S.Adm_No, S.Stud_Name, E.Subject_Name, E.Marks_Obtained
FROM STUDENT S
RIGHT JOIN EXAMS E
ON S.Adm_No = E.Adm_No; -- Fetches all exam records, even if some students may not exist in the STUDENT table (Null Values for Marks_Obtained)
SELECT S.Adm_No, S.Stud_Name, E.Subject_Name, E.Marks_Obtained
FROM STUDENT S
RIGHT OUTER JOIN EXAMS E
ON S.Adm_No = E.Adm_No; -- RIGHT OUTER JOIN acts as similar to RIGHT JOIN
FULL (OUTER) JOIN
: Returns all records when there is a match in either LEFT or RIGHT TABLE.
SELECT S.Adm_No, S.Stud_Name, E.Subject_Name, E.Marks_Obtained
FROM STUDENT S
FULL OUTER JOIN EXAMS E
ON S.Adm_No = E.Adm_No; -- Fetches all exam records, even if some students may not exist in the STUDENT table (Null Values)
SELECT S.Adm_No, S.Stud_Name, E.Subject_Name, E.Marks_Obtained
FROM STUDENT S
FULL JOIN EXAMS E
ON S.Adm_No = E.Adm_No; -- FULL JOIN acts as similar to FULL OUTER JOIN
SELF JOIN
: A self join is when a table is joined with itself. It is useful for hierarchical or recursive data structures. Let's say we want to find students from the same address (students who live in the same location).
SELECT S1.Stud_Name AS Student1, S2.Stud_Name AS Student2, S1.Addres
FROM STUDENT S1
INNER JOIN STUDENT S2
ON S1.Addres = S2.Addres
WHERE S1.Adm_No <> S2.Adm_No; -- This query matches students who live at the same address but ensures they are not the same student by using S1.Adm_No <> S2.Adm_No
CROSS JOIN
: It combines every row of the first table with every row of the second table.Example
: Cross join students with their subjects.
SELECT S.Stud_Name, E.Subject_Name
FROM STUDENT S
CROSS JOIN EXAMS E; -- Pairs every student with every subject, producing a large set of combinations
UNION
: It Combines the results of two or more SELECT statements. The UNION operator only returns distinct records from one or more tables.
SELECT Adm_No FROM STUDENT
UNION
SELECT Guardian_Name FROM STUDENT;
π Home
+----------------------------------------------------------+
| It is used to give a user access rights to the database. |
+----------------------------------------------------------+
GRANT SELECT ON STUDENT TO UserA; -- Gives the user 'UserA' the ability to perform SELECT queries on the STUDENT table
GRANT INSERT, UPDATE ON STUDENT TO UserA; -- Allows UserA to insert new records and update existing ones in the STUDENT table
π Home
+----------------------------------------------------------------------------------+
| It is used to remove access rights from the database which is granted to a user. |
+----------------------------------------------------------------------------------+
REVOKE SELECT ON STUDENT TO UserA; -- Removes the SELECT permission, so UserA can no longer query data from the STUDENT table
REVOKE INSERT, UPDATE ON STUDENT TO UserA; -- Removes the ability for UserA to insert new records or update existing ones in the STUDENT table
π Home
+--------------------------------------------------------------------------------------+
| It is used to save the current transaction permanently in the database. |
| Once a COMMIT is executed, the changes are made permanent and cannot be rolled back. |
+--------------------------------------------------------------------------------------+
BEGIN TRANSACTION;
INSERT INTO STUDENT (Adm_No, DOJ, Stud_Name, Gender, Guardian_Name, Address, Contact_Number, Class, Fee)
VALUES ('ROSE00332', '2023-09-15', 'John Doe', 'M', 'Richard Doe', 'Greenfield', '1234567890', 8, 350);
COMMIT;
π Home
+-------------------------------------------------------------+
| It is used to Undo changes made in the current transaction. |
+-------------------------------------------------------------+
BEGIN TRANSACTION;
INSERT INTO STUDENT (Adm_No, DOJ, Stud_Name, Gender, Guardian_Name, Address, Contact_Number, Class, Fee)
VALUES ('ROSE00333', '2023-09-15', 'Jane Smith', 'F', 'John Smith', 'Blueville', '9876543210', 7, 300);
ROLLBACK; -- If something goes wrong, rollback the transaction
π Home
+----------------------------------------------------------------------------------+
| It is used to set a point within a transaction to which you can roll back later. |
+----------------------------------------------------------------------------------+
BEGIN TRANSACTION;
INSERT INTO STUDENT (Adm_No, DOJ, Stud_Name, Gender, Guardian_Name, Address, Contact_Number, Class, Fee)
VALUES ('ROSE00334', '2023-09-15', 'Alice Brown', 'F', 'Sam Brown', 'Redtown', '1122334455', 6, 250);
SAVEPOINT Save1;
INSERT INTO STUDENT (Adm_No, DOJ, Stud_Name, Gender, Guardian_Name, Address, Contact_Number, Class, Fee)
VALUES ('ROSE00335', '2023-09-15', 'Bob White', 'M', 'Jim White', 'Greenville', '5566778899', 5, 275);
ROLLBACK TRANSACTION Save1; -- Something goes wrong, rollback to the savepoint
COMMIT; -- Now commit the first insert, but not the second
π Home
+------------------------------------------------------------------------------------+
| It is used to specify characteristics for the transaction (e.g., isolation level). |
+------------------------------------------------------------------------------------+
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
BEGIN TRANSACTION;
-- Query or Insert/Update/Delete operations
INSERT INTO STUDENT (Adm_No, DOJ, Stud_Name, Gender, Guardian_Name, Address, Contact_Number, Class, Fee)
VALUES ('ROSE00336', '2023-09-15', 'Charlie Green', 'M', 'Paul Green', 'Bluefield', '9988776655', 9, 400);
COMMIT;
π Home
+------------------------------------------------------------------------------------------------+
| It is used to manipulate string data for tasks like concatenation, extraction, and formatting. |
+------------------------------------------------------------------------------------------------+
SELECT CONCAT(Adm_No, ' - ', Stud_Name) AS StudentDetails
FROM STUDENT;
SELECT CONCAT('Name: ', Stud_Name, ', Guardian: ', Guardian_Name) AS [Full Details]
FROM STUDENT;
SELECT SUBSTRING(Stud_Name, 1, 3) AS ShortName
FROM STUDENT;
SELECT SUBSTRING(Adm_No, 5, 4) AS PartAdmNo
FROM STUDENT;
SELECT Stud_Name, LEN(Stud_Name) AS NameLength
FROM STUDENT;
SELECT Address, LEN(Address) AS AddressLength
FROM STUDENT;
SELECT CHARINDEX('Md', Stud_Name) AS Md_Position
FROM STUDENT;
SELECT PATINDEX('%R%', Stud_Name) AS R_Position
FROM STUDENT;
SELECT UPPER(Stud_Name) AS UpperCaseName
FROM STUDENT;
SELECT LOWER(Address) AS LowerCaseAddress
FROM STUDENT;
SELECT TRIM(Contact_Number) AS TrimmedContact
FROM STUDENT;
SELECT LTRIM(Stud_Name) AS Trimmed_Left_Name
FROM STUDENT;
SELECT RTRIM(Stud_Name) AS Trimmed_Right_Name
FROM STUDENT;
SELECT REPLACE(Stud_Name, 'Md', 'Mr.') AS Updated_Name
FROM STUDENT;
SELECT REPLACE(Adm_No, '-', ' ') AS ModifiedAdmNo
FROM STUDENT;
SELECT STUFF(Stud_Name, 1, 0, 'Dr. ') AS Stuffed_Name
FROM STUDENT;
SELECT LEFT(Adm_No, 5) AS FirstFive
FROM STUDENT;
SELECT RIGHT(Contact_Number, 4) AS LastFourDigits
FROM STUDENT;
SELECT REVERSE(Adm_No) AS ReversedAdmNo -- reverse the order of characters in a string
FROM STUDENT;
SELECT REVERSE(Stud_Name) AS ReversedName -- reverse the order of characters in a string
FROM STUDENT;
SELECT REPLICATE('*', 5) AS Stars -- Return star (*) 5 times
FROM STUDENT;
SELECT REPLICATE(Stud_Name, 2) AS DoubledName -- Return the same Student Name 2 times
FROM STUDENT;
SELECT FORMAT(Contact_Number, '###-###-####') AS FormattedContact -- format a value according to a format
FROM STUDENT;
SELECT FORMAT(DOJ, 'MM/dd/yyyy') AS FormattedDOJ
FROM STUDENT;