Structured Query Language
Structured Query Language
SQL: A database programming language that uses to create and manipulate databases using the
tools/packages. In other word, SQL is a Query language for most commercial relational database
management systems (DBMS). There are many different versions of the SQL language, but to be
in compliance with the ANSI standard, they must support the same major keywords in a similar
manner (such as SELECT, UPDATE, DELETE, INSERT, WHERE, and others). Most of the
SQL database programs also have their own proprietary extensions in addition to the SQL
standard such as TSQL (Transact-SQL) for Microsoft SQL Server and PLSQL and SQL plus for
Oracle.
Any DBMS should have a language for defining the structures in the database – this is called the
DDL (Data Definition Language). This is used by the database designer/administrator to build
the database.
It should also have a language for manipulating the data in the database – this is called the DML
(Data Manipulation Language). This language is used by users of the database to insert, retrieve,
modify and delete data in the database.
Generally, SQL is Structured Query Language, which is a computer language for storing,
manipulating and retrieving data stored in relational database.
SQL is the standard language for Relation Database System. All relational database management
systems like MySQL, MS Access, Oracle, Sybase, Informix, postgres and SQL Server use SQL
as standard database language.
Why SQL?
Allows users to access data in relational database management systems.
Allows users to describe the data.
Allows users to define the data in database and manipulate that data.
Allows to embed within other languages using SQL modules, libraries &
pre-compilers.
Allows users to create and drop databases and tables.
Allows users to create view, stored procedure, functions in a database.
Allows users to set permissions on tables, procedures and views.
SQL Process:
When you are executing an SQL command for any RDBMS, the system determines the best way to
carry out your request and SQL engine figures out how to interpret the task.
There are various components included in the process. These components are Query Dispatcher,
Optimization Engines, Classic Query Engine and SQL Query Engine, etc. Classic query engine
handles all non-SQL queries, but SQL query engine won't handle logical files.
SQL Commands
Unfortunately, as we discussed previously there are many different versions of the SQL
language, but to be in compliance with the ANSI standard, they must support the same major
keywords or commands in a similar manner (such as SELECT, UPDATE, DELETE, INSERT,
WHERE, and others).
The standard SQL commands to interact with relational databases are CREATE, SELECT,
INSERT, UPDATE, DELETE and DROP. These SQL commands are grouped or classified into
four major categories depending on their functionality or nature:
You would use these data types while creating your tables. You would choose a particular data
type for a table column based on your requirement.
SQL Server offers six categories of data types for your use:
SQL Operators
What is an Operator in SQL?
An operator is a reserved word or a character used primarily in an SQL statement's WHERE
clause to perform operation(s), such as comparisons and arithmetic operations.
Operators are used to specify conditions in an SQL statement and to serve as conjunctions for
multiple conditions in a statement. The available types of operators in SQL are the following:
Arithmetic operators
Comparison operators
Logical operators
\\
An expression is a combination of one or more values, operators, and SQL functions that
evaluate to a value.
SQL EXPRESSIONs are like formulas and they are written in query language. You can also use
them to query the database for specific set of data. We will discuss about the syntax and examples in
select statement.
SQL is followed by unique set of rules and guidelines called Syntax. This tutorial gives you
a quick start with SQL by listing all the basic SQL Syntax:
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 (;).
Important point to be noted is that SQL is case insensitive, which means SELECT and
select have same meaning in SQL statements, but MySQL makes difference in table names.
So if you are working with MySQL, then you need to give table names as they exist in the
database.
Example:
If you want to create new database called testDB, then CREATE DATABASE statement would be
as follows:
MYSQL> CREATE DATABASE testDB;
Once a database is created, you can check it in the list of databases using SHOW statement as
follows:
+ +
| Database |
+ +
| information_schema |
| AMROOD |
| TUTORIALSPOINT |
| mysql |
| orig |
| test |
| testDB |
+ +
7 rows in set (0.00 sec)
When you have multiple databases in your SQL Schema, then before starting your operation, you
would need to select a database where all the operations would be performed.
USE statement: is the SQL statement that used to select any existing database in SQL
schema.
Syntax:
USE Database_name;
Example: if you want to work with testDB database, then you can execute the following SQL
command and start working with testDB database.
MYSQL> USE testDB;
DROP DATABASE statement: is used to drop or delete an existing database in SQL
schema.
Syntax:
Example:
If you want to delete an existing database <testDB>, then DROP DATABASE statement would
be as follows:
NOTE: Be careful before using this operation because by deleting an existing database would
result in loss of complete information stored in the database.
Creating a basic table involves naming the table, defining its columns, fixing each column's data
type and defining constraints.
o CREATE TABLE statement: is used to create a new table object of database.
Syntax:
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY (one or more columns)
);
SQL Constraints:
Here as we discussed theoretically there are constraints that are the rules enforced on data columns
on table. These are used to limit the type of data that can go into a table. This ensures the
accuracy and reliability of the data in the database. Constraints could be column level or table level.
Column level constraints are applied only to one column, whereas table level constraints are
applied to the whole table.
So, in this lab we will see the following commonly used constraints available in SQL:
NOT NULL Constraint: Ensures that a column cannot have NULL value.
DEFAULT Constraint: Provides a default value for a column when none is specified.
Example:
Creates a CUSTOMERS table with ID as primary key and NOT NULL are the constraints
showing that these fields cannot be NULL while creating records in this table:
MYSQL> CREATE TABLE customers ( Id
int not null,
Name varchar (20) not null, Age
int not null,
Address char (25),
Salary decimal (18, 2),
Primary key (id)
);
If customers table has already been created, then to add a NOT NULL constraint to SALARY
column in Oracle and MySQL, you would write a statement similar to the following:
ALTER TABLE customers
Modify salary decimal (18, 2) not null;
DEFAULT Constraint
The DEFAULT constraint provides a default value to a column when the INSERT INTO
statement does not provide a specific value.
Example:
For example, the following SQL creates a new table called customers and adds five columns.
Here, SALARY column is set to 5000.00 by default, so in case INSERT INTO statement does
not provide a value for this column. Then by default this column would be set to 5000.00.
CREATE TABLE customers (
Id int not null,
Name varchar (20) not null, Age
int not null,
Address char (25),
Salary decimal (18, 2) default 5000.00, Primary
key (id)
);
If customers table has already been created, then to add a DFAULT constraint to SALARY
column, you would write a statement similar to the following:
ALTER TABLE customers
MODIFY SALARY DECIMAL (18, 2) default 5000.00;
UNIQUE Constraint
The UNIQUE Constraint prevents two records from having identical values in a particular column.
In the CUSTOMERS table, for example, you might want to prevent two or more people from
having identical age.
Example:
For example, the following SQL creates a new table called CUSTOMERS and adds five
columns. Here, AGE column is set to UNIQUE, so that you can not have two records with same
age:
CREATE TABLE customers (
Id int not null,
Name varchar (20) not null, Age
int not null unique, Address char
(25),
Salary decimal (18, 2),
Primary key (id)
);
If CUSTOMERS table has already been created, then to add a UNIQUE constraint to AGE
column, you would write a statement similar to the following:
ALTER TABLE CUSTOMERS
MODIFY AGE INT NOT NULL UNIQUE;
You can also use following syntax, which supports naming the constraint in multiple columns as
well:
ALTER TABLE CUSTOMERS
ADD CONSTRAINT myUniqueConstraint UNIQUE (AGE, SALARY); To
drop a UNIQUE constraint, use the following SQL:
ALTER TABLE CUSTOMERS
DROP CONSTRAINT myUniqueConstraint;
If you are using MySQL, then you can use the following syntax:
ALTER TABLE CUSTOMERS
DROP INDEX myUniqueConstraint;
PRIMARY Key Constraint
A primary key is a field in a table which uniquely identifies each row/record in a database table.
Primary keys must contain unique values. A primary key column cannot have NULL values. A
table can have only one primary key, which may consist of single or multiple fields. When
multiple fields are used as a primary key, they are called a composite key. If a table has a primary
key defined on any field(s), then you cannot have two records having the same value of that
field(s).
Note: You would use these concepts while creating database tables.
To create a PRIMARY KEY constraint on the "ID" column when CUSTOMERS table already
exists, use the following SQL syntax:
ALTER TABLE CUSTOMER ADD PRIMARY KEY (ID);
NOTE: If you use the ALTER TABLE statement to add a primary key, the primary key
column(s) must already have been declared to not contain NULL values (when the table was first
created).
For defining a PRIMARY KEY constraint on multiple columns, use the following SQL syntax:
CREATE TABLE CUSTOMERS (
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID, NAME)
);
To create a PRIMARY KEY constraint on the "ID" and "NAMES" columns when
CUSTOMERS table already exists, use the following SQL syntax:
ALTER TABLE CUSTOMERS
ADD CONSTRAINT PK_CUSTID PRIMARY KEY (ID, NAME);
You can clear or delete the primary key constraints from the table, Use Syntax: ALTER
TABLE CUSTOMERS DROP PRIMARY KEY;
If ORDERS table has already been created, and the foreign key has not yet been set, use the syntax
for specifying a foreign key by altering a table.
ALTER TABLE ORDERS
ADD FOREIGN KEY (Customer_ID) REFERENCES CUSTOMERS (ID);
To drop a FOREIGN KEY constraint, use the following SQL:
ALTER TABLE ORDERS
DROP FOREIGN KEY;
CHECK Constraint
The CHECK Constraint enables a condition to check the value being entered into a record. If the
condition evaluates to false, the record violates the constraint and isn’t entered into the table.
Example:
For example, the following SQL creates a new table called CUSTOMERS and adds five
columns. Here, we add a CHECK with AGE column, so that you can not have any CUSTOMER
below 18 years:
CREATE TABLE CUSTOMERS (
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL CHECK (AGE >= 18),
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
If CUSTOMERS table has already been created, then to add a CHECK constraint to AGE column, you
would write a statement similar to the following:
ALTER TABLE CUSTOMERS
MODIFY AGE INT NOT NULL CHECK (AGE >= 18);
You can also use following syntax, which supports naming the constraint in multiple columns as
well:
ALTER TABLE CUSTOMERS
ADD CONSTRAINT myCheckConstraint CHECK (AGE >= 18);
To drop a CHECK constraint, use the following SQL. This syntax does not work with MySQL:
ALTER TABLE CUSTOMERS
DROP CONSTRAINT myCheckConstraint;
INDEX Constraint
The INDEX is used to create and retrieve data from the database very quickly. Index can be created
by using single or group of columns in a table. When index is created, it is assigned a ROWID for
each row before it sorts out the data. Proper indexes are good for performance in large databases,
but you need to be careful while creating index. Selection of fields depends on what you are using in
your SQL queries.
Example:
For example, the following SQL creates a new table called CUSTOMERS and adds five
columns:
CREATE TABLE CUSTOMERS (
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
Now, you can create index on single or multiple columns using the following syntax: CREATE
INDEX index_name
ON table_name (column1, column2. ......... );
To create an INDEX on AGE column, to optimize the search on customers for a particular
o SHOW TABLES statement: is used to show the existing tables in the database.
Syntax:
SHOW tables;
o DROP TABLE statement: is used to remove a table definition and all data, indexes,
triggers, constraints, and permission specifications for that table. The SQL DROP
command is used to remove an object from the database. If you drop a table, all the rows in
the table are deleted and the table structure is removed from the database. Once a table is
dropped we cannot get it back, so be careful while using DROP command. When a table
is dropped all the references to the table will not be valid.
NOTE: You have to be careful while using this command because once a table is deleted then all
the information available in the table would also be lost forever.
Syntax:
DROP TABLE table_name;
Example:
To drop CUSTOMERS table from database
MYSQL> DROP TABLE CUSTOMERS;
o ALTER TABLE statement: is used to add, drop or modify table columns. The SQL
Example:
o RENAME TABLE statement: is used to change the name of the table or a database
object.
Syntax:
With RENAME statement you can rename a table. Some of the relational database management
system (RDBMS) does not support this command, because this is not standardizing statement.
So use the following syntax:
RENAME TABLE {oldtable_name} TO {newtable_name};
Where {oldtable_name} table that exists in the current database, and {newtable_name} is new
table name.
Example:
To change the name of the table employee to my_employee, the query would be like
RENAME table employee TO my_emloyee;
Compiled By: - Melsew D Page 22
SQL Lab Manual PICE
N.B: You may not need to specify the column(s) name in the SQL query if you are adding values
for all the columns of the table. But make sure the order of the values is in the same order as the
columns in the table.
Example:
If you want to insert a row to the employee table, the query would be like,
INSERT INTO employee (id, name, dept, age, salary location) VALUES (105, 'Srinath',
'Aeronautics', 27, 33000);
NOTE: When adding a row, only the characters or date values should be enclosed with single
quotes.
If you are inserting data to all the columns, the column names can be omitted. The above insert
statement can also be written as:
INSERT INTO employee
VALUES (105, 'Srinath', 'Aeronautics', 27, 33000);
Assume we have created the following tables in the database: Student table and Teacher table. These
database tables are used here for better explanation of SQL DML commands/statements. And
starting from this we are going to manipulate data on this tables.
UPDATE Statement: is used to change the value in an existing record. A Statement is used
to modify the existing rows in a table.
Syntax:
UPDATE table_name
SET column1 = value1, column2 = value2. ...columnN=valueN
[WHERE CONDITION];
NOTE: In the Update statement, WHERE clause identifies the rows that get affected. If you do
not include the WHERE clause, column values for all the rows get affected.
Example: To update the department of betelehem from student table by Maths
UPDATE student
SET Department= ‘Maths’
WHERE Sid=102;
NOTE: The WHERE clause in the SQL delete command is optional and it identifies the rows in
the column that gets deleted. If you do not include the WHERE clause all the rows in the table is
deleted, so be careful while writing a DELETE query without WHERE clause.
Example: To delete a student with Sid 100 from the student table, the SQL delete query would be
like,
DELETE FROM student WHERE Sid = 100;
To delete all the rows from the student table, the query would be like, DELETE
FROM student;
NOTE: In a SQL SELECT statement only SELECT and FROM statements are mandatory. Other
clauses like WHERE, ORDER BY, GROUP BY, HAVING are optional.
To retrieve specific data/records based on criteria from database tables you can use SQL clauses
and operators.
The operators are evaluated in a specific order of precedence, when more than one arithmetic
operator is used in an expression. The order of evaluation is: parentheses, division, multiplication,
addition, and subtraction. The evaluation is performed from the left to the right of the expression.
For example: If we want to display the first and last name of student combined together, the
SQL Select Statement would be like:
SELECT Fname, Lname FROM student;
SQL Clauses
SQL clauses are used to manipulate data on database. In this manual we will see some clauses,
operators and expressions in SQL with example in different SQL commands/statements.
For Example: To find or retrieve the Fname and Lname of a student with id 100, the query would
be like:
SELECT Fname, Lname FROM student
WHERE id = 100;
N.B: Comparison Operators and Logical Operators are used in WHERE Clause.
For Example: To find the name of a student with age above 20, the query would be like: SELECT
Fname, Lname FROM student
WHERE Age>20;
NOTE: Aliases defined for the columns in the SELECT statement cannot be used in the
WHERE clause to set conditions. Only aliases created for tables can be used to reference the columns
in the table.
NOTE: Aliases defined in the SELECT Statement can be used in WHERE Clause.
You can also use more than one column in the ORDER BY clause.
NOTE: The columns specified in ORDER BY clause should be one of the columns selected in the
SELECT column list.
You can represent the columns in the ORDER BY clause by specifying the position of a column in
the SELECT list, instead of writing the column name.
By default, the ORDER BY Clause sorts data in ascending order. If you want to sort the data in
descending order, you must explicitly specify it as shown below.
The above query sorts only the column 'Lname' in descending order and the column 'Fname' by
ascending order.
If you want to select both Fname and Lname in descending order, the query would be as given
below.
NOTE: Aliases defined in the SELECT Statement can be used in ORDER BY Clause.
The SQL GROUP BY clause is used in collaboration with the SELECT statement to arrange
identical data into groups.
The GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the
ORDER BY clause.
GROUP BY operates on the rows from the FROM clause as filtered by the WHERE clause. It
collects the rows into groups based on common values in the grouping columns. Except nulls,
rows with the same set of values for the grouping columns are placed in the same group. If any
grouping column for a row contains a null, the row is given its own group.
Syntax:
The basic syntax of GROUP BY clause is given below. The GROUP BY clause must follow the
conditions in the WHERE clause and must precede the ORDER BY clause if one is used.
SELECT column1, column2
FROM table_name
WHERE [conditions]
GROUP BY column1, column2
ORDER BY column1, column2
Example
SELECT Fname, Department
FROM student
GROUP BY Department;
The output would be like:
But as you can see from the table one Fname value is left that is Endalew Kassa because you did
not include all select columns in the GROUP BY clause.
NOTE: The GROUP BY clause should contain all the columns in the select list expect those
used along with the group functions. Group functions can appear with select statement as
follows:
The SQL GROUP BY Clause is also used along with the group functions (built-in functions) to
retrieve data grouped according to one or more columns. In Grouping Queries, the select list can
only contain grouping columns, plus literals, outer references and expression involving these
elements. Non-grouping columns from the underlying FROM tables cannot be referenced
directly. However, non-grouping columns can be used in the select list as arguments to Set
Functions. Set Functions summarize columns from the underlying rows of a group.
The WHERE clause places conditions on the selected columns, whereas the HAVING clause places
conditions on groups created by the GROUP BY clause.
The HAVING clause must follow the GROUP BY clause in a query and must also precedes the
ORDER BY clause if used. The following is the syntax of the SELECT statement, including the
HAVING clause:
As we discussed in the select statement WHERE, GROUP BY and HAVING clauses are used
together in a SELECT statement. And when this clauses are used together in a SELECT
statement, the WHERE clause is processed first, then the rows that are returned after the WHERE
clause is executed are grouped based on the GROUP BY clause.
Finally, any conditions on the group functions in the HAVING clauses are applied to the grouped rows
before the final output is displayed.
The percent sign represents zero, one, or multiple characters. The underscore represents a single
number or character. The symbols can be used in combinations
Syntax:
The basic syntax of „%‟ and „_‟ is as follows:
SELECT FROM table_name
WHERE column LIKE 'XXXX%'
or
SELECT FROM table_name
WHERE column LIKE '%XXXX%'
or
SELECT FROM table_name
WHERE column LIKE 'XXXX_'
or
SELECT FROM table_name
WHERE column LIKE '_XXXX'
or
Note: You can combine N number of conditions using AND or OR operators. Here, XXXX
could be any numeric or string value.
Example:
Here are number of examples showing WHERE part having different LIKE clause with '%' and
'_' operators:
The following is an example, which would display all the records from student table where
Fname starts with B:
Create table Wife (Wid int, Wname varchar (10), Wsex char, Wage int, Primary key (Wid));
So will first create a table for Husband, insert some data, then create a separate table for Wife
using the field Wid within the Wife table to insert the primary Wid and form the relationship
between the two tables:
To select or retrieve data jointly from two or more tables we will use join conditions.
The Syntax for joining two tables is:
SELECT col1, col2, col3...
FROM table_name1, table_name2
WHERE table_name1.col2 = table_name2.col1;
So, to get a list of Husbands along with their corresponding Wife you'll need to perform a table
join on Husband. Hid = Wife.Wid for the two tables using a one-to-one relationship like so:
SELECT *
FROM husband, wife
WHERE husband.hid = Wife.wid
ORDER BY husband. hname ASC;
One To Many
In this type of relationship you identify the table representing the many side of the relationship
and add the primary key of the one side table to it.
Example for this cardinality is department to employee. So in this instance many employees belong
to one department therefore we add the field department id to the employee table and perform a
table join on employee.eid = department. did to retrieve employees and their corresponding
department.
So let’s create the department table, insert some records, and create employee table and insert
some records.
Create table department (Did int, Dname varchar (10), Dlocation int, Primary key (Hid));
Create table employee (Eid int, Did int, Ename varchar (10), Esex int, Eage int, Primary key
(Eid));
And finally to get/retrieve a list of employees and their department we perform a table join on
department. did = employee.eid for the two tables using a one-to-many relationship like so:
SELECT *
FROM department, employee
WHERE department. did = employee.eid
Many To Many
A relationship that is multi-valued in both directions is a many-to-many relationship. An
example for this cardinality of relationship is student to course. A student can take more than
one course, and a course can be taken by more than one student. So, this type of relationship is
helped by the use of a linking table student_course (the third table).
So first let's create a table for student and course and then insert some records, then create a
linking table called student_course which will help us join relationships between the two
tables student and course, then insert existing primary id's of both student and their course so we
can make the relationship work:
Create table student (Sid int, Sname varchar (10), Ssex int, Sage char, Primary key (Sid)); Create
table course (Cid int, Ccode int, Cname varchar (10), Ccredit int, Primary key (Cid)); Create table
Finally, to obtain or select a list of departments and what type/number of employees they employed we
perform a table joins Student_Student.Sid = student. Sid
AND Student_Student.Cid = Course.Cid for the three tables using a many-to-many relationship like
so:
SELECT *
FROM student, course, student_course
WHERE student_course.sid = student.sid
AND student_course.cid = course.cid
ORDER BY student. Sname ASC;
SQL Joins are used to relate information in different tables. A Join condition is a part of the SQL
query that retrieves rows from two or more tables. The SQL Joins clause is used to combine
records from two or more tables in a database. A JOIN is a means for combining fields from two
tables by using values common to each. A SQL Join condition is used in the SQL WHERE
Clause of SELECT, UPDATE, DELETE statements.
If a SQL join condition is omitted or if it is invalid the join operation will result in a Cartesian
product. The Cartesian product returns a number of rows equal to the product of all rows in all
the tables being joined. For example, if the first table has 20 rows and the second table has 10
rows, the result will be 20 * 10 or 200 rows. This query takes a long time to execute.
Note: Here, it is noticeable that the join is performed in the WHERE clause. Several operators
can be used to join tables, such as =, <, >, <>, <=, >=, !=, BETWEEN, LIKE, and NOT; they can
all be used to join tables. However, the most common operator is the equal symbol.
Note: we have used one of the type of joint condition that is inner join. But there are a number of
joint conditions.
Inner Join:
All the rows returned by the SQL query satisfy the SQL join condition specified. Returns rows
when there is a match in both tables. The most frequently used and important of the joins is the
INNER JOIN.
The INNER JOIN creates a new result table by combining column values of two tables (table1
and table2) based upon the join-predicate. The query compares each row of table1 with each row
of table2 to find all pairs of rows which satisfy the join-predicate. When the join-predicate is
satisfied, column values for each matched pair of rows of A and B are combined into a result
row.
Syntax:
The basic syntax of INNER JOIN is as follows:
SELECT table1.column1, table2.column2...
FROM table1
INNER JOIN table2
ON table1.common_filed = table2.common_field;
NB: You can leave INNER JOIN word in the above Syntax. Because this condition is implicit in
the where clause as previous one.
LEFT JOIN
The SQL LEFT JOIN returns all rows from the left table, even if there are no matches in the
right table. This means that if the ON clause matches 0 (zero) records in right table, the join will
still return a row in the result, but with NULL in each column from right table.
This means that a left join returns all the values from the left table, plus matched values from the
right table or NULL in case of no matching join predicate.
Syntax:
RIGHT JOIN
The SQL RIGHT JOIN returns all rows from the right table, even if there are no matches in the
left table. This means that if the ON clause matches 0 (zero) records in left table, the join will
still return a row in the result, but with NULL in each column from left table.
This means that a right join returns all the values from the right table, plus matched values from
the left table or NULL in case of no matching join predicate.
Syntax:
The basic syntax of RIGHT JOIN is as follows:
SELECT table1.column1, table2.column2...
FROM table1
RIGHT JOIN table2
ON table1.common_filed = table2.common_field;
FULL JOIN
The SQL FULL JOIN combines the results of both left and right outer joins.
The joined table will contain all records from both tables, and fill in NULLs for missing matches
on either side.
Syntax:
The basic syntax of FULL JOIN is as follows:
SELECT table1.column1, table2.column2...
FROM table1
FULL JOIN table2
ON table1.common_filed = table2.common_field;
CARTESIAN JOIN
The CARTESIAN JOIN or CROSS JOIN returns the Cartesian product of the sets of records
from the two or more joined tables. Thus, it equates to an inner join where the join-condition
always evaluates to True or where the join-condition is absent from the statement.
Syntax:
The basic syntax of INNER JOIN is as follows:
SELECT table1.column1, table2.column2...
FROM table1, table2 [, table3 ]
SQL Views
A VIEW is a virtual table, through which a selective portion of the data from one or more tables
can be seen. Views do not contain data of their own. They are used to restrict access to the
database or to hide data complexity. A view is stored as a SELECT statement in the database.
DML operations on a view like INSERT, UPDATE, DELETE affects the data in the original
table upon which the view is based.
The Syntax to create a SQL view is
CREATE VIEW view_name
AS
SELECT column_list
FROM table_name [WHERE condition];
View_name is the name of the VIEW.
The SELECT statement is used to define the columns and rows that you want to display
in the view.
Note: A view always shows up-to-date data! The database engine recreates the data, using the
view's SQL statement, every time a user queries a view.
For Example: to create a view on the product table the SQL query would be like
CREATE VIEW view_product
AS
SELECT product_id, product_name
FROM product;
Now we want to add the "Category" column to the "Current Product List" view. We will update
the view with the following SQL:
Nested Queries
SQL Subquery
Subquery or Inner query or Nested query is a query in a query. A Subquery is usually added in
the WHERE Clause of the SQL statement. Most of the time, a Subquery is used when you know
how to search for a value using a SELECT statement, but do not know the exact value.
Subqueries are an alternate way of returning data from multiple tables.
Subqueries can be used with the following SQL statements along with the comparisons operators
like =, <, >, >=, <=, IN, BETWEEN etc.
SELECT
INSERT
UPDATE
DELETE
There are a few rules that Subqueries must follow:
Subqueries must be enclosed within parentheses.
A subquery can have only one column in the SELECT clause, unless multiple columns
are in the main query For the subquery to compare its selected columns.
An ORDER BY cannot be used in a subquery, although the main query can use an
ORDER BY. The GROUP BY can be used to perform the same function as the ORDER
BY in a subquery.
Subqueries that return more than one row can only be used with multiple value operators,
such as the IN operator.
The SELECT list cannot include any references to values that evaluate to a BLOB,
ARRAY, CLOB, or NCLOB.
A subquery cannot be immediately enclosed in a set function.
The BETWEEN operator cannot be used with a subquery; however, the BETWEEN
operator can be used within the subquery.
Subqueries with the SELECT Statement:
Subqueries are most frequently used with the SELECT statement. T he basic syntax is as
follows:
SELECT column_name [, column_name ]
FROM table1 [, table2 ]
WHERE column_name OPERATOR
(SELECT column_name [, column_name ]
FROM table1 [, table2 ]
[WHERE])
Example: Consider the CUST OMERS table having the following records:
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
Now, let us check following subquery with SELECT statement:
SQL> SELECT *
FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS
WHERE SALARY > 4500);
Subqueries also can be used with INSERT statements. The INSERT statement uses the data
returned from the subquery to insert into another table. The selected data in the subquery can be
modified with any of the character, date or number functions.
Example: Consider a table CUST OMERS_BKP with similar structure as CUST OMERS table.
Now to copy complete CUST OMERS table into CUST OMERS_BKP, following is the syntax:
SQL> INSERT INTO CUSTOMERS_BKP
SELECT * FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS);
Example: Assuming, we have CUST OMERS_BKP table available which is backup of CUST
OMERS table.
Following example updates SALARY by 0.25 times in CUSTOMERS table for all the customers
whose AGE is greater than or equal to 27:
SQL> UPDATE CUSTOMERS
SET SALARY = SALARY * 0.25
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
WHERE AGE >= 27);
This would impact two rows and finally CUST OMERS table would have the following records:
Example: Assuming, we have CUST OMERS_BKP table available which is backup of CUST
OMERS table.
Following example deletes records from CUST OMERS table for all the customers whose AGE
is greater than or equal to 27:
SQL> DELETE FROM CUSTOMERS
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
This would impact two rows and finally CUST OMERS table would have the following records:
NOTE:
1) You can nest as many queries you want but it is recommended not to nest more than 16
Subqueries in oracle.
2) If a subquery is not dependent on the outer query it is called a non-correlated subquery.
SQL Index
Index in SQL is created on existing tables to retrieve the rows quickly. When there are thousands
of records in a table, retrieving information will take a long time. Therefore indexes are created
on columns which are accessed frequently, so that the information can be retrieved quickly.
Indexes can be created on a single column or a group of columns. When a index is created, it
first sorts the data and then it assigns a ROWID for each row.
Syntax to create Index:
CREATE INDEX index_name
ON table_name (column_name1,column_name2...);
In Oracle there are two types of SQL index namely, implicit and explicit.
Implicit Indexes:
They are created when a column is explicit defined with PRIMARY KEY, UNIQUE KEY
Constraint.
Explicit Indexes:
They are created using the "create index.. " syntax.
NOTE:
1) Even though sql indexes are created to access the rows in the table quickly, they slow down
DML operations like INSERT, UPDATE, DELETE on the table, because the indexes and tables
both are updated along when a DML operation is performed. So use indexes only on columns
which are used to search the table frequently.
2) Is not required to create indexes on table which have less data.
3) In oracle database you can define up to sixteen (16) columns in an INDEX.
SQL COUNT Function - The SQL COUNT aggregate function is used to count the number
of rows in a database table. This function returns the number of rows in the table that satisfies
the condition specified in the WHERE condition. If the WHERE condition is not specified,
then the query returns the total number of rows in the table.
For Example: If you want the number of employees in a particular department, the query
would be:
SELECT COUNT (*) FROM employee
WHERE department = „Computer Science‟;
If you want the total number of employees in all the department, the query would take the
form:
SQL String Functions - Complete list of SQL functions required to manipulate strings in
SQL.
The basic Syntax for creating user using CREATE USER Command is:
Create user “user_name” identified by “Password”
If you are running the code/site accessing MySQL on the same machine, hostname would be
localhost.
NOTE: At this point newuser abebe has no permissions to do anything with the databases. In
fact, if newuser even tries to login (with the password, password), they will not be able to reach
the MySQL shell.
We can also use the SQL command GRANT to both create a new user and to set the needed
privileges at the same time, this is done in the following way:
The basic Syntax for creating user using GRANT Command is:
GRANT usage (Privilege) ON *.* TO „User@hostname‟ IDENTIFIED BY 'password';
The asterisks in this command refer to the database and table (respectively) that they can
access—this specific command allows to the user to perform usages (the tasks) across all the
databases and tables.
Once you have finalized the permissions that you want to set up for your new users, always be
sure to reload all the privileges.
FLUSH PRIVILEGES;
Your changes will now be in effect.
To see the users you have or are created use the following syntax:
SELECT user FROM mysql.user;
o ALL PRIVILEGES- as we saw previously, this would allow a MySQL user all access
to a designated database (or if no database is selected, across the system)
o CREATE- allows them to create new tables or databases
o DROP- allows them to them to delete tables or databases
o DELETE- allows them to delete rows from tables
o INSERT- allows them to insert rows into tables
o SELECT- allows them to use the Select command to read through databases
o UPDATE- allow them to update table rows
o GRANT OPTION- allows them to grant or remove other users' privileges
Object_name is the name of a database object like TABLE, VIEW, STORED PROC and
SEQUENCE.
User_name is the name of the user to whom an access right is being granted.
PUBLIC is used to grant access rights to all users.
ROLES are a set of privileges grouped together.
WITH GRANT OPTION - allows a user to grant access rights to other users.
To provide a specific user with permission, you can use this framework:
GRANT [type of permission] ON [database name].[table name] TO „[username]‟@'localhost‟;
If you want to give them access to any database or to any table, make sure to put an asterisk (*)
in the place of the database name or table name. Each time you update or change a permission
be sure to use the FLUSH PRIVILEGES command.
Example: To create user abebe and to provide all privileges on all database and tables:
If you have the user abebe you can simply provide privilege as follows:
Grant all privileges on *.* to „Abebe‟@‟localhost‟ identified by '123' with grant option;
To create a user abebe and to provide all privilege on all tables of PICE database:
To create a user abebe and assign select privilege on course table of dbstudent database:
Create user 'abebe'@'localhost' identified by '123';
Grant select on dbstudent.course to 'abebe'@'localhost' identified by '123';
To create a user abebe and assign select, insert, delete privileges on course table of dbstudent
database:
To check the privileges for an account or user we can use SHOW GRANTS command:
SHOW GRANTS FOR 'User'@'hostname';
The REVOKE command removes user access rights or privileges to the database objects.
If you need to revoke a permission, the structure is almost identical to granting it:
REVOKE [type of permission] ON [database name]. [Table name] FROM
„[username]‟@„localhost‟;
Example: To remove all privileges on all databases and all tables from user abebe:
REVOKE ALL PRIVILEGES ON *.*
FROM „abebe‟@‟localhost‟;
To remove select privilege on all tables of PICE database from user abebe:
REVOKE SELECT ON PICE.*
FROM „abebe‟@‟localhost‟;
REVOKE SELECT ON PICE FROM user abebe; this command will REVOKE a SELECT
privilege on all tables of PICE database from user abebe. When you REVOKE SELECT
privilege on a database from a user, the user will not be able to SELECT data from that database
tables anymore. However, if the user has received SELECT privileges on that database tables
from more than one user, he/she can SELECT from that database tables until everyone who
granted the permission revokes it. You cannot REVOKE privileges if they were not initially
granted by you.
CREATE object Allows users to create the specified object in their own schema.
CREATE ANY object Allows users to create the specified object in any schema.
The above rules also apply for ALTER and DROP system privileges.
Roles: Roles are a collection of privileges or access rights. When there are many users in a
database it becomes difficult to grant or revoke privileges to users. Therefore, if you define roles,
you can grant or revoke privileges to users, thereby automatically granting or revoking
privileges. You can either create Roles or use the system roles pre-defined by oracle.
Some of the privileges granted to the system roles are as given below:
Creating Roles:
For Example: To create a role called "testing" with password as "pwd", the code will be as
follows:
It's easier to GRANT or REVOKE privileges to the users through a role rather than assigning a
privilege directly to every user. If a role is identified by a password, then, when you GRANT or
REVOKE privileges to the role, you definitely have to identify it with the password.
For example: To grant CREATE TABLE privilege to a user by creating a testing role:
To revoke a CREATE TABLE privilege from testing ROLE, you can write: