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

Unit IV SQL

The document introduces SQL and relational database concepts, describing how data is organized into tables with rows and columns and can be queried using SQL commands. It explains key SQL elements like schemas, relations, attributes, tuples, queries, joins, and aggregate functions that allow users to define, manipulate and analyze data in a relational database. Common SQL statements are also covered including creating tables, inserting rows, updating data, aggregating results, and selecting data through queries with filtering conditions.

Uploaded by

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

Unit IV SQL

The document introduces SQL and relational database concepts, describing how data is organized into tables with rows and columns and can be queried using SQL commands. It explains key SQL elements like schemas, relations, attributes, tuples, queries, joins, and aggregate functions that allow users to define, manipulate and analyze data in a relational database. Common SQL statements are also covered including creating tables, inserting rows, updating data, aggregating results, and selecting data through queries with filtering conditions.

Uploaded by

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

Unit IV

SQL
Introduction to Structured Query Language
(SQL)
• Data :- Raw facts and figures which are useful to an
organization. We cannot take decisions on the basis of data.

• Information:- Well processed data is called an information.


We can take decisions on the basis of information.

• Field: Set of characters that represents specific data element.

• Record: Collection of fields is called a record. A record can


have fields of different data types.
• Database: Collection of logically related data along with its
description is termed as database.

• Tuple: A row in a relation is called a tuple.

• Attribute: A column in a relation is called an attribute. It is also termed


as field or data item.

• Degree: Number of attributes in a relation is called degree of a relation.

• Cardinality: Number of tuples in a relation is called cardinality of a


relation.
• Primary Key: Primary key is a key that can uniquely
identifies the records/tuples in a relation. This key can
never be duplicated and NULL.

• Foreign Key: Foreign Key is a key that is defined as a


primary key in some other relation. This key is used to
enforce referential integrity in RDBMS.

• Candidate Key: Set of all attributes which can serve as a


primary key in a relation.
Structured Query Language

• The standard for relational database management systems


(RDBMS)

• RDBMS: A database management system that manages data as


a collection of tables in which all relationships are
represented by common values in related tables
• Specify syntax/semantics for data definition and
manipulation (DDL and DML)

• Define data structures and basic operations

• Enable portability of database definition and application


modules
Benefits of a Standardized Relational Language

• Reduced training costs


• Productivity
• Application portability
• Application longevity
SQL Environment
• Catalog
• A set of schemas that constitute the description of a database
• Schema
• The structure that contains descriptions of objects created by a
user (base tables, views, constraints)
• Data Definition Language (DDL)
• Commands that define a database, including creating, altering,
and dropping tables and establishing constraints
• Data Manipulation Language (DML)
• Commands that maintain and query a database
• Data Control Language (DCL)
• Commands that control a database, including administering
privileges and committing data
SQL Database Definition
• Data Definition Language (DDL)

Major CREATE statements:

• CREATE SCHEMA–defines a portion of the database


owned by a particular user.

• CREATE TABLE–defines a new table and its columns

• CREATE VIEW–defines a logical table from one or


more tables or views
Creating Table Structures

• Use one line per column (attribute) definition


• Use spaces to line up attribute characteristics and
constraints
• NOT NULL specification
Creating Table Structures (continued)

• Primary key attributes contain both a NOT NULL and a


UNIQUE specification

• RDBMS will automatically enforce referential integrity for


foreign keys

• Command sequence ends with semicolon


SQL Constraints
• NOT NULL constraint
• Ensures that column does not accept nulls
• UNIQUE constraint
• Ensures that all values in column are unique
• DEFAULT constraint
• Assigns value to attribute when a new row is added to
table
• CHECK constraint
• Validates data when attribute value is entered
SQL Indexes
• When primary key is declared, DBMS automatically creates
unique index
• Often need additional indexes
• Using CREATE INDEX command, SQL indexes can be
created on basis of any selected attribute
• Composite index
• Index based on two or more attributes
• Often used to prevent data duplication
Data Manipulation Commands

• Adding table rows


• Saving table changes
• Listing table rows
• Updating table rows
• Restoring table contents
• Deleting table rows
• Inserting table rows with a select subquery
Adding Table Rows

