0% found this document useful (0 votes)
35 views29 pages

SQL GreatthoughtsIT 8april24

sql

Uploaded by

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

SQL GreatthoughtsIT 8april24

sql

Uploaded by

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

What is Data

 The first two components of information systems: Hardware and Software. Without data,
hardware and software are not very useful. Data is the third component of an information
system.
 Data are the raw bits and pieces of information with no context. If I told you, “15, 23, 14,
85,” you would not have learned anything.
 By itself, data is not that useful. To be useful, it needs to be given context. Returning to the
example above, if I told you that “15, 23, 14, and 85″ are the numbers of students that had
registered for upcoming classes, that would be information.
 Data can be quantitative or qualitative. Quantitative data is numeric, the result of a
measurement, count, or some other mathematical calculation. Qualitative data is
descriptive. “Ruby Red,” the color of a 2013 Ford Focus, is an example of qualitative data.
 Once we have put data into context, aggregated and analyzed it. We can use that to
make decisions. Once we consume of this information produces knowledge. This
knowledge can be used to make decisions, set policies etc.,
What is Data Base

 The goal of many information systems is to transform data into information in order to
generate knowledge that can be used for decision making. In order to do this, the system
must be able to take data, put the data into context, and provide tools for aggregation
and analysis. A database is designed for just such a purpose.
 The database stores the data in well-structured format/in organized manner. We can derive
information from a well-structured data.
 A database is a place to store information permanently. It can store the simplest data, such
as a list of people as well as the most complex data.
 A database is a systematic collection of data. They support electronic storage and
manipulation of data. Databases make data management easy.
 The database's primary goal is to store a huge amount of data.
 Example: An online telephone directory uses a database to store data of people, phone
numbers, and other contact details. Your electricity service provider uses a database to
manage billing, client-related issues, handle fault data, etc
Why use Data Base

 Databases are able to store vast numbers of records in an effective manner.


 It's simple to locate data, add new data and modify or delete available data.
 Data can be easily searched in a database using techniques like indexing, binary
searching, etc.
 Data can be quickly and easily sorted in a database. It can be imported into other
applications easily.
 Database is Multi-access means that more than one person can use the same
database at the same time.
 The security of data in the database is more than that of physical paper files
because the database provides additional security patterns for authorized access.
 Databases are also used for transaction management. Transactions are some set of
programs used for some logical word, databases are used to maintain consistency
and accuracy during the transactions.
What is DBMS

 A database management system is software that manages a database by storing,


retrieving, and manipulating the data from a database. Oracle, MySQL, etc
are well-known DBMS tools.
 Some functions of a Database Management System are:
 A database management system (DBMS) provides an interface for performing
various activities such as creation, deletion, and modification of the data.
 A database management system (DBMS) allows users to design databases that
meet their specific needs.
 A database management system (DBMS) is a collection of programs that respond
to user commands.
 It ensures the database's safety by providing security patterns like password
protection and verification to ensure access to only authorized users.
 It can be easily used using the queries.
Types of DB’s
 Distributed databases: Contributions from the common database and information captured by
local computers
 Relational databases: DB relationships in the form of tables. Example of the RDBMS system include MySQL,
Oracle, and SQL Server.
 Object-oriented databases: The data is stored in the form of objects. PostgreSQL is an example of an object-
oriented relational DBMS
 Centralized database: This type of computers databases store application procedures that help
users access the data even from a remote location.
 Cloud databases: A database which is optimized or built for such a virtualized environment. There are so many
advantages of a cloud database, some of which can pay for storage capacity and bandwidth. It also offers
scalability on-demand, along with high availability.
 NoSQL databases: NoSQL database is used for large sets of distributed data. There are a few big data performance problems
that are effectively handled by relational databases. This type of computers database is very efficient in analyzing large-size
unstructured data.

 Graph databases: A graph-oriented database uses graph theory to store, map, and query relationships. These kinds of
