0% found this document useful (0 votes)
70 views

SQL Notes

The document discusses Structured Query Language (SQL) and Relational Database Management Systems (RDBMS). SQL is a standard language used to create, access, and manipulate databases. It allows users to define tables with columns and rows, and perform operations like insert, update, delete on the data. RDBMS is a database system that stores data in tables with rows and columns, and supports CRUD operations. Some examples of RDBMS software include Oracle, MySQL, and SQL Server. The document also covers SQL components, creating and altering database tables, and inserting, updating, and deleting data.

Uploaded by

Hh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
70 views

SQL Notes

The document discusses Structured Query Language (SQL) and Relational Database Management Systems (RDBMS). SQL is a standard language used to create, access, and manipulate databases. It allows users to define tables with columns and rows, and perform operations like insert, update, delete on the data. RDBMS is a database system that stores data in tables with rows and columns, and supports CRUD operations. Some examples of RDBMS software include Oracle, MySQL, and SQL Server. The document also covers SQL components, creating and altering database tables, and inserting, updating, and deleting data.

Uploaded by

Hh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 76

▪The Structured Query Language (SQL) is a standard

programming language to access and manipulate databases.


SQL allows the user to create, retrieve, alter, and transfer
information among databases.
▪It is a language designed for managing and accessing data in
a Relational Data Base Management System (RDBMS).
▪RDBMS stands for Relational DataBase Management System.
Oracle, MySQL, MS SQL Server, IBM DB2 and Microsoft
Access are RDBMS packages. SQL is a language used to
access data in such databases.
▪In general, Database is a collection of tables that store sets of
data that can be queried for use in other applications. A
database management system supports the development,
administration and use of database platforms.
▪RDBMS is a type of DBMS with a row-based table structure
that connects related data elements and includes functions
related to Create, Read, Update and Delete operations,
collectively known as CRUD.
▪The data in RDBMS, is stored in database objects, called
Tables. A table is a collection of related data entries and it
consist of rows and columns.

4
▪A field is a column in a table that is designed to maintain
specific related information about every record in the table.

▪It is a vertical entity that contains all information associated


with a specific field in a table.

▪The fields in a student table may be of the type AdmnNo,


StudName, StudAge, StudClass, Place etc.
▪A Record is a row, which is a collection of related fields or
columns that exist in a table.

▪A record is a horizontal entity in a table which represents the


details of a particular student in a student table.

6
Components of SQL
▪SQL commands are divided into four categories:
1. To create a database, type the following command.
CREATE DATABASE database_name;
For example to create a database to store the tables,
CREATE DATABASE stud;
2. To work with the database, type the following command.
USE DATABASE;
For example to use the stud database created,
USE stud;
▪ The Data Definition Language (DDL) consist of SQL statements
used to define the database structure or schema.
▪ It simply deals with descriptions of the database schema and is
used to create and modify the structure of database objects in
databases.
▪ The DDL provides a set of definitions to specify the storage
structure and access methods used by the database system.
▪SQL commands which come under Data Definition Language
are:
Data Definition Language (DDL)
Command Description
CREATE Creates table in the database.
ALTER Alters the structure of the database.
DROP Deletes table from database.
By Data Manipulation we mean,
▪Insertion of new information into the database
▪Retrieval of information stored in a database.
▪Deletion of information from the database.
▪Modification of data stored in the database.
▪SQL commands which come under Data Manipulation
Language are :
Data Manipulation Language (DML)
Command Description
INSERT Inserts data into a table
UPDATE Updates the existing data within a table.
Deletes all records from a table, but not the space
DELETE
occupied by them.
Data Type Description
Fixed width string value. Values of this type is
char
enclosed in single quotes.
(Character)
For ex. Anu’s will be written as ‘Anu’‘s’.
Variable width character string. This is similar to
varchar char except the size of the
data entry vary considerably.
It is same as decimal except that the maximum
integer number of digits may not
exceed the precision argument.
Data Type Description
dec It represents a fractional number such as 15.12,
(Decimal) 0.123 etc.

