0% found this document useful (0 votes)
57 views57 pages

SQL Programming

The document discusses various SQL concepts including: 1. SQL is used to retrieve, modify, update, insert or delete data from relational databases. It is case-insensitive. 2. SQL data types include string, numeric, and date/time types used to define column data. Common constraints ensure columns cannot be null, values are unique, or satisfy certain conditions. 3. Key SQL commands retrieve (select), add (insert), modify (update), or remove (delete) data. Joins combine data from multiple tables. Aggregate functions perform calculations on data sets.

Uploaded by

Mrinaal Malhotra
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
57 views57 pages

SQL Programming

The document discusses various SQL concepts including: 1. SQL is used to retrieve, modify, update, insert or delete data from relational databases. It is case-insensitive. 2. SQL data types include string, numeric, and date/time types used to define column data. Common constraints ensure columns cannot be null, values are unique, or satisfy certain conditions. 3. Key SQL commands retrieve (select), add (insert), modify (update), or remove (delete) data. Joins combine data from multiple tables. Aggregate functions perform calculations on data sets.

Uploaded by

Mrinaal Malhotra
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 57

Revision Class Unit - 2

Introduction to SQL
• SQL stands for structured query language.

• It is used to retrieve, modify, update, insert or deletion information from the


relational database.

• SQL is case- insensitive.


Terminology in SQL
ROLL_NO NAME ADDRESS PHONE AGE

1 RAM DELHI 9455697981 18

2 RAMESH GURGAON 9652431543 18

3 SUJIT ROHTAK 9156253131 19

4 SURESH DELHI 9156768971 20

• Attribute
• Tuple
• Degree
• Cardinality:
• Schema
SQL data types

• SQL data types define the type of data which can be stored in the columns of a
table.
Data types mainly classified into three categories for every database.
- String Data types
- Numeric data Types
- Data and time Data types

String Data types :


CHAR(size ) : fixed length string
VARCHAR(size): variable length string.
SQL DATA TYPES
Numeric Data Types:
INT(size) : used for integers.
Float(size, d): used for floating point numbers.

DateTime Data Type:


DATETIME(fsp): It is used to specify date and time combination. Its
format is YYYY-MM-DD hh:mm:ss.
SQL constraints
The following constraints are commonly used in SQL:
1. NOT NULL - Ensures that a column cannot have a NULL value
2. UNIQUE - Ensures that all values in a column are different
3. PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each row in a table
4. FOREIGN KEY - Prevents actions that would destroy links between tables
5. CHECK - Ensures that the values in a column satisfies a specific condition
6. DEFAULT - Sets a default value for a column if no value is specified
SQL commands
1.Data definition language (DDL) : It is used to define the schema. For creation or alteration of the relation. Certain
constraints are added so that the data added is as per the schema.
The types of constraints followed are:
i)Domain constraints
ii)Referential integrity
2. Data manipulation language (DML) : DML commands are used to retrieve the data from the relation. Mainly select
query is used for DML.
3. TCL: Transaction Control Language commands are used to manage transactions in the database. These are used to
manage the changes made by DML-statements
4. DCL: A Data Control Language is a syntax similar to a computer programming language used to control access to
data stored in a database (Authorization).
Examples of DCL commands :
•GRANT: allow specified users to perform specified tasks.
•REVOKE: cancel previously granted or denied permissions.
SQL Keys
1. Primary key : A column or columns is called primary key
(PK) that uniquely identifies each row in the table.
2. Foreign key: a foreign key in one table used to point primary key in
another table.
3. Composite key: A composite key is a combination of two or more
columns in a table that can be used to uniquely identify each row in
the table
4. Alternate/ Secondary key: The set of alternate keys which are
unique keys but not the primary key.
SQL commands
1. Create command: used to create a relational table.
• Example:
CREATE TABLE Employee  
(  
EmployeeID int,  
FirstName varchar(255),  
LastName varchar(255),  
Email varchar(255),  
AddressLine varchar(255),  
City varchar(255)  
);  
SQL commands
2. Select command: used to retrieve information from the table.
Example:
• Select * from employee;

3. UNIQUE/ DISTINCT statement is used to retrieve a unique or


distinct element from the table.
Example:
Select unique employee_dept from employee;
SQL commands
4. COUNT(): used to get the number of rows in the table
Example:
Select count(employee_dept) from employee;

Count() can also be used with where clause:


Select count(*) from employee where employee_dept = ‘accounts’;
SQL commands
5. Top command: This will give top N number of rows from the tables in
the output.
Example:
SELECT TOP 4 * FROM Student;  

6. LIMIT clause: limit commands limits the number of rows in the


output:
Example:
Select * from student LIMIT 4;
SQL commands
7. First() : used to return the first value of the column mentioned.
Example:
Select first(customer_name) from customer;