computers databases are mostly used for analyzing interconnections. For example, an organization can use a graph database to
mine data about customers from social media.

 Personal database: A personal database is used to store data stored on personal computers that are smaller and easily
manageable. The data is mostly used by the same department of the company and is accessed by a small group of people.
What is SQL - https://dev.mysql.com/downloads/installer/

• SQL stands for Structured Query Language.


• SQL is a programming language for storing and processing information in a relational database. A relational
database stores information in tabular form, with rows and columns representing different data attributes and
the various relationships between the data values. You can use SQL statements to store, update, remove,
search, and retrieve information from the database. You can also use SQL to maintain and optimize
database performance.
• SQL is required for the following tasks
To create new databases, tables, and views
To insert records in a database
To update records in a database
To delete records from a database
To retrieve data from a database
SQL used for CRUD operations . (C create R read U update D delete)
DBMS vs RDBMS
DBMS RDBMS
In DBMS data are store as a file. In Rdbms data are store in a tabular form.

In dbms relationship between two tables or files are In Rdbms relationship between two tables or files can be
maintained programmatically specified at the time of table creation.

Dbms does not support client server architecture. Rdbms supports client server architecture.

Dbms does not support distributed architecture. Rdbms support distributed architecture.

In rdbms there are multiple level of security, at logging level, at


In dbms there are no security of data.
command level, at object level.

Dbms may satisfy less than 7 rules of Dr. e.f codd Rdbms usually satisfy more than 7 to 8 rules of Dr. e.f codd.

Normalization is not available in DBMS. Normalization is available in RDBMS.

Examples of DBMS are file systems, xml etc. Example of RDBMS are mysql, postgre, sql server, oracle etc.
Data Base Schema
It’s the database designers who design the schema to help programmers understand the database and make it useful.

A database schema is a structure that represents the logical storage of the data in a database.

A database schema is the logical representation of a database, which shows how the data is stored logically in the entire
database.

A database schema contains schema objects that may include tables, fields, packages, views, relationships, primary key,
foreign key etc.,

The schema does not physically contain the data itself; instead, it gives information about the shape of data and how it can be
related to other tables or models.

A database schema can be divided broadly into two categories −

Physical Database Schema − This schema pertains to the actual storage of data and its form of storage like files, indices,
etc. It defines how the data will be stored in a secondary storage.

Logical Database Schema − This schema defines all the logical constraints that need to be applied on the data stored. It
defines tables, views, and integrity constraints.
SQL Commands

 SQL commands are instructions. It is used to communicate with the


Create Example database. It is also used to perform specific tasks, functions, and
queries of data.
 SQL can perform various tasks like create a table, add data to
tables, drop the table, modify the table, set permission for users.
Types of SQL Commands
 There are five types of SQL commands:
 DDL
 DML
CREATE TABLE students ( id INTEGER
PRIMARY KEY, name VARCHAR(30) NOT  DCL
NULL, gender CHAR(1) NOT NULL);
 TCL
 DQL
Big Picture
Data Types in SQL
Data type Syntax

Integer INTEGER

Smallint SMALLINT

Numeric NUMERIC(P,S)

Real REAL

Decimal DECIMAL(P,S)

Float FLOAT(P)

Character CHAR(X)

Character varying VARCHAR2(X)

Date Date

Time TIME
Table Commands (Create/Drop/Alter/Truncate)
CREATE TABLE Students (
StdID int ,
StudentName varchar(255) ,
Branch varchar(255),
Specialization varchar(255),
Gender varchar(255),
Age int
);

ALTER TABLE Students ADD Email varchar(255);

TRUNCATE TABLE Students;

DROP TABLE Students;


Table Commands (Insert/Update/Delete)

Insert into Students values(1,'AABC1', 'Btech', 'MEC', 'M', 19);


Insert into Students values(2,'AABC2', 'Btech', 'ECE', 'M', 19);

Insert into students (stdid, stname) values (2, ‘Krishna’);