• INSERT
Used to enter data into table
Syntax:
INSERT INTO table_name
VALUES (value1, value2, … , valuen);
Adding Table Rows (continued)

• When entering values, notice that:


• Row contents are entered between parentheses - ( )
• Character and date values are entered between apostrophes
‘DBMS’, ‘2019-08-01’
• Numerical entries are not enclosed in apostrophes
• Attribute entries are separated by commas
(‘dbms’, ‘nmims’, 2019)
• A value is required for each column
• Use NULL for unknown values
Saving Table Changes
• Changes made to table contents are not physically saved on
disk until, one of the following occurs:
• Database is closed
• Program is closed
• COMMIT command is used
Syntax:
• COMMIT [WORK];
• Will permanently save any changes made to any table in the database
Listing Table Rows
SELECT
Used to list contents of table
Syntax:
• SELECT columnlist
FROM tablename;
• Columnlist represents one or more attributes, separated
by commas
• Asterisk can be used as wildcard character to list all
attributes ( select * from table_name;)
Updating Table Rows
Update
• Modify data in a table
• Syntax:
UPDATE tablename
SET columnname = expression [columname = expression]
[WHERE conditionlist];
• If more than one attribute is to be updated in row, separate
corrections with commas
Restoring Table Contents
• ROLLBACK
• Used to restore database to its previous condition
• Only applicable if COMMIT command has not been used to
permanently store changes in database
Syntax:
• ROLLBACK;
• COMMIT and ROLLBACK only work with data
manipulation commands that are used to add, modify, or
delete table rows
Deleting Table Rows

DELETE
• Deletes a table row
Syntax:
DELETE FROM tablename
[WHERE conditionlist ];
WHERE condition is optional
Inserting Table Rows with a Select Subquery

INSERT
• Inserts multiple rows from another table (source)
• Uses SELECT subquery
• Query that is embedded (or nested) inside another query
• Executed first
Syntax:
• INSERT INTO tablename SELECT columnlist FROM
tablename;
Selecting Rows with Conditional Restrictions

Select partial table contents by placing restrictions on rows to


be included in output
• Add conditional restrictions to SELECT statement, using
WHERE clause
Syntax:
• SELECT columnlist
FROM tablelist
[ WHERE conditionlist ] ;
Special Operators

• BETWEEN
• Used to check whether attribute value is within a range
• IS NULL
• Used to check whether attribute value is null
• LIKE
• Used to check whether attribute value matches given string
pattern
Special Operators (continued)

• IN
• Used to check whether attribute value matches any value within a
value list
• EXISTS
• Used to check if subquery returns any rows
Use of AGGREGATE functions in SQL.
Performing calculations on multiple rows of a single column
of a table and returning a value.
Create table with following attributes

Table name: - title


• Attributes
 Author_fname
 Author_lname
 Title
 Pages
 Released_year
 Stock_quantity
COUNT Function
• The COUNT function returns the total number of values in the
specified field. It works on both numeric and non-numeric data types. All
aggregate functions by default exclude nulls values before working
on the data.

• COUNT (*) is a special implementation of the COUNT function that


returns the count of all the rows in a specified table. COUNT (*) also
considers Nulls and duplicates.
mysql> select count(*) from books;
mysql> select count(*) author_fname from
books;
mysql> select count (distinct author_fname)
from books;
Distinct omits duplicate records from the results.
mysql> select count (distinct
author_fname, author_lname)
from books;
mysql> select count (title) from books;
mysql> select count (title) from books
where title like ‘% The’;

mysql> select count (title) from books


where title like ‘The %’;
mysql> select count(author_fname),
author_lname
from books
group by author_lname;
mysql> select min (released_year) from books;
mysql> select max (released_year) from books;
mysql> select min(pages) As smallbook from books;
mysql> select SUM (pages) from books;
mysql> select SUM (stock_quantity) from books;
AVG The AVG() aggregate function
calculates the average of non-NULL
values in a set.
mysql> select AVG
(stock_quantity)
from books;
mysql> select count (title), released_year
from books
Group by released_year;
mysql> select max(s_quantity) As Max_avail from books;
mysql> select title from books where
(pages<100) group by title;
Use of Logical and Relational Operators in
SQL.
Select title, released_year from books
where
released_year=‘2018’;
Select title, released_year