int It represents a number without a decimal point.


(Integer) Here the size argument is not used.

It is same as integer but the default size may be


small int
smaller than Integer.
It represents a floating point number in base 10
float exponential notation and
may define a precision up to a maximum of 64.
▪You can create a table by using the CREATE TABLE command.
▪When a table is created, its columns are named, data types
and sizes are to be specified.
▪Each table must have at least one column.
▪ The syntax of CREATE TABLE command is :

CREATE TABLE <table-name>


(<column name><data type>[<size>]
(<column name><data type>[<size>]……);
▪The SQL command will be as follows:
CREATE TABLE Student (Admno integer(5),
Name varchar(20), Gender char(1), Age
integer, Place char(10));
▪ The previous one is a simple table structure without any
restrictions.
▪ You can also set constraints to limit the type of data that can go
into the fields of the table.
▪ Constraints are used to limit the type of data that can go into a
table.
▪ This ensures the accuracy and reliability of the data in the
database. Constraints could be either on a column level or a table
level.
▪The syntax for a table created with constraint is given as
below:
CREATE TABLE <table-name> (<column name><data
type>[<size>]<column constraint>, (<column
name><data type>[<size>]<column constraint>……
<table constraint>(<column name>,[<column
name>….])….. );
▪Following is an example for student table with “NOT NULL”
column constraint. This constraint enforces a field to always
contain a value.
CREATE TABLE Student (Admno integer NOT NULL
PRIMARY KEY, Name char(20) NOT NULL, Gender
char(1) unique, Age integer, Place char(10));
▪The previous command creates a table “student” in which
the field Admno of integer type is defined NOT NULL, Name
of char type is defined as NOT NULL which means these two
fields must have values.
▪The fields Gender, Age and Place do not have any constraints.
▪The ALTER command is used to alter the table structure like
adding a column, renaming the existing column, change the
data type of any column or size of the column or delete the
column from the table.
▪It is used in the following way :
ALTER TABLE <table-name> ADD <column-name><data
type><size>;
▪To add a new column “Address” of type ‘char’ to the Student
table, the command is used as
ALTER TABLE Student ADD Address char(20);
▪To modify existing column of table, the ALTER TABLE
command can be used with MODIFY clause like wise:
ALTER table <table-name> MODIFY <column-name> <data
type> <size>;

ALTER TABLE Student MODIFY Address varchar (20);


▪The ALTER command can be used to rename an existing
column in the following way :

ALTER <table-name> change old-column-name


new-column-name datatype(size);
▪ For example to rename the column Address to City, the
command is used as :
ALTER TABLE Student change Address City
varchar(30);
▪ The ALTER command can also be used to remove a column or all
columns, for example to remove a particular column, the DROP
COLUMN is used with the ALTER TABLE to remove a particular field,
the command can be used as:
ALTER <table-name> DROP COLUMN <column-name>;
▪To remove the column City from the Student table, the
command is used as :
ALTER TABLE Student DROP COLUMN City;
ALTER TABLE Student DROP PRIMARY KEY ;

;
▪The DROP TABLE command is used to remove a table from
the database.
▪Once a table is dropped we cannot get it back, so be careful
while using DROP TABLE command.
▪Once all the rows are deleted, the table can be deleted by
DROP TABLE command in the following way:

DROP TABLE table-name;

▪For example to delete the Student table:


DROP TABLE Student;
▪Once the schema or structure of the table is created, values
can be added to the table.
▪The DML commands consist of inserting, deleting and
updating rows into the table.
▪The INSERT command helps to add new data to the database
or add new records to the table.
▪The command is used as follows:

INSERT INTO <table-name> [column-list] VALUES (values);


INSERT INTO Student (Admno, Name, Gender, Age, Place)
VALUES (100,’ Ashish’,’ M’, 17,’ Chennai’);
INSERT INTO Student (Admno, Name, Gender)
VALUES ( 101, ‘Adarsh’, ‘M’,);
▪Two new records are added to the table as shown below:
Admno Name Gender Age Place
100 Ashish M 17 Chennai
101 Adarsh M 18 Delhi
▪The order of values must match the order of columns in the
CREATE TABLE command.
▪Specifying the column names is optional if data is to be
added for all columns.
▪The command to add values into the student table can also
be used in the following way:
INSERT INTO Student VALUES ( 102, ‘Akshith’, ‘M’, ‘17,’ ‘Bangalore’);
▪To add data to only some columns in a record by specifying
the column name and their data, it can be done by:
INSERT INTO Student(Admno, Name, Place)
VALUES (103, ‘Ayush’, ‘Delhi’);
▪The above command adds the following record with default
values of ‘M’ for Gender and Age as 18.
103 Ayush M 18 Delhi
▪The UPDATE command updates some or all data values in a
database.

▪It can update one or more records in a table.


▪The UPDATE command specifies the rows to be changed
using the WHERE clause and the new data using the SET
keyword.
▪ The command is used as follows:

UPDATE <table-name> SET column-name = value, column-name =


value,… WHERE condition;

▪ For example to update the field age:

UPDATE Student SET Age = 20 WHERE Admnno=102;


UPDATE Student SET Age = 20 WHERE Place=‘Chennai’;

The above command will change the age to 20 for those students
whose place is “Bangalore”.
▪The table will be updated as follows:

Admno Name Gender Age Place


100 Ashish M 17 Chennai
101 Adarsh M 18 Delhi
102 Akshith M 20 Bangalore
103 Ayush M 18 Delhi
▪To update multiple fields, multiple field assignment can be
specified with the SET clause separated by comma.
▪For example to update multiple fields in the Student table,
the command is given as:
UPDATE Student SET Age=18, Place = ‘Chennai’
WHERE Admno = 102 ;
UPDATE Employee SET Salary=Salary+2000 where
salary>=10000 and salary<=20000;
▪The command modifies the record in the following way.

Admno Name Gender Age Place


100 Ashish M 17 Chennai
101 Adarsh M 18 Delhi
102 Akshith M 18 Chennai
103 Ayush M 18 Delhi
▪The DELETE command permanently removes one or more
records from the table.
▪It removes the entire row, not individual fields of the row, so
no field argument is needed.
▪The DELETE command is used as follows :
DELETE FROM table-name WHERE condition;
▪For example to delete the record whose admission number is
104 the command is given as follows:

DELETE FROM Student WHERE Admno=104;

▪The following record is deleted from the Student table.


104 Abinandh M 18 Chennai
▪To delete all the rows of the table, the command is used as :
DELETE FROM Student;

▪The table will be empty now and could be destroyed using


the DROP command
DELETE The DELETE command deletes only the rows from the table
based on the condition given in the where clause or deletes
all the rows from the table if no condition is specified. But it does
not free the space containing the table.

DROP The DROP command is used to remove an object from the


database. If you drop a table, all the rows in the table is deleted
and the table structure is removed from the database. Once a
table is dropped we cannot get it back.
▪One of the most important tasks when working with SQL is to
generate Queries and retrieve data.
▪A Query is a command given to get a desired result from the
database table.
▪The SELECT command is used to query or retrieve data from
a table in the database.
▪The SELECT command is used to retrieve a subset of records
from one or more tables.
▪The SELECT command can be used in various forms:
Syntax:

SELECT <column-list> FROM <table-name>;

Table-name is the name of the table from which the information is


retrieved.
Column-list includes one or more columns from which data is retrieved.
▪Student table has the following data:
Admno Name Gender Age Place
100 Ashish M 17 Chennai
101 Adarsh M 18 Delhi
102 Akshith M 17 Bangalore
103 Ayush M 18 Delhi
104 Abinandh M 18 Chennai
105 Revathi F 19 Chennai
106 Devika F 19 Bangalore
107 Hema F 17 Chennai
SELECT Admno, Name FROM Student;
The above SELECT command Admno Name
100 Ashish
will display the data as: 101 Adharsh
102 Akshith
103 Ayush
104 Abinandh
105 Revathi
106 Devika
107 Hema
▪To view all the fields and rows, command can be given as
SELECT * FROM Student;
Admno Name Gender Age Place
100 Ashish M 17 Chennai
101 Adarsh M 18 Delhi
102 Akshith M 17 Bangalore
103 Ayush M 18 Delhi
104 Abinandh M 18 Chennai
105 Revathi F 19 Chennai
106 Devika F 19 Bangalore
107 Hema F 17 Chennai
▪The WHERE clause in the SELECT command specifies the
criteria for getting the desired result.
▪The general form of SELECT command with WHERE Clause is:
SELECT <column-name>[,<column-name>,….] FROM
<table-name> WHERE condition>;
▪For example to display the students admission number and
name of only those students who belong to Chennai, the
SELECT command is used in the following way :
SELECT Admno, Name, Place FROM Student WHERE Place =
Admno Name Place ”Chennai”;
100 Ashish Chennai
104 Abinandh Chennai
105 Revathi Chennai
107 Hema Chennai
SELECT Admno, Name, Age FROM Student WHERE Age >= 18;

Admno Name Age


101 Adarsh 18
103 Ayush 18
104 Abinandh 18
105 Revathi 19
106 Devika 19
▪The relational operators like =, <, <=, >, >=, <> can be used to
compare two values in the SELECT command used with
WHERE clause. The logical operators AND, OR, and NOT can
also be used to connect search conditions in the WHERE
clause.
For example :
SELECT Admno, Name, Age, Place FROM Student WHERE
(Age>=18 AND Place = "Delhi");
Admno Name Age Place
101 Adarsh 18 Delhi
103 Ayush 18 Delhi
The SELECT command can also be used in the following ways:
SELECT Admno, Name, Age, Place FROM Student
WHERE (Age>=18 OR Place ="Delhi");
SELECT Admno, Name, Place FROM Student WHERE (NOT Place ="Delhi");
▪The DISTINCT keyword is used along with the SELECT
command to eliminate duplicate rows in the table. This helps
to eliminate redundant data.
▪For Example:
SELECT DISTINCT Place FROM Student; Place
Chennai
▪When the keyword DISTINCT is used, only one Bangalore
NULL value is returned, even if more NULL Delhi

values occur.
▪ The BETWEEN keyword defines a range of values the record must fall
into to make the condition true.
▪ The range may include an upper value and a lower value between
which thecriteria must fall into.
SELECT Admno, Name, Age, Gender FROM Student WHERE
Age BETWEEN 18 AND 19;
Admno Name Gender Age
101 Adarsh M 18
103 Ayush M 18
104 Abinandh M 18
105 Revathi F 19
106 Devika F 19
▪The NOT BETWEEN is reverse of the BETWEEN operator
where the records not satisfying the condition are displayed.

SELECT Admno, Name, Age FROM Student WHERE


Age NOT BETWEEN 18 AND 19;
Admno Name Age
100 Ashish 17
102 Akshith 17
107 Hema 17
▪The IN keyword is used to specify a list of values which must
be matched with the record values.
▪In other words it is used to compare a column with more
than one value.
▪It is similar to an OR condition.
▪For example :
SELECT Admno, Name, Place FROM Student WHERE Place IN
(“Chennai”, “Delhi”);

Admno Name Place


100 Ashish Chennai
101 Adarsh Delhi
103 Ayush Delhi
104 Abinandh Chennai
105 Revathi Chennai
107 Hema Chennai
▪The NOT IN keyword displays only those records that do not
match in the list.
SELECT Admno, Name, Place FROM Student WHERE Place NOT
IN (“Chennai”, “Delhi”);
will display students only from places other than “Chennai”
and “Delhi”. Admno Name Place
102 Akshith Bangalore
106 Devika Bangalore
▪The NULL value in a field can be searched in a table using the
IS NULL in the WHERE clause.
▪For example to list all the students whose Age contains no
value, the command is used as:
SELECT * FROM Student WHERE Age IS NULL;
LIKE is used with two wildcard characters:

a)%

b)_
• Search for employee whose name begins from ‘s’
like ‘s%’;

