Presentation is loading. Please wait.

Presentation is loading. Please wait.

Structured Query Language (SQL) For creating and manipulating Database

Similar presentations


Presentation on theme: "Structured Query Language (SQL) For creating and manipulating Database"— Presentation transcript:

1 Structured Query Language (SQL) For creating and manipulating Database
Chapter 9 Structured Query Language (SQL) For creating and manipulating Database Download these slides

2 SQL We studied about relational database in last chapter, SQL is used to create and manage a Relational Database . The original version was developed at IBM. It provides a high level declarative interface for the users. Examples for RDBMS Soft wares are MySQL, Oracle, Sybase, Informix,Postgres SQL Server and MS Access etc

3 Features of SQL Relational database language
Simple, Flexible, Powerful. Provides create ,modify tables, insert and manipulate data Data security Provides concept of views Integrity checks while inserting data

4 Eg: insert,delete,update,select
Components of SQL DDL (Data Definition Language) : Commands for defining / creating, deleting, modifying schema or structure of a relation. Eg: create ,drop,alter DML (Data Manipulation Language) It includes commands for inserting, deleting, selecting and modifying tuples in a relation. Eg: insert,delete,update,select DCL (Data Control Language) It includes commands control access to the database for security concerns, Eg: Grant ,revoke SQL is used to embed with other programming languages like C, C++ etc..

5 Working on MySQL MySQL is free, fast, easy to use RDBMS Open source
High security Works on many Operating system and with many languages like PHP, Perl, C, C++,Java etc Work effectively even with Huge volume of data Best for Web development with PHP

6 MySQL General Commands
Quit; / Exit; Create database “database name”; Use “database name”; Show databases; Desc / Describe “tablename”; Tee c:\output.txt

7 Data types in SQL (For indicating Types of values in a field)
Int or Integer Eg: 69,0,-112 Dec or Decimal Usage: Decimal (Size,D), D for digits after decimal point (Dec(5,2) eg: ) Char or Character Usage: char (Size) , char (10) reserved for 10 characters Varchar(size) Date Time

8 Integer types Int - For representing decimal numbers without fraction.
Syntax :Attributename int Example : accno int Automatically set the size. Big int For representing Large decimal numbers upto 18 digits. Small int For representing small decimal numbers. Tiny int For representing very small decimal numbers. Medium int For representing medium sized decimal numbers. Syntax : Attributename small int Example : Slno small int,

9 Char & Varchar For representing character type of data. Allocate memory storage of maximum number of characters in the field, Varchar for variable length string Char Syntax:- Attributename Char(size) Example: Name char(25) Place char(10) Sex char Varchar Syntax:- Attributename varchar(size) Example: remarks varchar(150)

10 Format: ’15:08:26’ in HH:MM:SS
Other Types Dec- For representing fractional decimal numbers. Syntax : Attributename Dec (size, scale) Example : percentage dec (5, 2) Total 5 digits or more with 2 places for decimal point. Date For representing dates in a specified format. Syntax : Attributename date Example : dob date Format: ‘ ’,’2010/02/25’,’ ’ Time :For representing time in a specified format. Syntax : Attributename time Example : tob time Format: ’15:08:26’ in HH:MM:SS

11 SQL Commands Classified into two DDL Commands DML Commands Create table Select Alter Table Update Drop Table Delete Insert View

12 SQL Commands (DDL Commands)
Create table command It is used to create a relation or table with a set of columns with constraints. Syntax: Create table Tablename (columnname datatype (size) column constraint, …………………………………, ………………………………… );

13 Rules for naming table Must not a SQL keyword.
Must begin with an alphabet. May contain digits, letters, underscore. Space, symbols, special symbols are not allowed. It should be unique. Uppercase and lowercase treated as same.

14 Column Constraints Constraints are the rules applied on data that are entered into the column of a table They are some keywords by which some restrictions can be implement in the desired columns. They are mention after the data type of the column. It ensures the integrity, consistency and redundancy. So it also called database integrity constraints. They are Not Null, Auto_Increment, Unique, Primary Key, Default, etc