from books

where
released_year !=‘2018’;
Select title, released_year

from books

where

released_year>2018;
Select title, released_year

from books

where

released_year>=2018;
mysql>select 99>1 mysql> select 99<1;
+------+
+------+ | 99<1 |
| 99>1 | +------+
+------+ | 0|
| 1| +------+
+------+
1 row in set (0.00 sec)
1 row in set (0.00 sec)
Exercise:

SELECT * FROM table_name

WHERE
condition1
AND
condition2
AND ...conditionN;
Exercise:

SELECT * FROM
table_name
WHERE
condition1
OR condition2
OR... conditionN;
Exercise:
SELECT * FROM

table_name WHERE

condition1 AND

(condition2 OR condition3);
SELECT attribute1,attribute2, attribute3

FROM tablename

WHERE attribute3

NOT BETWEEN AND ;


SELECT * FROM books
WHERE pages
BETWEEN 50 AND 100
SELECT cust_code, cust_name, cust_city, cust_country, grade

FROM customer

WHERE

NOT cust_country = 'India'

AND

NOT cust_city = 'London'

AND

NOT grade = 1;
SELECT

Attributes

FROM

Table_name

WHERE NOT (attr1 = '' OR attr2 = '') AND attr3 and attr < ;
SELECT * FROM books
WHERE EXISTS
(SELECT pages FROM books WHERE Pages > 50);
SELECT * FROM title

WHERE Pages > SOME (SELECT Pages


FROM title WHERE Pages > 20);

TRUE if any of the subquery values


meet the condition
SELECT * FROM title
WHERE Pages >
ANY
(SELECT Pages FROM title WHERE Pages > 50);

TRUE if any of the subquery values meet


the condition
Set operators & Join/s Implementation in
SQL
• mysql> create table a (roll_no int, name char(20), branch char(20));
Query OK, 0 rows affected (0.08 sec)

mysql> desc a;
+---------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+----------+------+-----+---------+-------+
| roll_no | int(11) | YES | | NULL | |
| name | char(20) | YES | | NULL | |
| branch | char(20) | YES | | NULL | |
+---------+----------+------+-----+---------+-------+
3 rows in set (0.00 sec)
mysql> select * from a;
+---------+------+--------+
| roll_no | name | branch |
+---------+------+--------+
| 1 | abc | comp |
| 2 | abcd | comp |
| 3 | bcd | IT |
| 4 | cd | IT |
+---------+------+--------+
4 rows in set (0.00 sec)
mysql> create table c(roll_no int, name char(20), branch char(20));
Query OK, 0 rows affected (0.34 sec)

mysql> select * from c;


+---------+------+--------+
| roll_no | name | branch |
+---------+------+--------+
| 1 | abc | mech |
| 2 | bc | civil |
| 3 | bcd | comp |
| 1 | abc | comp |
+---------+------+--------+
4 rows in set (0.00 sec)
mysql> select * from a UNION all select * from c;
+---------+------+--------+
| roll_no | name | branch |
+---------+------+--------+
| 1 | abc | comp |
| 2 | abcd | comp |
| 3 | bcd | IT |
| 4 | cd | IT |
| 1 | abc | mech |
| 2 | bc | civil |
| 3 | bcd | comp |
| 1 | abc | comp |
+---------+------+--------+
8 rows in set (0.00 sec)
SQL LEFT JOIN

The SQL LEFT JOIN (specified with the keywords LEFT JOIN and ON)
joins two tables and fetches all matching rows of two tables for which
the SQL-expression is true,
plus rows from the first table that do not match any row in the second table.
mysql> select c.name,c.branch from c right join
a on a.roll_no=c.roll_no;
Cross join