• Search for employee whose name ends with ‘r’


like ‘%r’;

• Search for employee whose name contains ‘a’ anywhere


like ‘%a%’

• Search for employee whose dob is in feb

like ‘%-02-%’

• Search employee whose name is of 5 letters begins from ‘s’

‘s_ _ _ _ ’;
▪The ORDER BY clause in SQL is used to sort the data in either
ascending or descending based on one or more columns.
1. By default ORDER BY sorts the data in ascending order.
2. We can use the keyword DESC to sort the data in descending
order and the keyword ASC to sort in ascending order.
The ORDER BY clause is used as:
SELECT <column-name>[,<column-name>,….] FROM <table-
name> ORDER BY <column1>,<column2>,… ASC | DESC ;
▪To display the students in alphabetical order of their names:
SELECT * FROM Student ORDER BY Name ;
Admno Name Gender Age Place
104 Abinandh M 18 Chennai
101 Adarsh M 18 Delhi
102 Akshith M 17 Bangalore
100 Ashish M 17 Chennai
103 Ayush M 18 Delhi
106 Devika F 19 Bangalore
107 Hema F 17 Chennai
105 Revathi F 19 Chennai
SELECT * FROM Student WHERE Age>=18 ORDER BY Name;
Admno Name Gender Age Place
104 Abinandh M 18 Chennai
101 Adarsh M 18 Delhi
103 Ayush M 18 Delhi
106 Devika F 19 Bangalore
105 Revathi F 19 Chennai
AGGREGATE functions