15 Column Constraints Not Null:-
It ensure that a column can never have null or empty values. Unique:- It ensure that no two rows have the same value in the specified column. Primary Key:- To set a column as a primary key to identify a row/record/tuple in a table. It cannot contain a null value. Default:- To set a default value for column. Auto_increment:- if no values specified,MySQL automatically perform an increment feature (one coloumn is allowed for this rule)

16 Write query to create a table with the specifications given below
Column name Type of data and description Admno 3 digit numeric value with primary key Name String of 20 characters Sex Single character ‘M’ or ‘F’ Mark Upto 600 Percent A real number less than100 create table student (admno number(3) primary key auto_increment, name char(20),sex char, dob date, Mark int, percent dec(5,2) unique (admno);

17 Write query to create a table with the specifications given below
Column name Type of data and description empno 4 digit numeric value with primary key Name String of 25 characters Age 2 Digit with default value 30 Salary 5 digits, not empty Phone number 10 digit, Unique Designation 15 characters

18 Query:- Create table employee (empno dec(4) primary key, Name char(25), Age int default ’30’, Salary dec(7,2) not null, Phone big int , Designation char(15) Unique(Phone))

19 DML Commands They are Insert Select Update Delete View

20 Insert Command To insert values or records in to a table. So it adds new row to a table. Here the clauses “into” and “values” are used. Single quotes(‘) must be used if we insert characters or names Syntax: Insert into tablename [column1,column2,…] Values(value1, value 2, …….); where [ data inside square brackets ] is optional Example Query to add “rollno”, “name”, “score”, “grade” to the “student” table as follows. Insert into student Values(1, ‘Joseph’, 180, ‘A’);

21 Insert Command usages Another Methode Query to add “rollno”, “name”, only to the “student” table as follows. Insert into student (rollno,name) Values(2, ‘Gopi’); Or Insert into student Values(2, ‘Gopi’, null,null); If no constraints are set for other columns If we add two records same time use the following command Insert into student Values(12, ‘Jose’, 280, ‘A+’), (13, ‘Malu’, 186, ‘A’);

22 Insertion with interaction
We can insert records in to a table in an interaction manner. For this the symbol ‘&’ is used, it is called substitution operator. Syntax: Insert into tablename values(&columnname1,&columnname2……); Example Query to insert records to the table ‘student’ in interaction fashion as follows. Insert into student values (&rollno, ‘&name’, &score, ‘&grade’);

23 Explanation of clauses
Select Command Select command is used to retrieve and display the records or information from a table according to a condition. Syntax Select [distinct/all] column1,column2,… From tablename [Where condition Order by columnname Group by columnname Having condition;] Explanation of clauses Distinct : To display the records without duplication. All : To display all records with duplicates (*). From : To indicate the table name. Where : To specify the condition. Order by : To group the record in a table. Group by : To group a value in a column Having : To set condition for a selected group.

24 Query to retrieve all records in the student table
Examples for distinct, all (*) from clauses Query to retrieve all records in the student table Query: Select * from student; Query to retrieve name and score in the student table Query: Select name, score from student;

25 Query: Select distinct mark from student;
Query to retrieve all records in the student table with no duplicate marks Query: Select distinct mark from student; Query to retrieve name and grade in the student table Query: Select name, grade from student;

26 Examples for ‘Where’ clause
Note: In ‘where’ clause we can use the relational operators like =, >, <, >=, <=, !=,<>, and logical operators such as AND, OR, NOT also special operators such as IN, BETWEEN, LIKE, IS NULL can use. Write query to retrieve name and phone number of a student having age greater than 16 in student table. Query: Select name, phone From student Where (age>16); Another sample Select name, course From student Where course in (‘commerce’,’humanities’);

27 Examples for ‘Where’ clause
Write query to retrieve all students details with mark greater than 60. Query: Select *from student Where (mark>60); Write query to retrieve name and mark of students with mark greater than 60 and age less than 19. Query: Select name, mark from student Where (mark>60 AND age<19);

28 Examples for ‘Where’ clause
Write query to retrieve name, mark and age of students with age 16 or 17. Query: Select name, mark, age from student Where (age=16 OR age=17); Write query to retrieve name and mark of students with mark other than 100. Query: Select name, mark from student Where NOT (mark=100);

29 Examples for ‘Where’ clause
Write query to retrieve all details of students with name either Jayan or Joy. Query: Select *from student Where name IN(‘Jayan’, ‘Joy’); Write query to retrieve all details of students with marks between 30 and 60. Query: Select *from student Where mark BETWEEN 30 AND 60;

30 Examples for ‘Where’ clause with pattern matching
Write query to retrieve all details of students with name begin with letter ‘J’. Query: Select *from student Where (name LIKE ‘J%’); Note: The wild card characters % is used for any number of characters to match the pattern and Underscore _ only one character matching Eg: “Ab%’ > Gives Abin, Abhilash,Abdu etc ‘%cat%’ > Gives education,indication,catering etc ‘_ _ _ _ ‘ > Gives Abin, John,Abdu etc ‘_ _ _ %’ > Gives results of minimum three characters

31 Examples for ‘Where’ clause
Write query to retrieve all details of students with name begin with any character but ends with the letter ‘oy’. Query: Select *from student Where (name LIKE ‘_oy’); Write query to retrieve all details of students have no phone numbers. Query: Select *from student Where (phone IS NULL);

32 Sorting using ‘order by’ clause
It is used to retrieve data in ascending or descending manner from a table. For this the parameters like ASC and DESC is used. (ASC is default) Write query to retrieve all details of students in the order of their marks. Query: Select *from student Order by mark desc;

33 Examples for ‘order by’ clause
Write query to retrieve all details of students whose marks greater than 50 in the ascending order of name Query: Select *from student Where (mark>50) Order by name; Write query to retrieve class wise details of student in the order of name. Query: Select *from student Order by class, name;

34 Aggregate functions They are predefined functions used to compute results of arithmetic operations and also used to select column for a table. They are Function Usage Example AVG() To return the average values of a column. Select AVG (mark) From student; SUM() To return the sum of values of a column. Select SUM (price) From book; MAX() To return the maximum value of a column. Select MAX (mark) MIN() To return the minimum value of a column. Select MIN (mark) COUNT(*) To return the number of records or rows in a table. Select COUNT(*)

35 Examples for ‘group by’ and ‘having’ clause
The group by clause is used to group the row in a table based on common values. The having clause is used to set a condition for a selected groups. Consider the table given below No Name Designation 1 Arun Programmer 2 Deepa Designer 3 Latha 4 Raju Analyst 5 Meena

36 Examples for ‘group by’ and ‘having’ clause
The following query produces a table given below. Select designation, count(*) From employee Group by designation; Designation Count * Programmer 3 Designer 1 Analyst

37 Examples for ‘group by’ and ‘having’ clause
Consider the table given below No Name Designation Salary 1 Arun Programmer 25000 2 Deepa Designer 20000 3 Latha 4 Raju Analyst 15000 5 Meena The following query produces a table given below. Select designation, count(*) From employee Group by designation Having (salary>20000); Designation Count * Programmer 3 Select course, count(*) From student Group by course Having (count (*) > 3);

38 Modifying Data using Update Command
To change or modify or update the value in a column of a table. Here the clause ‘set’ is used . Also we can use the conditions by using ‘where’ clause. Synatx: Update tablename Set columnname1=value [, columnname2=value ,…] [where condition]; Example: Write query to change the ‘salary’ of all persons to 8000 in the table ‘employee’. Query: Update employee Set salary=8000;

39 Update Command Example:
Write query to change the ‘salary’ to ,of the person whose ‘idno’ =400 in the table ‘employee’. Query: Update employee Set salary=10000 Where(idno=400);

40 Update Command Query: Update employee Set salary= salary+salary* 0.05;
Example: Write query to increment the ‘salary’ of all persons to 5% of current salary in the table ‘employee’. Query: Update employee Set salary= salary+salary* 0.05; Example: Write query to update the field ‘total’ in the ‘student’ table as sum of ‘sub1’, ‘sub2’ and ‘sub3’. Query: Update student Set total=sub1+sub2+sub3;

41 Changing structure of the table using Alter table command
To modify the structure of an existing table by adding columns or modifying columns. It have 4 forms ‘Alter table’ with ‘add’ clause ‘Alter table’ with ‘modify’ clause ‘Alter table’ with ‘drop’ clause ‘Alter table’ with ‘rename to’ clause

42 ‘alter table’ with ‘add’ clause
To add new column in an existing table. Syntax Alter table tablename Add (columnname datatype(size) constraints) [First/After columnname]; Example: Query to add a new column ‘grade’ in the ‘student’ table the query as follows. Alter table student Add (grade char(2) not null); Alter table student Add gracemark int after grade;

43 ‘alter’ table with ‘modify’ clause
To modify an existing column in an existing table. Syntax: Alter table tablename Modify (coloumnname datatype(size) constraint); Example: Query to alter the column ‘rollno’ in ‘student’ table as follows. Alter table student (Rollno number(5) primary key);

44 ‘alter’ table with ‘drop’ clause
To remove an existing column in an existing table. Syntax: Alter table tablename drop (coloumnname); Example: Query to delete the column ‘gracemark’ in ‘student’ table as follows. Alter table student Drop gracemark;

45 ‘alter’ table with ‘rename to’ clause
To rename a table in the selected databse. Syntax: Alter table tablename Rename to new_table_name; Example: Query to rename the table student to student2015. Alter table student rename to student2015;

46 Synatx: Delete from tablename [where condition]
Delete Command To delete one or more records or row from a table according to a condition. Here the clauses like ‘from’ and ‘where’ are used. Synatx: Delete from tablename [where condition] Example: Write query to delete all records from the table ‘student’. Query: Delete from student; Example: Write query to delete records from the table ‘student’. Whose name is ‘Sarath’. Query: Delete from student Where (name=‘Sarath’);

47 Drop table command To remove/delete an existing table from the selected databse. Syntax: drop table tablename; Example: Query to delete ‘student2015’ table as follows. drop table student2015;

48 Nested Queries The result of one query is used as the condition of another query is called nested query. Here the inner query is placed within the where clause of the outer query. Example: Write query to display the student name and course with highest mark in the student table. Query: Select name,couse from student Where (mark=select max (mark) from student); NB:- It is derived from Select name,course from student; Select max (mark) from student;

49 Nested queries Example:
Write query to retrieve all details of students with minimum mark. Query: Select * from student Where (mark= select min (mark) From student); Sample Query: Select name from employee Where salary= (select max (salary) From employee);

50 Inserting query results to another table
Example: Write query to insert all the details of student from student table to the table teacher with total>400. Query: Insert into teacher Select *from student Where (mark>400);

51 Concept of Views A view is a temporary table used to provide different displays to an existing table. Advantages It provides data security. Avoids data redundancy. Users get only wanted data. Syntax Create view <view name> As select <attribute names> from <table name> [Where <conditions>];

52 View Example: Write a query to create a view from the table employee with name and salary with salary above Rs.10000 Query: Create view empview As select name, salary From employee Where (salary>=10000); Another sample: Create view oldstud As select * From student2015 Where dob<‘ ’;

53 View updation / deletion
Example: View can be updated using update command. View can be deleted using drop view command Query to update view: Update oldstud set regno= where admno=1005; Query to delete view: Drop view oldstud;

54 Thanks for Watching…………..
Download these slides By TCA Gafoor AKM HSS KOTTOOR


Download ppt "Structured Query Language (SQL) For creating and manipulating Database"

Similar presentations


Ads by Google