UPDATE Students SET StudentName =‘Srinivas', WHERE StdID =1;

DELETE FROM Students WHERE StudentName =‘Srinivas';


Table Commands (Grant/Revoke)
GRANT SELECT, INSERT, DELETE, UPDATE ON Users TO 'Sai'@'localhost;

SHOW GRANTS FOR ‘Sai'@localhost';

REVOKE SELECT ON users FROM 'Sai'@localhost';

REVOKE SELECT, INSERT, DELETE, UPDATE ON Users FROM 'Sai'@'localhost;

REVOKE ALL ON Users FROM 'Sai'@'localhost;


Table Commands (Commit/Rollback/Savepoint)
 The COMMIT statement lets a user save any changes or alterations on the current
transaction. These changes then remain permanent.
Ex: Commit;

 The ROLLBACK statement lets a user undo all the alterations and changes that occurred
on the current transaction after the last COMMIT.
Ex: Rollback;

 Savepoint is a command in SQL that is used with the rollback command. Consider you
are making a very long table, and you want to roll back only to a certain position in a
table then; this can be achieved using the savepoint
 START TRANSACTION;

 SAVEPOINT ini
Constraints

• NOT NULL - Ensures that a column cannot have a NULL value


• UNIQUE - Ensures that all values in a column are different
• PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each row in a table
• FOREIGN KEY - Prevents actions that would destroy links between tables
• CHECK - Ensures that the values in a column satisfies a specific condition
• DEFAULT - Sets a default value for a column if no value is specified
• CREATE INDEX - Used to create and retrieve data from the database very quickly
Table Creation with Constraints:

CREATE TABLE Persons ( ID int NOT NULL,


LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);

CREATE TABLE Persons ( ID int NOT NULL,


LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
UNIQUE (ID)
);

CREATE TABLE Persons ( ID int NOT NULL,


LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT UC_Person UNIQUE (ID,LastName)
);
Continues…!

 CREATE TABLE Persons (  CREATE TABLE Persons (


Personid int NOT NULL AUTO_INCREMENT, ID int NOT NULL,
LastName varchar(255) NOT NULL, LastName varchar(255) NOT NULL,
FirstName varchar(255), FirstName varchar(255),
Age int, Age int,
PRIMARY KEY (Personid) City varchar(255),
); CONSTRAINT CHK_Person CHECK (Age>=18 AND
City='Sandnes')
);
 CREATE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName  MySQL primary key is a single or combination of the
