DBMS sql
DBMS sql
PRASHANT TOMAR
Simple Queries in SQL
• SQL stands for Structured Query Language, and it is used to communicate with
the Database. This is a standard language used to perform tasks such as retrieval,
updation, insertion and deletion of data from a database.
• Structured Query Language (SQL) is a domain-specific language used in
programming and designed for managing data held in a relational database
management system (RDBMS), or for stream processing in a relational data
stream management system (RDSMS). It is particularly useful in handling
structured data where there are relations between different entities/variables of
the data.
• All the SQL statements start with any of the keywords like SELECT, INSERT,
UPDATE, DELETE, ALTER, DROP, CREATE, USE, SHOW and all the statements end
with a semicolon (;).
• The most important point to be noted here is that SQL is case insensitive, which
means SELECT and select have same meaning in SQL statements. Whereas, SQL
makes difference in table names. So, if you are working with SQL, then you need
to give table names as they exist in the database.
• Creating a basic table involves naming the table and defining its columns and
each column's data type. The SQL CREATE TABLE statement is used to create a
new table.
CREATE TABLE table_name
(
column1 datatype [ NULL | NOT NULL ],
column2 datatype [ NULL | NOT NULL ],
...
PRIMARY KEY( one columns)
);
• For example:
CREATE TABLE CUSTOMERS
(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) NULL,
SALARY DECIMAL (18, 2) NULL,
PRIMARY KEY (ID)
);
• In a database, a view is the result set of a stored query on the data, which the
database users can query just as they would in a persistent database collection
object. This pre-established query command is kept in the database dictionary.
• We can create a view by selecting fields from one or more tables present in the
database. A View can either have all the rows of a table or specific rows based on
certain condition.
• Views, which are a type of virtual tables allow users to do the following −
• Structure data in a way that users or classes of users find natural or intuitive.
• Restrict access to the data in such a way that a user can see and (sometimes)
• Summarize data from various tables which can be used to generate reports.
• Views can provide advantages over tables:
• Views can represent a subset of the data contained in a table. Consequently, a view can
limit the degree of exposure of the underlying tables to the outer world: a given user may
have permission to query the view, while denied access to the rest of the base table.
• Views can join and simplify multiple tables into a single virtual table.
• Views can act as aggregated tables, where the database engine aggregates data (sum,
average, etc.) and presents the calculated results as part of the data.
• Views can hide the complexity of data. For example, a view could appear as Sales2000 or
Sales2001, transparently partitioning the actual underlying table.
• Views take very little space to store; the database contains only the definition of a view, not
a copy of all the data that it presents.
• Depending on the SQL engine used, views can provide extra security.
);
• CHECK:
This constraint is used for specifying range of values for a particular column of a
table. When this constraint is being set on a column, it ensures that the specified
column must have the value falling in the specified range.
• In the above example we have set the check constraint on ROLL_NO column of
STUDENT table. Now, the ROLL_NO field must have the value greater than 1000.
• PRIMARY KEY:
Primary key uniquely identifies each record in a table. It must have unique values
and cannot contain nulls. In the below example the ROLL_NO field is marked as
primary key, that means the ROLL_NO field cannot have duplicate and null values.
Let’s create After triggers. First of all, let’s create a table and insert some
sample data. Then, on this table, I will be attaching several triggers.
CREATE TRIGGER <Schema_Name>.<Trigger_Name, sysname, Trigger_Name>
AS
BEGIN
END
GO
-- Trigger on an INSERT, UPDATE, or DELETE statement to a table or view (DML Trigger) SQL Server Syntax
ON { table | view }
AS
{ sql_statement [ ; ] [ ,...n ] | EXTERNAL NAME <method specifier [ ; ] > }
<dml_trigger_option> ::=
[ ENCRYPTION ]
[ EXECUTE AS Clause ]
<method_specifier> ::=
assembly_name.class_name.method_name
CREATE TRIGGER trg_AfterInsert ON [dbo].[Employee_Test]
FOR INSERT
AS
declare @empid int;
declare @empname varchar(100);
declare @empsal decimal(10,2);
declare @audit_action varchar(100);
select @empid = i.Emp_ID from inserted i;
select @empname = i.Emp_Name from inserted i;
select @empsal = i.Emp_Sal from inserted i;
set @audit_action = 'Inserted Record -- After Insert Trigger.';
• These kinds of triggers fire before the execution of an action query that can only be
DML statements like Insert, Update and Delete but after the execution of that query.
The table data will not be affected, in other words if you want to insert or update the
data of the table then you need to write it in the trigger using "inserted" or "deleted"
virtual tables.
CREATE TRIGGER [schema_name.] trigger_name
ON {table_name | view_name }
INSTEAD OF {[INSERT] [,] [UPDATE] [,] [DELETE] }
AS
{sql_statements}
• First, specify the name of the trigger and optionally the name of the schema to which
the trigger belongs in the CREATE TRIGGER clause.
• Second, specify the name of the table or view which the trigger associated with.
• Third, specify an event such as INSERT, DELETE, or UPDATE which the trigger will fire in
the INSTEAD OF clause. The trigger may be called to respond to one or multiple events.
• Fourth, place the trigger body after the AS keyword. A trigger’s body may consist of one
or more Transact-SQL statements.
• A typical example of using an INSTEAD OF trigger is to override an insert, update,
or delete operation on a view.
• Create View:
• Create connection
• Create statement
• Execute queries
• Close connection
Register the driver class
import java.sql.* ; // for standard JDBC programs
import java.math.* ; // for BigDecimal and BigInteger support
• The most common approach to register a driver is to use Java's Class.forName() method, to dynamically
load the driver's class file into memory, which automatically registers it. This method is preferable
because it allows you to make the driver registration configurable and portable.
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
Create the connection object
• You should use the registerDriver() method if you are using a non-JDK compliant
JVM, such as the one provided by Microsoft.
try {
Driver myDriver = new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver( myDriver );
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
import java.sql.*;
class OracleCon{
public static void main(String args[]){
try{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");
//step2 create the connection object
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
//step3 create the statement object
Statement stmt = con.createStatement();
//step4 execute query
ResultSet rs = stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));