8. LAST(): last is used to return the last value of the column mentioned.
Example:
Select last(customer_name) from customer;
SQL commands
9. IN operator: used to return the rows which meets the values
mentioned in IN operator. Basically as a replacement of multiple OR
statements:
Example:
Select * from student where student_course IN (AI, ML, DS);

10. SUM(): used to return summed value of the expression.


Example:
Select sum(salary) from employee where employee_dept = ‘HR’;
SQL commands
11. NULL : used to select rows with null values.
Example:
Select student_name, student_ID from student where marks is NULL;

12. Not NULL : used to select rows with non null values.
Example:
Select student_name, student_ID from student where marks is NOT
NULL;
SQL commands
13. Where clause: used to retrieve only those rows of the table which
satisfy some conditions.
Example:
Select empname, empID from employee where dept = ‘dev’;
14. AND condition: SQL AND condition is used in SQL query to create
two or more conditions to be met.
Example:
Select * from employee where dept = ‘HR’ AND location = ‘HYD’;
SQL commands
15. OR condition: used to get the result if they satisfy either of the
conditions mentioned.
Example:
SELECT *FROM emp WHERE Department = "IT" OR Location = "
Chennai";  
16. AS : SQL 'AS' is used to assign a new name temporarily to a table
column or even a table.
Select count(DISTINCT employee_dept) AS dept from employee;
SQL commands
17. ORDER BY : Whenever we want to sort the records based on the columns
stored in the tables of the SQL database, then we consider using the ORDER
BY clause in SQL.
Example:
Select * from employee order by salary;

18. ORDER BY DESC: if we want to order in the descending order then we


use the order by desc command.
Example:
Select * from employee ORDER BY salary DESC;
SQL commands
19. GROUP By: The Group By statement is used for organizing similar
data into groups.
WHERE clause is placed before the GROUP BY clause in SQL.
ORDER BY clause is placed after the GROUP BY clause in SQL.
Example:
Select name, ID, sum(salary) AS salary from employee group by
employee_dept;
SQL commands
20. HAVING clause: having clause is used to filter out the result of group by clause .
Example:
Select name, ID, sum(salary) AS salary from employee group by employee_dept
having sum(salary) > 500,000;
21. INSERT : SQL INSERT statement is a SQL query. It is used to insert a single or
a multiple records in a table.
Example:
INSERT into student( ID, name, age)
Values( 1, “Ashish”, 22),
(2, “Rahul”, 21);
SQL commands
22. DROP Table: SQL DROP TABLE statement is used to delete a table
definition and all data from a table.
Example:
DROP TABLE student;

23. DELETE TABLE: The DELETE statement is used to delete rows from a
table. If you want to remove a specific row from a table you should use
WHERE condition.
Example:
Delete from customer where location = ‘Chennai’;
SQL commands
24.Rename table: used to change the name of the table.

Example:
RENAME employees to Dev_employees;
25. Truncate table: A truncate SQL statement is used to remove all rows
(complete data) from a table. It is similar to the DELETE statement with
no WHERE clause.
Example:
Truncate Table employee;
SQL commands
26. Select Into: it is used to copy the contents of one table into another.
Example:
SELECT * INTO Coding_Employees FROM Employee;  

27. ALTER TABLE: ALTER TABLE statement in Structured Query


Language allows you to add, modify, and delete columns of an existing
table.
Example:
ALTER TABLE Cars ADD Car_Model Varchar(20); 
SQL commands
ALTER TABLE employee MODIFY employee_name VARCHAR(50);
ALTER TABLE employee DROP COLUMN employee_age;
ALTER TABLE employee RENAME COLUMN dept to emp_dept;