The SQL CROSS JOIN produces a result set which is the number of
rows in the first table multiplied by the number of rows in the second
table
+---------+------+--------+---------+------+--------+
| roll_no | name | branch | roll_no | name | branch |
+---------+------+--------+---------+------+--------+
mysql> select * from a cross | 1 | abc | comp | 1 | abc | mech |
join c; | 2 | abcd | comp | 1 | abc | mech |
| 3 | bcd | IT | 1 | abc | mech |
| 4 | cd | IT | 1 | abc | mech |
| 1 | abc | comp | 2 | bc | civil |
| 2 | abcd | comp | 2 | bc | civil |
| 3 | bcd | IT | 2 | bc | civil |
| 4 | cd | IT | 2 | bc | civil |
| 1 | abc | comp | 3 | bcd | comp |
| 2 | abcd | comp | 3 | bcd | comp |
| 3 | bcd | IT | 3 | bcd | comp |
| 4 | cd | IT | 3 | bcd | comp |
| 1 | abc | comp | 1 | abc | comp |
| 2 | abcd | comp | 1 | abc | comp |
| 3 | bcd | IT | 1 | abc | comp |
| 4 | cd | IT | 1 | abc | comp |
| 1 | abc | comp | 3 | bcd | IT |
| 2 | abcd | comp | 3 | bcd | IT |
| 3 | bcd | IT | 3 | bcd | IT |
| 4 | cd | IT | 3 | bcd | IT |
+---------+------+--------+---------+------+--------+
20 rows in set (0.00 sec)
Null Values

• The SQL NULL is the term used to represent a missing value.

• A NULL value in a table is a value in a field that appears to be blank.

• A field with a NULL value is a field with no value.

• It is very important to understand that a NULL value is different


than a zero value or a field that contains spaces.
SQL NOT NULL Constraint

• By default, a column can hold NULL values.

• The NOT NULL constraint enforces a column to NOT


accept NULL values.

• This enforces a field to always contain a value, which means


that you cannot insert a new record, or update a record
without adding a value to this field.
CREATE TABLE students ( NOT
NULL signifies
ID int NOT NULL, that column
should always
LastName varchar(50) NOT NULL, accept an
FirstName varchar(50) NOT NULL, explicit value of
the given data
Age int type.
);
SQL ensures that the "ID", "LastName", and "FirstName" columns
will NOT accept NULL values when the “students" table is created.
mysql> select * from a;
+---------+------+
| roll_no | name |
+---------+------+
| 1 | abcd |
| NULL | bcd |
+---------+------+
2 rows in set (0.08 sec)

mysql> select * from a where roll_no is not


null;
+---------+------+
| roll_no | name |
+---------+------+
| 1 | abcd |
+---------+------+
1 row in set (0.00 sec)
mysql> select * from a;
+---------+------+ mysql> select * from a where
| roll_no | name | roll_no is not null;
+---------+------+
+---------+------+ | roll_no|name|
| 1 | abcd | +---------+------+
| NULL | bcd | | 1 | abcd |
| 0 | ab |
| 0 | ab | +---------+------+
+---------+------+ 2 rows in set (0.00 sec)
3 rows in set (0.00 sec)
IS NULL()

The IS NULL command is used to test for empty values (NULL values).
mysql> select * from a; mysql> select roll_no *
+---------+------+ (isnull(roll_no)) from a;
| roll_no | name | +-----------------------------+
+---------+------+ | roll_no * (isnull(roll_no)) |
| 1 | abcd | +-----------------------------+
| NULL | bcd | | 0|
| 0 | ab | | NULL |
| NULL | dbms | | 0|
+---------+------+ | NULL |
4 rows in set (0.00 sec) +-----------------------------+
4 rows in set (0.00 sec)
Views
• A database view is a virtual table or logical table which is defined as
a SQL SELECT query with joins.

• Because a database view is similar to a database table, which consists


of rows and columns, so you can query data against it.

• Most database management systems, including MySQL, allow you


to update data in the underlying tables through the database view
with some prerequisites.
• A database view is dynamic because it is not related to the physical
schema.

• The database system stores views as a SQL SELECT statement with


joins. When the data of the tables changes, the view reflects that
changes as well.
Advantages of database view
• A database view allows you to simplify complex queries: A
database view is defined by an SQL statement that
associates with many underlying tables.

• You can use database view to hide the complexity of


underlying tables to the end-users and external applications.