1.SUM()
2.AVG()
3.COUNT()
4.MAX()
5.MIN()
6.COUNT(*)
Select SUM(salary) from emp;
Output – 161000
Select SUM(salary) from emp where dept=‘sales’;
Output - 59000
Select AVG(salary) from emp;
Output – 32200
Select AVG(salary) from emp where dept=‘sales’;
Output - 29500
COUNT(name)
Output – 5
COUNT(salary)
Output - 1
COUNT(DISTINCT dept)
Output – 3

• Select MAX(Salary) from emp;


Output – 45000
• Select MAX(salary) from emp where dept=‘Sales’;
Output - 35000
MIN(Salary)
Output – 24000

• Select MIN(salary) from emp where dept=‘IT’;


Output -27000

• Select COUNT(*) from emp;


Output – 5

• Select COUNT(salary) from emp;


Output - 5
count(*) Vs count()
• Count(*)
count()

• All aggregate function ignores the NULL values


▪The GROUP BY clause is used with the SELECT statement to
group the rows or columns having identical values or
divide the table in to groups.
▪For example to know the number of male students or female
students of a class, the GROUP BY clause may be used.
▪It is mostly used in conjunction with aggregate functions to
produce summary reports from the database.
▪The syntax for the GROUP BY clause is
SELECT <column-names> FROM <table-name> GROUP BY
<column-name> HAVING condition];

▪To apply the above command on the student table :


SELECT Gender FROM Student GROUP BY Gender;
▪The result will be given as: Gender
M
F
▪The point to be noted is that only two results have been
returned. This is because we only have two gender types
‘Male’ and ‘Female’.
▪The GROUP BY clause grouped all the ‘M’ students together
and returned only a single row for it. It did the same with the
‘F’ students.
▪For example to count the number of male and female
students in the student table, the following command is
given :

SELECT Gender, count(*) FROM Student GROUP BY Gender;

Gender Count (*)


M 5
F 3
▪The HAVING clause can be used along with GROUP BY clause
in the SELECT statement to place condition on groups and
can include aggregate functions on them. For example to
count the number of Male and Female students belonging to
Chennai .
SELECT Gender , count(*) FROM Student GROUP BY
Gender HAVING Place = ‘Chennai’;
Gender Count (*)
M 5
F 3
▪The above output shows the number of Male and Female
students in Chennai from the table Student.

You might also like