FROM Customers field, which is used to identify each record in a table
WHERE Country = 'Brazil'; uniquely. If the column contains primary key constraints,
then it cannot be null or empty. A table may have
duplicate columns, but it can contain only one primary
key.
Continues…!

 ALTER TABLE Persons  CREATE TABLE Persons (


 ADD CONSTRAINT UC_Person UNIQUE  ID int NOT NULL,
(ID,LastName);
 LastName varchar(255) NOT NULL,
 ALTER TABLE Persons
 FirstName varchar(255),
 DROP CONSTRAINT UC_Person;
 Age int,

 CONSTRAINT PK_Person PRIMARY KEY (ID, LastName)
 CREATE TABLE Persons (  );
 ID int NOT NULL,
 LastName varchar(255) NOT NULL,  ALTER TABLE Persons
 FirstName varchar(255),  DROP PRIMARY KEY;
 Age int, 

 PRIMARY KEY (ID)



Table Select:

SELECT * FROM Persons;


SELECT ID , LastName , Age FROM Persons ;
SELECT COUNT(*) FROM persons; -- Display number of records present in the persons table

ORDER BY :- Used this command to display the data of a column in particular order
ASC for Ascending order
DESC for Descending order

SELECT COUNT(DISTINCT Age ) FROM Persons ;

GROUP BY :- GROUP BY clause is used to collect data across multiple records and group the results by one or
more columns.

HAVING :- The HAVING clause is used to apply a filter on the result of GROUP BY based on the specified
condition.

The GROUP BY and HAVING clauses of Aggregate Functions are used more often with SELECT statements in
SQL queries. Generally used in reports of large data.
Table Select:

CREATE TABLE Employee(


EmployeeId number,
Name Varchar2(20),
Gender Varchar2(20),
Salary number,
Department Varchar2(20),
Experience Varchar2(20)
);

INSERT INTO Employee VALUES (1, 'Rachit', 'M', 50000, 'Engineering', '6 year')
INSERT INTO Employee VALUES (2, 'Shobit', 'M', 37000, 'HR', '3 year')
INSERT INTO Employee VALUES (3, 'Isha', 'F', 56000, 'Sales', '7 year')
INSERT INTO Employee VALUES (4, 'Devi', 'F', 43000, 'Management', '4 year')
INSERT INTO Employee VALUES (5, 'Akhil', 'M', 90000, 'Engineering', '15 year')

SELECT Department, sum(Salary) as Salary


FROM employee
GROUP BY department;

SELECT Department, sum(Salary) as Salary


FROM employee
GROUP BY department
HAVING SUM(Salary) >= 50000;
Joins
JOINS :-

The join clause allows us to retrieve data from two or more related tables into a meaningful result set.
We can join the table using a SELECT statement and a join condition.
It indicates how SQL can use data from one table to select rows from another table.
In general, tables are related to each other using foreign key constraints.

There are four types of JOINS

INNER JOIN
SELF JOIN
CROSS JOIN
OUTER JOIN

CREATE TABLE Student (


id int PRIMARY KEY IDENTITY,
admission_no varchar(45) NOT NULL,
first_name varchar(45) NOT NULL,
last_name varchar(45) NOT NULL,
age int,
city varchar(25) NOT NULL
);
Joins
CREATE TABLE Fee (
admission_no varchar(45) NOT NULL,
course varchar(45) NOT NULL,
amount_paid int,
);

INSERT INTO Student VALUES(1,3354,'Luisa', 'Evans', 13, 'Texas');


INSERT INTO Student VALUES(2,2135, 'Paul', 'Ward', 15, 'Alaska');
INSERT INTO Student VALUES(3,4321, 'Peter', 'Bennett', 14, 'California');
INSERT INTO Student VALUES(4,4213,'Carlos', 'Patterson', 17, 'New York');
INSERT INTO Student VALUES(5,5112, 'Rose', 'Huges', 16, 'Florida');
INSERT INTO Student VALUES(6,6113, 'Marielia', 'Simmons', 15, 'Arizona');
INSERT INTO Student VALUES(7,7555,'Antonio', 'Butler', 14, 'New York');
INSERT INTO Student VALUES(8,8345, 'Diego', 'Cox', 13, 'California');

INSERT INTO Fee VALUES (3354,'Java', 20000);


INSERT INTO Fee VALUES(7555, 'Android', 22000);
INSERT INTO Fee VALUES(4321, 'Python', 18000);
INSERT INTO Fee VALUES(8345,'SQL', 15000);
INSERT INTO Fee VALUES(5112, 'Machine Learning', 30000);
Joins
INNER JOINS :-

INNER JOIN
This JOIN returns all records from multiple tables that satisfy the specified join condition.
It is the simple and most popular form of join and assumes as a default join.
If we omit the INNER keyword with the JOIN query, we will get the same output.

SELECT Student.admission_no, Student.first_name, Student.last_name, Fee.course, Fee.amount_paid


FROM Student
INNER JOIN Fee
ON Student.admission_no = Fee.admission_no;

SELF JOIN :- It means that each table row is combined with itself and with every other table row.
The SELF JOIN can be thought of as a JOIN of two copies of the same tables.
We can do this with the help of table name aliases to assign a specific name to each table's instance.
The table aliases enable us to use the table's temporary name that we are going to use in the query.
It's a useful way to extract hierarchical data and comparing rows inside a single table.

SELECT S1.first_name, S2.last_name, S2.city


FROM Student S1, Student S2
WHERE S1.id <> S2.iD AND S1.city = S2.city
ORDER BY S2.city;
Joins
CROSS JOIN
CROSS JOIN in SQL Server combines all of the possibilities of two or more tables and returns a result that includes every row from all
contributing tables.
It's also known as CARTESIAN JOIN because it produces the Cartesian product of all linked tables.
The Cartesian product represents all rows present in the first table multiplied by all rows present in the second table.

SELECT Student.admission_no, Student.first_name, Student.last_name, Fee.course, Fee.amount_paid


FROM Student
CROSS JOIN Fee
WHERE Student.admission_no = Fee.admission_no;

OUTER JOIN
OUTER JOIN in SQL Server returns all records from both tables that satisfy the join condition. In other words, this join will not return only the
matching record but also return all unmatched rows from one or both tables.

We can categories the OUTER JOIN further into three types:

LEFT OUTER JOIN


RIGHT OUTER JOIN
FULL OUTER JOIN
Joins
LEFT OUTER JOIN
The LEFT OUTER JOIN retrieves all the records from the left table and matching rows from the right table.
It will return NULL when no matching record is found in the right side table. Since OUTER is an optional keyword,
it is also known as LEFT JOIN.

SELECT Student.admission_no, Student.first_name, Student.last_name, Fee.course, Fee.amount_paid


FROM Student
LEFT OUTER JOIN Fee
ON Student.admission_no = Fee.admission_no;

RIGHT OUTER JOIN


The RIGHT OUTER JOIN retrieves all the records from the right-hand table and matched rows from the left-hand table.
It will return NULL when no matching record is found in the left-hand table. Since OUTER is an optional keyword,
it is also known as RIGHT JOIN

SELECT Student.admission_no, Student.first_name, Student.last_name, Fee.course, Fee.amount_paid


FROM Student
RIGHT OUTER JOIN Fee
ON Student.admission_no = Fee.admission_no;
Joins
FULL OUTER JOIN
The FULL OUTER JOIN in SQL Server returns a result that includes all rows from both tables.
The columns of the right-hand table return NULL when no matching records are found in the left-hand table.
And if no matching records are found in the right-hand table, the left-hand table column returns NULL.

SELECT Student.admission_no, Student.first_name, Student.last_name, Fee.course, Fee.amount_paid


FROM Student
FULL OUTER JOIN Fee
ON Student.admission_no = Fee.admission_no;
tatement Syntax
SELECT column_name(s)
FROM table_name
/ OR
WHERE condition
AND|OR condition
ALTER TABLE table_name
ADD column_name datatypeor
TABLE
ALTER TABLE table_name
DROP COLUMN column_name
SELECT column_name AS column_alias
FROM table_nameor
ias)
SELECT column_name
FROM table_name AS table_alias
SELECT column_name(s)
FROM table_name
EEN
WHERE column_name
BETWEEN value1 AND value2
TE
CREATE DATABASE database_name
BASE
CREATE TABLE table_name
(
ment Syntax

SELECT column_name(s) FROM table_name WHERE column_name IN (value1,value2,..)


INTO INSERT INTO table_name
VALUES (value1, value2, value3,....)or
INSERT INTO table_name
(column1, column2, column3,...)
VALUES (value1, value2, value3,....)
JOIN SELECT column_name(s)
FROM table_name1
INNER JOIN table_name2
ON table_name1.column_name=table_name2.column_name
OIN SELECT column_name(s)
FROM table_name1
LEFT JOIN table_name2
ON table_name1.column_name=table_name2.column_name
JOIN SELECT column_name(s)
FROM table_name1
RIGHT JOIN table_name2
ON table_name1.column_name=table_name2.column_name
OIN SELECT column_name(s)
FROM table_name1
FULL JOIN table_name2

You might also like