• Through a database view, you only have to use simple SQL
statements instead of complex ones with many joins.
• A database view helps limit data access to specific users. You
may not want a subset of sensitive data can be accessible
to all the users.

• You can use a database view to expose only non-sensitive


data to a specific group of users.
• A database view provides extra security layer. Security is a
vital part of any relational database management system.
The database view offers additional protection for a database
management system.

• The database view allows you to create the read-only view to


expose read-only data to specific users. Users can only
retrieve data in read-only view but cannot update it.
CREATE VIEW inventory AS

SELECT column1, column2, ...

FROM table_name

WHERE condition;
To view the virtual table

SELECT * FROM [inventory];


Disadvantages of the Database Views
???
•Performance: Querying data from a database
view can be slow especially if the view is created
based on other views.
•Tables dependency: You can create a view based on
underlying tables of the database. Whenever you change
the structure of these tables that view associated with, you
have to change the view as well.
Stored procedure

A Stored procedure is a procedure that is stored in a database. It has a


name, parameter list and sql statements. The first part of
the SQL statement that creates a stored procedure is the words
"CREATE PROCEDURE".
Stored Procedures & Functions

Views

Way to register queries inside DBMS

Stored Procedures & Functions

Way to register code inside DBMS


Advantages

• Reusability: do not need to write the code again and again.


• Programming language-like environment
Assignment, Loop, For, IF statements
• Call it whenever needed
From select statement, another procedure, or another function
CREATE PROCEDURE procedure_name
AS
sql_statement
EXEC procedure_name;
DELIMITER // For example:
• mysql> DELIMITER // The delimiter is the character or string of
characters that you'll use to tell the mysql client that you've
finished typing in an SQL statement.
• For ages, the delimiter has always been a semicolon. That causes a
problem because, in a stored procedure, one can have many
statements, and every one must end with a semicolon.
mysql> create procedure p3() select * from a;//
Query OK, 0 rows affected (0.07 sec)

mysql> call p3();


+---------+------+
| roll_no | name |
+---------+------+
| 1 | abcd |
| NULL | bcd |
| 0 | ab |
| NULL | dbms |
+---------+------+
4 rows in set (0.06 sec)
Query OK, 0 rows affected (0.08 sec)
mysql>
• The first part of the SQL statement that creates a stored procedure is
the words "CREATE PROCEDURE".
• The second part is the procedure name. The name of this new
procedure is p3.
• Procedure Names are not case sensitive, so 'p1' and 'P1' are the same
name.
• You cannot use two procedures with the same name in the same database.
That would be overloading. Some DBMSs allow overloading. MySQL
doesn't.
You can make a procedure that contains pretty well anything,
including INSERT, UPDATE, DELETE, SELECT, DROP,
CREATE, REPLACE, and so on.
MySQL Stored Procedures
• Parameter type
• IN
• OUT
• INOUT
• The procedures may return one or more data sets as OUT
parameters.
IN – is the default mode. When you define an IN parameter in a stored procedure,
the calling program has to pass an argument to the stored procedure.

It means that even the value of the IN parameter is changed inside the stored
procedure, its original value is retained after the stored procedure ends. In other
words, the stored procedure only works on the copy of the IN parameter.
OUT – the value of an OUT parameter can be changed inside the
stored procedure and its new value is passed back to the calling
program.
Stored procedure cannot access the initial value of
the OUT parameter when it starts.
INOUT – an INOUT parameter is a combination
of IN and OUT parameters. It means that the calling program may
pass the argument, and the stored procedure can modify
the INOUT parameter, and pass the new value back to the calling
program.
DELIMITER //
Example
CREATE PROCEDURE GetOffice
ByCountry
(IN countryName VARCHAR(255))
IN parameter in BEGIN
the GetOfficeByCountry
SELECT *
stored procedure that
selects offices located in a FROM offices
particular country. WHERE country = countryName;
END //
DELIMITER ;
mysql> create procedure dt() select Curdate();
Query OK, 0 rows affected (0.32 sec)

mysql> call dt;


+------------+
| Curdate() |
+------------+
| 2019-08-05 |
+------------+
1 row in set (0.05 sec)
Query OK, 0 rows affected (0.06 sec)
mysql> create procedure hi() select ('hello world');
Query OK, 0 rows affected (0.06 sec)

