Database SQL 065545
Database SQL 065545
SQL is required:
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
What is Database?
A database is an organized collection of data, so that it can be easily
accessed and managed.
You can organize data into tables, rows, columns, and index it to make it
easier to find relevant information. Database handlers create a database in such a
way that only one set of software program provides access of data to
all the users.
Modern databases are managed by the database management system (DBMS). SQL or
Structured Query Language is used to operate on the data stored in a database.
RDBMS Concepts
RDBMS stands for Relational Database Management System.
RDBMS is the basis for SQL, and for all modern database systems like MS SQL
Server, IBM DB2, Oracle, MySQL, and Microsoft Access.
A Relational database management system (RDBMS) is a database management
system (DBMS) that is based on the relational model as introduced by E. F. Codd.
What is a table?
The data in an RDBMS is stored in database objects which are called as
tables.
This table is basically a collection of related data entries and it consists
of numerous columns and rows.
"Table" is another term for "relation"
SQL Syntax
SQL follows some unique set of rules and guidelines called syntax. Here, we
are providing all the basic SQL syntax:
SQL is not case sensitive. Generally, SQL keywords are written in
uppercase.
SQL statements are dependent on text lines. We can place a single SQL
statement on one or multiple text lines.
You can perform most of the action in a database with SQL statements.
SQL depends on relational algebra and tuple relational calculus. ( It is a
non-procedural query language which is based on finding a number of tuple
variables also known as range variable for which predicate holds true. It
describes the desired information without giving a specific procedure for obtaining
that information.)
SQL statements are started with any of the SQL commands/keywords like SELECT,
INSERT, UPDATE, DELETE, ALTER, DROP etc. and the statement ends with a semicolon
(;).
An SQL developer must decide what type of data that will be stored inside
each column when creating a table. The data type is a guideline for SQL to
understand what type of data is expected inside of each column, and it also
identifies how SQL will interact with the stored data.
In MySQL there are three main data types: String / Text, Numeric, and Date
and time.
CHAR(size) A FIXED length string (can contain letters, numbers, and special
characters). The size parameter specifies the column length in characters -
can be from 0 to 255. Default is 1
VARCHAR(size) A VARIABLE length string (can contain letters, numbers, and
special characters). The size parameter specifies the maximum column length in
characters - can be from 0 to 65535
TINYTEXT Holds a string with a maximum length of 255 characters
TEXT(size) Holds a string with a maximum length of 65,535 bytes
MEDIUMTEXT Holds a string with a maximum length of 16,777,215 characters
LONGTEXT Holds a string with a maximum length of 4,294,967,295 characters
SQL Commands
SQL commands are mainly categorized into five categories as discussed below:
• DDL
• DML
• DRL
• DCL
• TCL
1)CREATE – is used to create the database or its objects (like table, index,
function, views, store procedure and triggers).
Example
CREATE DATABASE testDB;
ii.CREATE TABLE: The CREATE TABLE statement is used to create a table in SQL.
We know that a table comprises of rows and columns. So while creating tables we
have to provide all the information to SQL about the names of the columns,
type of data to be stored in columns, size of the data etc. Let us now dive into
details on how to use CREATE TABLE statement to create tables in SQL.
Syntax
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);
The column parameters specify the names of the columns of the table.
The datatype parameter specifies the type of data the column can hold (e.g.
varchar, integer, date, etc.).
The new table gets the same column definitions. All columns or specific
columns can be selected.
If you create a new table using an existing table, the new table will be
filled with the existing values from the old table.
Syntax
CREATE TABLE new_table_name AS
SELECT column1, column2,...
FROM existing_table_name
WHERE ....;
Syntax
DROP DATABASE databasename;
Note: Be careful before dropping a database. Deleting a database will result
in loss of complete information stored in the database!
Example
DROP DATABASE testDB;
Syntax
DROP TABLE table_name;
Note: Be careful before dropping a table. Deleting a table will result in
loss of complete information stored in the table!
Example
DROP TABLE Shippers;
Example
ALTER TABLE Customers
ADD Email varchar(255);
The following SQL deletes the "Email" column from the "Customers"
table:
Example
ALTER TABLE Customers
DROP COLUMN Email;
The TRUNCATE TABLE statement is used to delete the data inside a table
including all spaces allocated for the records are removed, but not the table
itself.
Syntax
TRUNCATE TABLE table_name;
B. If you are adding values for all the columns of the table, you do not need
to specify the column names in the SQL query. However, make sure the order of the
values is in the same order as the columns in the table. Here, the INSERT
INTO syntax would be as follows:
Note: Be careful when updating records in a table! Notice the WHERE clause in
the UPDATE statement. The WHERE clause specifies which record(s) that should be
updated. If you omit the WHERE clause, all records in the table will be
updated!
UPDATE Customers
SET ContactName = 'Alfred', City= 'Frankfurt'
WHERE CustomerID = 1;
UPDATE Customers
SET ContactName='Juan'
WHERE Country='Mexico';
DELETE Syntax
DELETE FROM table_name WHERE condition;
Note: Be careful when deleting records in a table! Notice the WHERE clause in
the DELETE statement. The WHERE clause specifies which record(s) should be
deleted. If you omit the WHERE clause, all records in the table will be
deleted!
Example
DELETE FROM Customers;
DROP statement: The DROP command removes a table from the database. All
the tables' rows, indexes and privileges will also be removed. No DML triggers
will be fired. The operation cannot be rolled back.
SELECT Syntax
Here, column1, column2, ... are the field names of the table you want to
select data from. If you want to select all the fields available in the table, use
the following syntax:
WHERE Syntax
Clause Description
The above command will alter the user details and will provide it access to
unlimited tablespace on system.
TCL
TCL is abbreviation of Transactional Control Language. It is used to manage
different transactions occurring within a database.
TCL commands can only use with DML commands like INSERT, DELETE and UPDATE
only.
These operations are automatically committed in the database that's why they
cannot be used while creating tables or dropping them.
Here are some commands that come under TCL:
Syntax:
COMMIT;
Example:
COMMIT;
ROLLBACK – Restores database to original state since the last COMMIT command
in transactions
Syntax:
ROLLBACK;
Example:
Syntax:
SAVEPOINT SAVEPOINT_NAME;
Types of Expression:
1) Boolean Expression: SQL Boolean Expressions are SQL expressions that only
return Boolean Datatype as a result. These expressions can be of two types −
Boolean Expressions that check for equality of two values using SQL
comparison operators. Here, equality of these values is a condition.
Boolean Expressions can also contain one value paired with an SQL
logical operator. In this case, the logic specified acts like a condition.
Syntax:
SELECT column1, column2, columnN
FROM table_name
WHERE BOOLEAN EXPRESSION;
Example:
SELECT * FROM CUSTOMERS WHERE SALARY = 10000;
Syntax
SELECT numerical_expression as OPERATION_NAME
FROM table_name
WHERE NUMERICAL EXPRESSION ;
Example:
1) SELECT (15 + 6) AS ADDITION
2) SELECT COUNT(*) AS "RECORDS" FROM CUSTOMERS;
3) SELECT SUM(column_name) FROM table_name WHERE condition;
4) SELECT COUNT(ProductID) FROM Products;
5) SELECT AVG(Price) FROM Products;
3) Date Expressions: Date Expressions are used to compare date related values
with current system date and time values.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE DATE EXPRESSION ;
Example:
1) SELECT CURRENT_TIMESTAMP;
2) SELECT DATE FROM ORDERS WHERE DATE < '2008/06/01';
3) SELECT * FROM Orders WHERE OrderDate='2008-11-11'
Executing Queries:
Statement objects allow you to execute basic SQL queries and retrieve the
results through the ResultSet class, which is described later.
To create a Statement instance, you call the createStatement() method on the
Connection object you have retrieved using one of the DriverManager.getConnection
() or DataSource.getConnection() methods described earlier.
Once you have a Statement instance, you can execute a SELECT query by calling
the executeQuery(String) method with the SQL you want to use.
To update data in the database, use the executeUpdate(String SQL) method.
This method returns the number of rows matched by the update statement, not the
number of rows that were modified.
If you do not know ahead of time whether the SQL statement will be a SELECT
or an UPDATE/INSERT, then you can use the execute(String SQL) method. This method
will return true if the SQL query was a SELECT, or false if it was an UPDATE,
INSERT, or DELETE statement. If the statement was a SELECT query, you can
retrieve the results by calling the getResultSet() method. If the statement
was an UPDATE, INSERT, or DELETE statement, you can retrieve the affected rows
count by calling getUpdateCount() on the Statement instance.
package com.java2novice.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MyExecuteMethod {
public static void main(String a[]){
Connection con = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.
getConnection("jdbc:oracle:thin:@<hostname>:<port num>:<DB name>"
,"user","password");
Statement stmt = con.createStatement();
//The query can be update query or can be select query
String query = "select * from emp";
boolean status = stmt.execute(query);
if(status){
//query is a select query.
ResultSet rs = stmt.getResultSet();
while(rs.next()){
System.out.println(rs.getString(1));
}
rs.close();
} else {
//query can be update or any query apart from select query
int count = stmt.getUpdateCount();
System.out.println("Total records updated: "+count);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try{
if(con != null) con.close();
} catch (Exception ex){}
}
}
}
Practice Session
1) Create table Person Having column personID, Name, DOB, Salary
create table person (
personID int,
Name varchar(255),
DOB date,
salary decimal
);
2) Add columns "Email_ID" in to table Person
ALTER TABLE person
Add Email_ID varchar(60);
3) Insert value 1, Edubridge, 19-02-1988, 1000.00, [email protected] into table
Person
4) write a query to update the name Edubridge with your name
SQL Server DBMS - SQL language (HDFC Bank - Saving acc, Credit acc, Loan acc)
MySQL Server DBMS - SQL language(HDFC - Saving acc, Current Acc, Credit card Acc)
Data/records
Table3 - statement
table1
rows/columns
data/records
Table2
Table3