DB Commands
DB Commands
1- RELATIONAL DATABASE
Relational database stores the structured data in tables with the help of rows and columns.
They use SQL for structured querying and are good for complex query and structured data
integrity.
Also known as NoSql database. They store data in a variety of formats such as documents,
key-value pairs, graphs and columns. They are good for unstructured and semi structured
data. Such as images, videos, and business documents.
Example - MongoDB
WHAT IS SQL
Sql is a structured query language, which is used for accessing and manipulating
databases. It also helps us in data retrieval,access control as well as transaction
management. It helps us to perform CRUD operations that is create, read,update and
delete in our database
WHAT IS MYSQL
MySQL is a specific relational database management system or software that uses sql as a
querying language.
HISTORY OF SQL
1. Retrieving Data- Extracting precious information from the database through queries .
2. Manipulating Data - Adding, Modifying, or Removing records within a database.
3. Defining Data - Create and adjust the structure of the database including
tables,views and index.
4. Controlling Data - Managing database by gathering or revoking permission.
DOES SQL SUPPORTS PROGRAMMING LANGUAGE FEATURE
It is true that SQL is a language, but it does not support programming as it is not a
programming language, it is a command language. We do not have conditional statements
in SQL like for loops or if..else, we only have commands which we can use to query,
update, delete, etc. data in the database
TYPES OF COMMANDS
DLC deals with the control and security of data within database
Commands - GRANT, REVERT
WHAT IS SCHEMA
06 To Insert values into table COMMAND-INSERT INTO tableName (Column1, Column2... ColumnN)
VALUES (value1,value2.......value n)
INSERT- DML Command
EXAMPLE- INSERT INTO employee (empId,name,salary)
VALUES
(1, ”Raj” ,1200),
(2, ”Rahul” ,1100),
(3, ”Riti” ,1100)
NOTE- We can directly insert the values in the table without specifying
the attributes, but in this way data is stored in a sequential manner.
Numeric
INT Used for storing whole numbers without decimal points. (-2,147,483,648 to 2,147,483,647 (signed
integer)
DOUBLE Used for storing decimal numbers. (8-byte) more precised than float
DECIMAL(p, s) Used for exact numeric representation. p is the precision and s is the scale
IMPORTANT By default all the numeric datatypes can have negative as well as positive values. Thisrestrict the range
so if we know there is only +ve values which are stored we use UNSIGNED attribute (0-255). for eg-
salary can never be in negative or age
Character Data
Types
DATETIME/TIMES Used for storing date and time values. (yyyy-mm-dd hh:mm:ss)
TAMP
Command :
CREATE TABLE example1
( createdTs TIMESTAMP
);
BLOB (Binary Used for storing large amounts of binary data.(var len)
Large Object)
Command :
Primary Key :
A primary key is a key which uniquely identifies each record in a table. It ensures that each
tuple or record can be uniquely identified within the table. It is always Unique + Not null
Foreign Key :
A foreign key is a field in a table that refers to the primary key in another table. It
establishes a relationship between two tables.
NOTE- Foreign key helps to perform operations related to the parent table, such as joining
tables or ensuring referential integrity
REFERENTIAL INTEGRITY- Any of the updates that happen in the base table that need to
be done in the child table is called referential integrity. It helps us to maintain data integrity.
Cascading is a set of rules which dictate what actions should be taken automatically when
a referenced row in the parent table is modified or deleted.
COMMAND USE EXAMPLE
CASCADE If a row in the parent table is updated or
deleted, all related rows in the child table will
be automatically updated or deleted.
ON DELETE The ON DELETE CASCADE clause indicates CREATE TABLE childtableName ( childId INT
CASCADE that if a row in the parent table (parent_table) PRIMARY KEY, baseId INT, FOREIGN KEY
is deleted, all corresponding rows in the child (baseId) REFERENCES baseTableName(baseId)
table (child_table) will be automatically ON DELETE CASCADE );
deleted as well
ON UPDATE The ON UPDATE CASCADE clause CREATE TABLE childtableName ( childId INT
CASCADE indicates that if a row in the parent table PRIMARY KEY, baseId INT, FOREIGN KEY
(parent_table) is updated, all corresponding (baseId) REFERENCES parenttableName(childId)
rows in the child table (child_table) will be ON UPDATE CASCADE );
automatically updated as well.
UPDATE AND DELETE COMMANDS
UPDATE The UPDATE command in SQL is used to modify existing records UPDATE table_name SET columnName1=
in a table. value1(to be set) , columnName2 =value2(to
be set) WHERE condition;
If you get a safe mode error while executing queries run this query
SET SQL_SAFE_UPDATES=0;
DELETE The DELETE command in SQL is used to remove records from a DELETE FROM table_name
table (Basically it delete the entire raw) WHERE condition;
OPERATOR IN SQL
Arithmetic Operators ● addition (+) SELECT * FROM employee WHERE age+1
● subtraction (-) =60;
● multiplication (*)
● division (/)
● modulus (%) - Gives remender
Logical Operators AND It combines two conditions and returns SELECT * FROM employee WHERE city=
true if both are true 'Pune ' AND age > 18;
OR It combines two conditions and returns : SELECT * FROM employee WHERE city=
true if either is true 'Pune ' OR age > 18;
IN Operator IN(Checks if a value matches in a list of values) SELECT * FROM employee WHERE
department IN ('IT' , 'HR');
IS NULL / IS NOT IS NULL (checks for null values) , IS NOT SELECT * FROM employee WHERE
NULL Operators NULL(checks for not null values) department IS NOT NULL;
LIKE & Wildcard LIKE operator is used to search for a specified pattern 1.% (percent sign): It matches for any
Operators : in a column. It uses wildcard operators for matching sequence of zero or more characters.
patterns.
QUERY :
SELECT * FROM employee WHERE name
LIKE 'A%' ;
QUERY :
SELECT * FROM employee WHERE name
LIKE '_A%' ;
BETWEEN Operator Checks if a value is within a range of values. SELECT * FROM employee WHERE salary
: BETWEEN 1200 AND 1500;
AGGREGATE FUNCTIONS
Aggregate functions perform some operations on a set of rows and then returns a single
value summarising the data. These are used with SELECT statements to perform
calculations
It finds the average, or the " middle " number, of all the SELECT AVG(salary) FROM employee
numbers in a list.
this willl tell the avg amount company is
paying to its employees
WHERE It filters the rows based on specified SELECT col1 col2 FROM tableName WHERE
conditions. condition;
LIMIT The LIMIT clause in SQL is used to restrict ex : SELECT * FROM employee LIMIT 2;
the number of rows returned by a query.
This query retrieves the first 2 rows from the
table.
Joins are used to combine rows from two or more tables based on a related or shared or
common column between them.
Left Join/Left It is used to fetch all the records from the left Query:
Outer Join table along with matched records from the right
table. If there are no matching records in the SELECT columns FROM table1
right table, NULL values are returned for the LEFT JOIN table2 ON
columns of the right table. table1.colName = table2.colName;
Right Join/ Right It is used to fetch all the records from the right Query:
Outer Join table along with matched records from the left
table. If there are no matching records in the left SELECT columns FROM table1
table, NULL values are returned for the columns RIGHT JOIN table2 ON
of the left table table1.colName = table2.colName;
Full Join/Full ● It returns the matching rows of both left and Query:
Outer Join: right table and also includes all rows from
both tables even if they don’t have matching SELECT columns FROM table1
rows LEFT JOIN table2 ON
table1.colName = table2.colName;
● It is based on the principal of union ( left +
right +common) UNION
Cross Join: ● It combines each row of the first table with Query:
every row of the second table
SELECT * FROM table1 CROSS
● It is similar to the cartesian product JOIN table2;
EXCLUSIVE JOIN IN SQL
Exclusive joins are used when we want to retrieve data from two tables excluding matched
rows. They are a part of outer joins or full outer join.
Left Exclusive JOIN When we retrieve records from the left table Query:
excluding the ones matching in both the left
and right table . SELECT columns FROM table1
LEFT JOIN table2 ON
table1.colName = table2.colName;
WHERE table2.colName IS NULL;
Right Exclusive JOIN When we retrieve records from the right Query:
table excluding the ones matching in both
the left and right table . SELECT columns FROM table1
RIGHT JOIN table2 ON
table1.colName = table2.colName;
WHERE table1.colName IS NULL;
Full Exclusive JOIN When we retrieve records from the right Query:
table and left table excluding the ones
matching in both left and right table SELECT columns FROM table1
LEFT JOIN table2 ON
table1.colName = table2.colName;
WHERE table2.colName IS NULL;
UNION
Union operator in sql combines the rows of two tables UNION operator in SQL is used to combine the results
in a single set and gives unique rows by removing of two or more SELECT queries into a single result set
duplicate rows. and gives all rows by not removing duplicate rows.
QUERY: QUERY:
WHERE CLAUSE
Subqueries can be used with WHERE clause to filter data based on conditions.
QUERY:
QUESTION - Find all the employees who have salary greater than the min salary
QUERY:
SELECT min(age) AS min_age FROM employee;
QUERY:
SELECT emp.name
FROM employee emp, (subquery)
AS subquery
WHERE emp.age > subquery.min_age;
using subqueries in SELECT:
QUESTION :- Print the employees with the average age and age of employees
QUERY:
SELECT AVG(age) FROM employee
QUERY:
SELECT (subquery)AS avg_age , age FROM employee;
Nth Highest Salary
QUERY:
SELECT DISTINCT Salary FROM // Distinct so that no value is repeated
tableName
ORDER BY Salary DESC LIMIT n-1, 1; //n is nth value which we want to calculate.
Views In SQL
A view is a virtual table in SQL. It helps in providing a filtered view of data for security purposes.
Some time we in company we have to share some data to other and at the same time we have to
maintain data abstraction so that we use view command
QUERY:
CREATE VIEW viewName AS SELECT columns FROM baseTableName;
Query:
(to create a procedure)
CREATE PROCEDURE procedureName()
BEGIN
Query
END;
Query:
(to call the procedure)
CALL procedureName();
Examples: Return the details of the order by id (Stored procedure with params)
Query 2:
CREATE PROCEDURE getAllOrderDetailsById(IN id int)
BEGIN
SELECT *FROM Orders WHERE id = id;
END;