Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Database and SQL Final

The document provides an overview of database concepts, including the relational data model, SQL commands, and database management systems. It covers key topics such as data types, constraints, DDL and DML commands, and the interface of Python with SQL databases. Additionally, it discusses the importance of reducing data redundancy and ensuring data integrity within a database system.

Uploaded by

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

Database and SQL Final

The document provides an overview of database concepts, including the relational data model, SQL commands, and database management systems. It covers key topics such as data types, constraints, DDL and DML commands, and the interface of Python with SQL databases. Additionally, it discusses the importance of reducing data redundancy and ensuring data integrity within a database system.

Uploaded by

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

• Database concepts: introduction to database concepts and its need

• Relational data model: relation, attribute, tuple, domain, degree,


cardinality, keys (candidate key, primary key, alternate key, foreign key)

• Structured Query Language: introduction,


• Data Definition Language and Data Manipulation Language,
• data type (char(n), varchar(n), int, float, date),

• constraints (not null, unique, primary key),


• create database, use database, show databases, drop database, show
tables, create table, describe table, alter table (add and remove an attribute,
add and remove primary key), drop table, insert, delete, select, operators
(mathematical, relational and logical), aliasing, distinct clause, where
clause, in, between, order by, meaning of null, is null, is not null, like, update
command, delete command
• Aggregate functions (max, min, avg, sum, count), group by, having
clause,

• joins : Cartesian product on two tables, equi-join and natural join

• Interface of python with an SQL database: connecting SQL with Python,


performing insert, update, delete queries using cursor, display data by using
fetchone(), fetchall(), rowcount, creating database connectivity applications
 Raw facts and  Meaningful/
figures processed
data
 to store records permanently
 Files are specific to an application
 Drawbacks
o data redundancy
o data inconsistency
o non- sharable data
o non-standardized data
o insecure data
o incorrect data
 Collectionof inter related data to
serve multiple applications
 Is a computer –based record
keeping system
 A software to manage database and run
operations on the data requested (store,
maintain and utilize) provides centralized
control of data
 e.g. Oracle, Sybase, MySQL
 Has data organized into tables(i.e. rows and columns)
or relations
 A row in a table represents a relationship among a set
of values.
 A table is a collection of such relationships hence
called as relation.
 software to create a database which is a
collection of tables.
 It manages database and runs operations
on the data requested (store, maintain and
utilize) provides centralized control of
data
 Oracle
 Microsoft SQL Server
 IBM DB2
 IBM Informix
 SAP Sybase Adaptive Server Enterprise
 SAP Sybase IQ
 Teradata
 MySQL
 Is a part of open source enterprise stack LAMP DBMS for Mobile
(Linux, Apache, MySQL, PHP) Devices
 runs on all platforms e.g. Linux, Unix and
Windows  SQL Anywhere
 popular for web-based applications and online  DB2 Everywhere
publishing  IBM Mobile Database
 PostgreSQL
 SQL Server Compact
 Free and most advanced open source database
systems.  SQL Server Express
 Its source code is available under PostgreSQL  Oracle DatabaseLite
license, a liberal open source license
 SQLite
 SQLite
 Is not client-server database engine rather it is  SQLBase
embedded into the end program
 Used widely by several browsers, OSs and
embedded systems (such as mobile phones)

 A databasealong with a
DBMS is referred to as a
database system.
 reduces data redundancy-data redundancy means duplication of
data(no separate copies of data)
 reduces data inconsistency- means incorrect or conflicting data.