28. UPDATE Table: SQL UPDATE statement is used to change the data of the
records held by tables. Which rows is to be update, it is decided by a condition
Example:
UPDATE employee
SET salary = salary + 0.1* salary
Where rating = 2;
SQL operators
1. SQL Arithmetic Operators: performs the operation on the
numerical data of the database table
- Addition operation:
- Subtraction operation
- Multiplication operation.
- Division operation
- Modulus operation
Example: select empSalary + bonus from employee;
SQL operators
2. SQL Comparison operations: The Comparison Operators in SQL
compare two different data of SQL table and check whether they are the
same, greater, and lesser.
- Equal ( =)
- not equal( !=)
- Greater than (>)
- Less than (<)
- Greater than or equal to ( >=) - less than or equal to (<=)
Example: select * from employee where salary > 200000;
SQL operators
3. Logical operators: Logical Operators in SQL perform the Boolean
operations, which give two results True and False
- AND
- OR
- NOT
- IN
- LIKE
- ANY
- ALL
SQL operators
4. SET operators
-Union
-Union ALL
- Intersect
- minus
Aggregate functions in SQL
• count()
• SUM()
• AVG()
• MIN()
• MAX()
JOINS
• SQL Join statement is used to combine data or rows from two or more
tables based on a common field between them. Different types of Joins
are as follows: 
• INNER JOIN
• LEFT JOIN
• RIGHT JOIN
• FULL JOIN
JOINS
Inner join: Inner join is used to get the common data from both the
tables which satisfies the condition.
Consider the following tables:
JOINS
Select student.name, student.age, course. Course_ID from student
inner join course on student. Roll_no = course.rollno ;
JOINS
Left join: This join returns all the rows of the table on the left side of the
join and matches rows for the table on the right side of the join. For the
rows for which there is no matching row on the right side, the result-set
will contain null. 
Select student.name, student.age, course. Course_ID from student left
join course on student. Roll_no = course.rollno ;
JOINS
Right join: This join returns all the rows of the table on the right side of
the join and matching rows for the table on the left side of the join. For
the rows for which there is no matching row on the left side, the result-
set will contain null. 
Select student.name, student.age, course. Course_ID from student right
join course on student. Roll_no = course.rollno ;
JOINS
FULL JOIN: Full join combines the results of left join and
right join.
Select student.name, student.age, course. Course_ID from
student full join course on student. Roll_no =
course.rollno ;
Nested Queries
In nested queries, a query is written inside a query. 

Take the following example:


Lets take the help of previous tables student and course.

Select student.name from student where student.rollno IN ( select


course.rollno from course where course.ID = 3);
Views
A view is a virtual table based on the result-set of an
SQL statement.

A view contains rows and columns, just like a real table.


The fields in a view are fields from one or more real
tables in the database.
Views
Create view syntax :
CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;

CREATE VIEW Brazil_Customers AS
SELECT CustomerName, ContactName
FROM Customers
WHERE Country = 'Brazil';
PL/SQL Basics
• PL/SQL stands for "Procedural Language extension of SQL" that is
used in Oracle. 
• PL/SQL is a block structured language
• PL/SQL includes procedural language elements like conditions and
loops.
•  It allows declaration of constants and variables, procedures and
functions, types and variable of those types and triggers.
• It can support Array and handle exceptions 
Variable in PL/SQL
PL/SQL allocates memory for the variable's value and the storage
location is identified by the variable name.

Syntax for declaring the variable:


variable_name [CONSTANT] datatype [NOT NULL] [:= | DEFAULT i
nitial_value]  

Initializing the variable( by assignment operator or default statement)


1.counter binary_integer := 0;  
2.greetings varchar2(20) DEFAULT 'Hello JavaTpoint';    
Variable in PL/SQL
Variable scope : variable declared in the inner block will not be
accessible from outside.
Variable Attribute:
1. The %TYPE attribute is used to declare variables according to the
already declared variable or database column.
<var_name> <tab_name>.<column_name>%TYPE;  
2. %ROWTYPE:The %ROWTYPE attribute is used to declare a
record type that represents a row in a table.
<var_name> <tab_name>.ROW%TYPE;  
Basic Syntax for
Example:
PL/SQL
There are three sections: DECLARE
DECLARE Message varchar2(20): ‘Hello,
< declaration section> world!’;
BEGIN BEGIN
< executable commands> dbms.output.put_line(message);
END END:
PL/SQL for writing procedures
The PL/SQL stored procedure or simply a procedure is a PL/SQL block
which performs one or more specific tasks.

Procedure contains the a header and a body.

Parameters in a procedure:
• IN parameter
• OUT parameter
• INOUT parameter
PL/SQL for writing procedures
Syntax for creating procedure:
1.CREATE [OR REPLACE] PROCEDURE procedure_name  
2.    [ (parameter [,parameter]) ]  
3.IS  
4.    [declaration_section]  
5.BEGIN  
6.    executable_section  
7.[EXCEPTION  
8.    exception_section]  
9.END [procedure_name];  
PL/SQL for writing procedures
Example:
1.create or replace procedure "INSERTUSER"    
2.(id IN NUMBER,    
3.name IN VARCHAR2)    
4.is    
5.begin    
6.insert into user values(id,name);    
7.end;    
8./       
Calling the procedure:
9.BEGIN    
10.   insertuser(101,'Rahul');  
11.   dbms_output.put_line('record inserted successfully');    
12.END;    
13./    
PL/SQL for writing procedures
• DROP procedure:

• In order to delete a procedure, we can use the drop procedure


command:
• DROP PROCEDURE procedure_name;   
PL/SQL for writing cursors
Cursors: When an SQL statement is processed, Oracle creates a memory
area known as context area.

A cursor is a pointer to this context area. It contains all information


needed for processing the statement.

A cursor is used to referred to a program to fetch and process the rows