mysql> call hi;


+-------------+
| hello world |
+-------------+
| hello world |
+-------------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
CREATE PROCEDURE insert_into_table
( table_name VARCHAR, deptnumber NUMBER, deptname
VARCHAR, location VARCHAR)
IS
stmt_str VARCHAR(200);
BEGIN
stmt_str := 'INSERT INTO ' || table_name || ' values
(:deptno, :dname, :loc)';

EXECUTE IMMEDIATE stmt_str


USING
deptnumber, deptname, location;

END; /
SHOW ERRORS;
Using DROP procedure procedure_name you can drop the
procedure.
Debugging Complex SQL Queries – The General
Process
• Check on syntax and logic:
• The first basic step is investigating the SQL code.
• The different SQL statements like an update, insert, or delete
statements can be nested together.
• You need to work on the testing logic and separate the level of
nesting too.
• Now substitute representative values into correlated subqueries
for the automatic execution. These subsequent debugging steps
are able to handle only one query at a time.
• Check on SQL joins:
• Once you have resolved issues related to syntax or flow, the next
focus is joining logic.
• It is easy to run afoul of joins so we have to make sure that we are
not losing records accidentally.
• Check on Predicates:
• We have to restore the “where predicates” and run the query
again. In case, the query fails to run, there is clearly something
wrong with predicates.
• Read the code carefully that will help you to find errors certainly.
If you are still not able to spot errors then step back and restore a
few predicates at one time.
• Check on attributes:
• If joins and predicates both are correct, the next step is to focus
on attributes.
• We introduce multiple attributes together and you have to make
sure all attributes ensure the right results.
• Check on nesting queries: In the final step, put the nested queries
together from the initial SQL statement. We should test the SQL
statements thoroughly to make sure that it runs correctly.
Things to Consider when Writing Complex SQL Queries

• Focus on the final output


• Understand the database relationships
• Good understanding of database relationships among different
fields.
• Break the query into manageable parts.
• Aggregate the result sets
• This is the time to aggregate the different result sets with Group By statement.
You may also use multiple aggregate functions on the basis of requirements like
COUNT, MAX, MIN, SUM, or AVG etc.
• Make the query easy to read
Embedded SQL

Embedded SQL is a method of combining the computing power of a programming


language and the database manipulation capabilities of SQL.

• C language (Pro*C in Oracle)


• COBOL (Pro*COBOL in Oracle, Cobol-IT in PostgreSQL)
• SQLJ
• Java language
• Programming language called host language
Accessing SQL From a Programming Language

• API (Application-program Interface) for a program to interact with a


database server
• Application makes calls to
• Connect with the database server
• Send SQL commands to the database server
• Fetch tuples of result one-by-one into program variables
• Various tools:
• ODBC (Open Database Connectivity) works with C, C++, C#, and Visual
Basic. Other API’s such as ADO.NET sit on top of ODBC
• JDBC (Java Database Connectivity) works with Java
• Embedded SQL
ODBC
• Open Database Connectivity (ODBC) standard
• Standard for application program to communicate with a database server.
• Application program interface (API) to
• Open a connection with a database,
• Send queries and updates,
• Get back results.
• Applications such as GUI, spreadsheets, etc. can use ODBC
• API that database vendors can implement for their
system via ODBC driver
• Your program makes requests via the API
• Driver talks to the DBMS using SQL
• Available drivers:

• SQL Server, Access, FoxPro, Excel, dBase,


• Data source the database, its associated DBMS, operating
system, and network platform
• Driver manager intermediary between the application and
DBMS drivers
• Driver processes ODBC requests and submits SQL
statements to a data source
• Access any data from any application, regardless of which
DBMS is handling the data
• Insert a middle layer between an application and the
database management system

• Allow application programs to use SQL to access data from


any kinds of sources.
JDBC
• It is a Java API for communicating with database
systems supporting SQL.
• JDBC supports a variety of features for querying and
updating data, and for retrieving query results.
• JDBC also supports metadata retrieval, such as querying
about relations present in the database and the names and
types of relation attributes.
• Model for communicating with the database:
• Open a connection
• Create a “statement” object
• Execute queries using the Statement object to send queries and fetch results
• Exception mechanism to handle errors
Why Should We Use JDBC ?