(multiple copies of same data (propagates updates at all places)
 facilitates data sharing-data is shared by many different users
 enforces data standards-stores standardized data format and
facilitates the data interchange /migration between systems
 ensures data security-centralized database protects data against
unauthorized users and gives access to authorized users by
carrying out authorization checks for sensitive data
 maintains data integrity- unification of several distinct data files
reduces data redundancy to a greater extent and integrity checks
are designed to ensure that data values confirms to certain
specified rules
 is an open source RDBMS software which can
be easily downloaded from the official
website https://dev.mysql.com/downloads.

 After installing MySQL, start MySQL service.


The appearance of mysql> prompt means
that MySQL is ready to accept SQL statements
• 2-D table storing logically related data
• Each column has a name & contains single
value for each row
• Each row must be unique/distinct
• Is a collection of relationships where a row
represents a relationship among a set of
values.
 Rows of a table/relation where each row
represents a complete unit of information
about a single entity
 Columns of a table/relation where each
column represents one type of information
 No. of rows  No. of columns
(tuples)in a (attributes)in a
relation relation
 Setof possible values for a specified
column
Keys Attributes used to distinguish the rows
Primary key One or more columns to uniquely identify rows within a table
When Primary key consists of more than one attribute then it is
called composite-Primary key. The non-primary key attributes of
a table are called as non-key attributes

Candidate key All column combinations that can serve as a primary key (are
candidates for primary key)
Alternate key A candidate key which is not the primary key

Foreign key Non-key attribute whose value is derived from the primary key
of another table
OR
Non-key attribute which is the primary key of some other table
Foreign/Detail table- in which foreign key exists
Primary/Master table – defines the Primary key, which the
foreign key of Detail table refers to.
 is a data sublanguage containing a set of commands used by
RDBMS(e.g MySQL database) to access data.
 Is a 4th generation non-procedural language (specifies WHAT
is required but not on HOW it is to be done) that enables us to
create and operate on relational databases
 It works on a PC, a workstation, a mini or a mainframe.
 There are numerous versions of SQL.
 Structured Query Language used by RDBMS to communicate
with database
 Manages one or more data tables and relationships between data
tables with information in the data dictionary
 Is efficient, easy to use and learn , functionally
complete
 Recovery and concurrency
 Security -by views
 Integrity constraints –to ensure data values in
columns confirm to certain specified rules
Char(n) Varchar(n)
Specifies fixed-length Specifies variable-length
character string character string
If char(n) is specified If varchar(n) is specified datatype
datatype for a column, for a column,
nsize of values stored in n max.size of values stored in
this column is n bytes. this column is n bytes.

If the length of value < n If the length of value < n then no


then blanks are added to blanks are added and specified
make it n bytes bytes used by the value is
occupied.
 Constraints are the certain types of
restrictions on the data values that an
attribute can have.

 They are used to ensure correctness of data.

 However, it is not mandatory to define


constraints for each attribute of a table
PRIMARY KEY UNIQUE
Ensures that no two rows have the Ensures that no two rows have the
same value in the primary key same value in the specified
column
Columns that is set as primary key Column that is unique may or may
must also be unique not be a primary key
Only one primary key constraint Multiple UNIQUE constraints can
can be set on a table be defined on a table
Primary key constraint ensures UNIQUE constraint when applied to
that there cannot be null value in columns ensures that there cannot
specified column exist more than one NULL value in
OR the column
Primary key does not allow null OR
values UNIQUE allows null values
There can exist only one column There can exist multiple columns
or combination of columns with with UNIQUE constraints in a table
PRIMARY KEY constraint
 A DBMS can manage multiple databases on
one computer.
 Therefore, we need to select the database
that we want to use.

 To know the names of existing databases, we


use the statement :
 SHOW DATABASES;
 From the listed databases, we can select the
database to be used.

 USE databasename;
 To know the list of tables within a database.

 SHOW TABLES;
 To create a database, we use the CREATE
DATABASE statement:

 CREATE DATABASE databasename;


 To delete a database, we use the DROP
DATABASE statement:

 DROP DATABASE databasename;

Note: Using the DROP statement to remove a database will


ultimately remove all the tables within it
 After creating a database, we need to define
relations in this database and specify attributes
for each relation along with data type and
constraint (if any) for each attribute. This is
done using the CREATE TABLE statement.

 CREATE TABLE tablename (attributename1 datatype constraint,


attributename2 datatype constraint, ……………………….
attributenameN datatype constraint);
 The number of columns in a table defines the
degree of that relation, which is denoted by
N.
 Attribute name specifies the name of the
column in the table.
 Datatype specifies the type of data that an
attribute can hold.
 Constraint indicates the restrictions imposed
on the values of an attribute.
 By default, each attribute can take NULL
values except for the primary key
 CREATE TABLE STUDENT
 (RollNumber INT,
 SName VARCHAR(20),
 SDateofBirth DATE,
 GUID CHAR (12),
 PRIMARY KEY (RollNumber));
 “,” is used to separate two attributes

 each statement terminates with a semi-colon


(;) and is used to run/execute the command.

 The arrow (->) is an interactive continuation


prompt. If we enter an unfinished statement,
the SQL shell will wait for us to enter the rest
of the statement.
 We can view the structure of an already
created table using the DESCRIBE statement
or DESC statement.

 DESC tablename;
 Is used to change or alter the structure
(schema) of the table

 Is used to add/remove an attribute or to


modify the datatype of an existing attribute
or to add constraint in attribute.
 Uses ADD,DROP,MODIFY clauses
 ALTER TABLE Student
ADD PRIMARY KEY (R_No);
 ALTER TABLE Student
ADD PRIMARY KEY (FirstName,LastName);
 ALTER TABLE table_name
ADD FOREIGN KEY(attri name) REFERENCES referenced_tbl_name (attr name);

ALTER TABLE STUDENT


ADD FOREIGN KEY(guid) REFERENCES Guardian (guid);
 ALTER TABLE table_name
ADD UNIQUE (attribute name);

 ALTER TABLE Guardian


ADD UNIQUE (GPhone);
 ALTER TABLE table_name
ADD attribute name DATATYPE;

 ALTER TABLE Guardian


ADD income INT;
ALTER TABLE table_name
MODIFY attribute DATATYPE;

ALTER TABLE student


MODIFY Address VARCHAR(40);
ALTER TABLE table_name
MODIFY attribute DATATYPE NOT NULL;

ALTER TABLE STUDENT


MODIFY SName VARCHAR(20) NOT NULL;
ALTER TABLE table_name
MODIFY attribute DATATYPE DEFAULT default_value;

ALTER TABLE STUDENT


MODIFY SName VARCHAR(20) DEFAULT ‘ ‘;
 ALTER TABLE table_name
DROP attribute;

ALTER TABLE Guardian DROP income;


 ALTER TABLE table_name
DROP PRIMARY KEY;

ALTER TABLE Guardian


DROP PRIMARY KEY;
 We can use a DROP statement to remove a
database or a table permanently from the
system.
 However, one should be very cautious while
using this statement as it cannot be undone.

 DROP TABLE table_name;

Note: Using the DROP statement to remove a table will ultimately


remove all the records within it
In your TERM-2 curriculum, there are only DDL and DML
commands
 DDL – Data Definition Language

 DML- Data Manipulation Language

 DCL- Data Control Language

 TCL – Transaction Control Language


 DDL is used to define or modify the structure
of database objects e.g. tables, views,
indexes

 DDL commands are:


 CREATE TABLE
 ALTER TABLE
 DROP TABLE
 DML is used to manipulate the data in
database objects
 DML commands are:
SELECT
INSERT
UPDATE
DELETE
• is used to select data from a database.

• The data returned is stored in a result table,


called the result-set.
 Retrieve selected columns
 Renaming of columns (column alias)
 Column expression
SELECT Ename AS Name, Salary*12 AS 'Annual Income’ FROM EMPLOYEE;
If an aliased column name has space as in the case of Annual Income, it should be enclosed in quotes as 'Annual Income

 Distinct Clause
SELECT DISTINCT DeptId FROM EMPLOYEE;

 WHERE Clause
 Membership operator IN
 ORDER BY Clause
 Handling NULL Values
 Substring pattern matching
 Relational operators (<=,< , >, >=, =, !=) -
can be used to specify such conditions.

 Logical operators AND, OR, and NOT are


used to combine multiple conditions
To select data from the specified columns
SELECT column1, column2, ...
FROM table_name;

Here, column1, column2, ... are the field names of the table you want to select
data from.

To select data from all columns


SELECT * FROM table_name;
The following SQL statement selects the
"CustomerName" and "City" columns from the
"Customers" table:
Example
SELECT CustomerName, City FROM Customers;
The following SQL statement selects all the
columns from the "Customers" table:

Example
SELECT * FROM Customers;
is used to return only distinct (different) values.

Inside a table, a column often contains many duplicate


values; and sometimes you only want to list the different
(distinct) values.

SELECT DISTINCT Syntax to get distinct combination of column1 and column2


SELECT DISTINCT column1, column2
FROM table_name;
The following SQL statement selects ALL
(including the duplicates) values from the
"Country" column in the "Customers" table:
Example
SELECT Country FROM Customers;
The following SQL statement selects only the
DISTINCT values from the "Country" column in the
"Customers" table:
Example

SELECT DISTINCT Country FROM Customers;


The WHERE clause is used to filter records.
The WHERE clause is used to extract only those
records that fulfill a specified condition.

WHERE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition;
The following SQL statement selects all the
customers from the country "Mexico", in the
"Customers" table:
Example
SELECT * FROM Customers
WHERE Country='Mexico';
Operator Description

= Equal

> Greater than

< Less than

>= Greater than or equal

<= Less than or equal

<> Not equal. Note: In some versions of SQL this operator


may be written as !=
BETWEEN , NOT Between a certain range
BETWEEN
LIKE ,NOT LIKE Search for a pattern (uses 2 wild cards - % and
underscore)
IN, NOT IN To specify multiple possible values for a column

IS NULL , To retrieve the records with null values in the specified


IS NOT NULL column
The WHERE clause can be combined with AND, OR, and NOT
operators.
The AND and OR operators are used to filter records based
on more than one condition:
 The AND operator displays a record if all the conditions
separated by AND are TRUE.
 The OR operator displays a record if any of the conditions
separated by OR is TRUE.
 The NOT operator displays a record if the condition(s) is

NOT TRUE.
The following SQL statement selects all fields
from "Customers" where country is
"Germany" AND city is "Berlin":
Example:
SELECT * FROM Customers
WHERE Country='Germany' AND City='Berlin';
The following SQL statement selects all fields
from "Customers" where city is "Berlin" OR
"München":
Example
SELECT * FROM Customers
WHERE City='Berlin' OR City='München';
The following SQL statement selects all fields
from "Customers" where country is NOT
"Germany":
Example
SELECT * FROM Customers
WHERE NOT Country='Germany';
The following SQL statement selects all fields from
"Customers" where country is "Germany" AND city must
be "Berlin" OR "München" (use parenthesis to form
complex expressions):
Example
SELECT * FROM Customers
WHERE Country='Germany' AND (City='Berlin' OR
City='München');
The ORDER BY keyword is used to sort the result-
set in ascending or descending order.
The ORDER BY keyword sorts the records in
ascending order by default. To sort the records in
descending order, use the DESC keyword.
ORDER BY Syntax

SELECT column1, column2, ...


FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
The following SQL statement selects all customers from
the "Customers" table, sorted by the "Country" column:
Example
SELECT * FROM Customers
ORDER BY Country;
The following SQL statement selects all
customers from the "Customers" table,
sorted DESCENDING by the "Country" column:
Example
SELECT * FROM Customers
ORDER BY Country DESC;
The following SQL statement selects all customers from the
"Customers" table, sorted by the "Country" and the
"CustomerName" column.

This means that it orders by Country, but if some rows have


the same Country, it orders them by CustomerName:

Example
SELECT * FROM Customers
ORDER BY Country, CustomerName;
The following SQL statement selects all
customers from the "Customers" table, sorted
ascending by the "Country" and descending by
the "CustomerName" column:
Example
SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;
 groups rows that have the same values into summary rows,
like "find the number of customers in each country".
 is often used with aggregate functions (COUNT, MAX, MIN,
SUM, AVG) to group the result-set by one or more
columns.
GROUP BY Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
The following SQL statement lists the number of
customers in each country:
Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country;
The HAVING clause was added to SQL because the
WHERE keyword could not be used with aggregate
functions.
HAVING Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
The following SQL statement lists the number of
customers in each country. Only include countries
with more than 5 customers:

Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5;
HAVING clause WHERE clause
1. The HAVING clause is used in 1. The WHERE clause is used in
database systems to fetch the database systems to fetch the
data/values from the groups data/values from the tables
according to the given condition. according to the given condition.
2. The HAVING clause is always 2. The WHERE clause can be
executed with the GROUP BY executed without the GROUP BY
clause. clause.
3. The HAVING clause can include 3. We cannot use the SQL
SQL aggregate functions in a query aggregate function with WHERE
or statement. clause in statements.
4. We can only use SELECT 4. Whereas, we can easily use
statement with HAVING clause for WHERE clause with UPDATE,
filtering the records. DELETE, and SELECT statements.
5. The HAVING clause is used in 5. The WHERE clause is always
SQL queries after the GROUP BY used before the GROUP BY clause
clause. in SQL queries.
6. It is used to filter groups. 6. It is used to filter the single record
of the table.
 is used to insert new records in a table.

 INSERT INTO tablename


VALUES(value 1, value 2,....);

Here, value 1 corresponds to attribute 1,


value 2 corresponds to attribute 2 and so on.

Note that we need not to specify attribute names in the


insert statement if there are exactly the same numbers of
values in the INSERT statement as the total number of
attributes in the table.
Caution: While populating records in a table with foreign
key, ensure that records in referenced tables are already
populated
 is used to insert new records in a table.

 INSERT INTO tablename


VALUES (value 1, value 2,....);

Here, value 1 corresponds to attribute 1,


value 2 corresponds to attribute 2 and so on.
e.g.
INSERT INTO Guardian VALUES (44, 'Amit Ahuja’, 5711492685,
'G-35,Ashok vihar, Delhi' );
 INSERT INTO tablename
(column1, column2, ...) VALUES (value 1, value 2,....);

Here, value 1 corresponds to column 1,


value 2 corresponds to column 2 and so on.
e.g.
INSERT INTO Guardian (GUID, GName, GAddress) VALUES (44, 'Amit Ahuja’, 'G-
35,Ashok vihar, Delhi' );
 We may need to make changes in the value(s)
of one or more columns of existing records in
a table.
 For example, we may require some changes in address, phone
number or spelling of name, etc.
 The UPDATE statement is used to make such
modifications in existing data.
 UPDATE table_name
SET attribute1 = value1,
attribute2 = value2, ...
WHERE condition;
 DELETE statement is used to delete/remove
one or more records from a table.

 DELETE FROM table_name WHERE condition;


 Aggregate functions are also called Multiple
Row functions.

 These functions work on a set of records as a


whole and return a single value for each
column of the records on which the function
is applied.
 1. It operates on groups of rows.

 2. It returns one result for a group of rows.


 3. It can be used in the select clause only.

 4. Max(), Min(), Avg(), Sum(), Count() and


Count(*) are examples of multiple row functions.

 5. These functions ignore null values present in


the column.
 It groups the rows together that contains the
same values in a specified column.

 We can use the aggregate functions (COUNT,


MAX, MIN, AVG and SUM) to work on the
grouped values. (ignores null values)

 HAVING Clause in SQL is used to specify


conditions on the rows with Group By clause
 Cartesian product operation combines tuples
from two relations.

 The degree of the resulting relation is


calculated as the sum of the degrees of both
the relations under consideration. The
cardinality of the resulting relation is
calculated as the product of the cardinality of
relations on which cartesian product is
applied.
 SELECT * FROM emp,department;
 Joining of two tables based on equality
condition.

 SELECT * FROM Dance, Music


WHERE Dance.Name = Music.Name;

 SELECT * FROM DANCE D, MUSIC M


WHERE D.Name = M.Name;
 a) Using condition in where clause

 SELECT * FROM UNIFORM U, COST C


 WHERE U.UCode = C.UCode;
 b) Explicit use of JOIN clause

 SELECT * FROM Uniform U JOIN cost C


ON U.Ucode=C.Ucode;
 Natural join is an equi join which has only
one copy of the column columns of the
tables.

 c) Explicit use of NATURAL JOIN clause

 SELECT * FROM UNIFORM NATURAL JOIN


COST;
Scode SubjectName NumberOfS AvgMarks ExamDate
tudents
083 Computer Sc 67 95 22-Mar-2014

301 English 110 85 01-Mar-2014

041 Maths 110 80 20-Mar-2014

042 Physics 100 90 05-Mar-2014

043 Chemistry 100 85 11-Mar-2014


•To display the name of all Subjects in descending order of their
subject codes.

•To display Average of AvgMarks for each number of students


groupings.
(As shown in column NumberOfStudents 67, 110, 100)

•To display the content of the EXAM table in alphabetic order of


SubjectName whose exam date is on or after 20-Mar-2014.

• To display Subjectname and NumberofStudents from the table


EXAM.

• To display NumberofStudents whose avgMarks in the range 90 to


250

You might also like