returned by the SQL statement, one at a time
Types of cursors
1. Implicit cursors: The implicit cursors are automatically generated by Oracle while an SQL
statement is executed.
Example:
2.DECLARE   
3.   total_rows number(2);  
4.BEGIN  
5.   UPDATE  customers  
6.   SET salary = salary + 5000;  
7.   IF sql%notfound THEN  
8.      dbms_output.put_line('no customers updated');  
9.   ELSIF sql%found THEN  
10.      total_rows := sql%rowcount;  
11.      dbms_output.put_line( total_rows || ' customers updated ');  
12.   END IF;   
13.END;  
14./  
Types of Cursors
2. Explicit cursors
Explicit cursors are defined by the programmers to gain more control over the context area.
• You must follow these steps while working with an explicit cursor.
1.Declare the cursor to initialize in the memory.:
CURSOR name IS  SELECT statement;   

2. Open the cursor to allocate memory.


CURSOR name IS  SELECT statement;   

3. Fetch the cursor to retrieve data.


FETCH cursor_name INTO variable_list;  
4. Close the cursor to release allocated memory.
Close cursor_name;  
Explicit cursor example
1.DECLARE  
2.   c_id customers.id%type;  
3.   c_name customers.name%type;  
4.   c_addr customers.address%type;  
5.   CURSOR c_customers is  
6.      SELECT id, name, address FROM customers;  
7.BEGIN  
8.   OPEN c_customers;  
9.   LOOP  
10.      FETCH c_customers into c_id, c_name, c_addr;  
11.      EXIT WHEN c_customers%notfound;  
12.      dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);  
13.   END LOOP;  
14.   CLOSE c_customers;  
15.END;  
16./  
PL/SQL for writing triggers
Trigger is invoked by Oracle engine automatically whenever a specified event
occurs

Triggers are written to be executed in response to any of the following events.:

• A database manipulation (DML) statement (DELETE, INSERT, or


UPDATE).
• A database definition (DDL) statement (CREATE, ALTER, or DROP).
• A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or
SHUTDOWN).
Creating a Trigger
1.CREATE [OR REPLACE ] TRIGGER trigger_name   
2.{BEFORE | AFTER | INSTEAD OF }   
3.{INSERT [OR] | UPDATE [OR] | DELETE}   
4.[OF col_name]   
5.ON table_name   
6.[REFERENCING OLD AS o NEW AS n]   
7.[FOR EACH ROW]   
8.WHEN (condition)    
9.DECLARE  
10.   Declaration-statements  
11.BEGIN   
12.   Executable-statements  
13.EXCEPTION  
14.   Exception-handling-statements  
15.END;  
Example for triggers
1.CREATE OR REPLACE TRIGGER display_salary_changes  
2.BEFORE DELETE OR INSERT OR UPDATE ON customers  
3.FOR EACH ROW  
4.WHEN (NEW.ID > 0)  
5.DECLARE  
6.   sal_diff number;  
7.BEGIN  
8.   sal_diff := :NEW.salary  - :OLD.salary;  
9.   dbms_output.put_line('Old salary: ' || :OLD.salary);  
10.   dbms_output.put_line('New salary: ' || :NEW.salary);  
11.   dbms_output.put_line('Salary difference: ' || sal_diff);  
12.END;  
13./  
• Update query on customers table:
• Old value in the table was 100
• Before running the upate query:
• Old.salary = 100
• New.salary = null
• After update query
• Old.salary = 100
• New .salary = 150
• Sal_diff = new.salary – old.salary => 150 -100
Connecting to oracle database using Python
Step 1: install cx_Oracle
Py –m pip install cx-Oracle
Step 2: import database specific module:
Import cx_Oracle
Step 3: connect()
Con = cx_Oracle.connect(‘username/password@localhost’)
Step 4: Cursor()
Cursor() = con.cursor()
Step 5: execute
Cursor.execute(sqlquery)
Step 6 : Commit()
Continue..
• Fetchone(), fetchall(), fetchmany():
1.fetchone() : This method is used to fetch one single row from the top
of the result set.
2.fetchmany(int): This method is used to fetch a limited number of rows
based on the argument passed in it.
3.fetchall() : This method is used to fetch all rows from the result set
• Close(): After all done it is mandatory to close all operations.
Cursor.close()
Con.close()
Example
import cx_Oracle
 
# Create a table in Oracle database
try:
 
    con = cx_Oracle.connect('tiger/scott@localhost:1521/xe')
    print(con.version)
 
    # Now execute the sqlquery
    cursor = con.cursor()
 
    # Creating a table employee
    cursor.execute(
        "create table employee(empid integer primary key, name varchar2(30), salary number(10, 2))")
 
    print("Table Created successfully")
 
except cx_Oracle.DatabaseError as e:
    print("There is a problem with Oracle", e)
 
# by writing finally if any error occurs
# then also we can close the all database operation
finally:
    if cursor:
        cursor.close()
    if con:
        con.close()

You might also like