• Before JDBC, ODBC API was the database API to connect and
execute the query with the database.
• ODBC API uses ODBC driver which is written in C language (i.e.
platform dependent and unsecured). That is why Java has defined its
own API (JDBC API) that uses JDBC drivers (written in Java language).
• We can use JDBC API to handle database using Java program and can
perform the following activities:
• Connect to the database
• Execute queries and update statements to the database
• Retrieve the result received from the database.
Basic steps to use a database in Java

1. Establish a connection
2. Create JDBC Statements
3. Execute SQL Statements
4. GET Result Set
5. Close connections

136
• (“oracle.jdbc.driver.OracleDriver”)

• Connection con = DriverManager.getConnection(……….)

• Statement stmt = con.createStatement() ;


• Creates a Statement object for sending SQL statements to the database.

• Close Connection
• stmt.close();
• con.close();
Dynamic SQL

• In dynamic SQL, query string can be taken as a parameter,


passed to DB
• Two steps:
• Prepare: compiles/optimizes the string
• Execute: executes the query
• Dynamic SQL enables you to write programs that reference
SQL statements whose full text is not known until runtime.

• Static SQL statements do not change from execution to


execution.
• Your program may accept user input that defines the SQL
statements to execute, or your program may need to complete
some processing work to determine the correct course of
action.

• In such cases, you should use dynamic SQL.

• These SQL statements may depend on user input, or they


may depend on processing work done by the program.
• Many types of applications need to use dynamic queries,
including:

• Applications that allow users to input or select query search or


sorting criteria at runtime.

• Applications that query a database where the data definitions of


tables are constantly changing.

• Applications that query a database where new tables are created often.
Q&A
What are the technical specifications of MySQL?

• MySQL has the following technical specifications -


• Flexible structure
• High performance
• Manageable and easy to use
• Replication and high availability
• Security and storage management
What is the difference between MySQL and SQL?
• SQL is known as the Structured Query Language. It is used
to interact with the database like MySQL. MySQL is a
database that stores various types of data and keeps it safe.
What is MySQL timestamp?

• MySQL timestamp is represented in readable format of


YYYY-MM-DD HH:MM:SS format.
What is REGEXP?

• REGEXP is a pattern match using a regular expression. A


Regular expression is a powerful way of specifying a pattern
for a sophisticated search.
SELECT

author_lname

FROM

books

WHERE

author_fname REGEXP '^(A|B|C)'

ORDER BY author_fname;
What is a View?

• A view is a virtual table which consists of a subset of data


contained in a table.
What is a stored procedure?

• Stored Procedure is a function consists of many SQL statement to


access the database system. Several SQL statements are
consolidated into a stored procedure and execute them
whenever and wherever required.
What is a constraint?
• Constraint can be used to specify the limit on the
data type of table.

• Constraint can be specified while creating or altering


the table statement. Sample of constraints are.
• NOT NULL.
• PRIMARY KEY.
• FOREIGN KEY etc.
What is Auto Increment?

• Auto increment keyword allows the user to create a unique


number to be generated when a new record is inserted
into the table.
What is Datawarehouse?
• Datawarehouse is a central repository of data from
multiple sources of information. Those data are
consolidated, transformed and made available for the
mining and online processing. Warehouse data have a
subset of data called Data Marts.
• What is SQL NOT NULL constraint?
NOT NULL constraint is used to ensure that the value in
the filed cannot be a NULL
What are aggregate functions in SQL?
SQL aggregate functions return a single value, calculated
from values in a column. Some of the aggregate functions in
SQL are as follows
• AVG() – This function returns the average value
• COUNT() – This function returns the number of rows
• MAX() – This function returns the largest value
• MIN() – This function returns the smallest value
• SUM() – This function returns the sum
What is an inconsistent dependency?

• Inconsistent dependency refers to the difficulty of accessing


particular data as the path to reach the data may be missing
or broken.

• Inconsistent dependency will leads users to search the data in


the wrong table which will afterward give the error as an output.

You might also like