0% found this document useful (0 votes)
9 views

3 Basic SQL

Uploaded by

zarryochola
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

3 Basic SQL

Uploaded by

zarryochola
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

What is SQL?

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.

Also, they are using different dialects, such as:

 MS SQL Server using T-SQL,

 Oracle using PL/SQL,

 MS Access version of SQL is called JET SQL (native format) etc.

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.

Following is a simple diagram showing SQL Architecture:


SQL Commands:
The standard SQL commands to interact with relational databases are CREATE, SELECT, INSERT,
UPDATE, DELETE and DROP. These commands can be classified into groups based on their
nature:

DDL - Data Definition Language:


Command Description

CREATE Creates a new table, a view of a table, or other object in database

ALTER Modifies an existing database object, such as a table.

DROP Deletes an entire table, a view of a table or other object in the database.

DML - Data Manipulation Language:


Command Description

SELECT Retrieves certain records from one or more tables

INSERT Creates a record


UPDATE Modifies records

DELETE Deletes records

DCL - Data Control Language:


Command Description

GRANT Gives a privilege to user

REVOKE Takes back privileges granted from user

SQL RDBMS Today


1. MySQL
2. Ms SQL Server
3. Oracle
4. Ms Access

SQL data type is an attribute that specifies type of data of any object. Each column, variable and
expression has related data type in SQL.

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:

Exact Numeric Data Types:


DATA TYPE FROM TO

bigint -9,223,372,036,854,775,808 9,223,372,036,854,775,807

int -2,147,483,648 2,147,483,647

smallint -32,768 32,767

tinyint 0 255

bit 0 1

decimal -10^38 +1 10^38 -1

numeric -10^38 +1 10^38 -1


money -922,337,203,685,477.5808 +922,337,203,685,477.5807

smallmoney -214,748.3648 +214,748.3647

Approximate Numeric Data Types:


DATA TYPE FROM TO

float -1.79E + 308 1.79E + 308

real -3.40E + 38 3.40E + 38

Date and Time Data Types:


DATA TYPE FROM TO

datetime Jan 1, 1753 Dec 31, 9999

smalldatetime Jan 1, 1900 Jun 6, 2079

date Stores a date like June 30, 1991

time Stores a time of day like 12:30 P.M.


Note: Here, datetime has 3.33 milliseconds accuracy where as smalldatetime has 1 minute accuracy.

Character Strings Data Types:


DATA TYPE FROM TO

Maximum length of 8,000 characters.( Fixed length


char char
non-Unicode characters)

Maximum of 8,000 characters.(Variable-length non-


varchar varchar
Unicode data).

Maximum length of 231characters, Variable-length


varchar(max) varchar(max)
non-Unicode data (SQL Server 2005 only).

Variable-length non-Unicode data with a maximum


text text
length of 2,147,483,647 characters.

Unicode Character Strings Data Types:


DATA TYPE Description

nchar Maximum length of 4,000 characters.( Fixed length Unicode)

nvarchar Maximum length of 4,000 characters.(Variable length Unicode)

Maximum length of 231characters (SQL Server 2005 only).( Variable


nvarchar(max)
length Unicode)

Maximum length of 1,073,741,823 characters. ( Variable length


ntext
Unicode )

Binary Data Types:


DATA TYPE Description

binary Maximum length of 8,000 bytes(Fixed-length binary data )

varbinary Maximum length of 8,000 bytes.(Variable length binary data)

Maximum length of 231 bytes (SQL Server 2005 only). ( Variable


varbinary(max)
length Binary data)

Maximum length of 2,147,483,647 bytes. ( Variable length Binary


image
Data)

Misc Data Types:


DATA TYPE Description

Stores values of various SQL Server-supported data types, except text,


sql_variant
ntext, and timestamp.

Stores a database-wide unique number that gets updated every time a


timestamp
row gets updated

uniqueidentifier Stores a globally unique identifier (GUID)

Stores XML data. You can store xml instances in a column or a variable
xml
(SQL Server 2005 only).

cursor Reference to a cursor object

table Stores a result set for later processing

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.

 Arithmetic operators
 Comparison operators
 Logical operators
 Operators used to negate conditions

SQL Arithmetic Operators:


Assume variable a holds 10 and variable b holds 20, then:

Show Examples
Operator Description Example

+ Addition - Adds values on either side of the operator a + b will give 30

Subtraction - Subtracts right hand operand from left hand


- a - b will give -10
operand

Multiplication - Multiplies values on either side of the


* a * b will give 200
operator

/ Division - Divides left hand operand by right hand operand b / a will give 2

Modulus - Divides left hand operand by right hand


% b % a will give 0
operand and returns remainder

SQL Comparison Operators:


Assume variable a holds 10 and variable b holds 20, then:

Show Examples
Operator Description Example

Checks if the values of two operands are equal or not, if yes


= (a = b) is not true.
then condition becomes true.

!= Checks if the values of two operands are equal or not, if (a != b) is true.


values are not equal then condition becomes true.

Checks if the values of two operands are equal or not, if


<> (a <> b) is true.
values are not equal then condition becomes true.

Checks if the value of left operand is greater than the value of


> (a > b) is not true.
right operand, if yes then condition becomes true.

Checks if the value of left operand is less than the value of


< (a < b) is true.
right operand, if yes then condition becomes true.

Checks if the value of left operand is greater than or equal to


>= the value of right operand, if yes then condition becomes (a >= b) is not true.
true.

Checks if the value of left operand is less than or equal to the


<= (a <= b) is true.
value of right operand, if yes then condition becomes true.

Checks if the value of left operand is not less than the value
!< (a !< b) is false.
of right operand, if yes then condition becomes true.

Checks if the value of left operand is not greater than the


!> (a !> b) is true.
value of right operand, if yes then condition becomes true.

SQL Logical Operators:


Here is a list of all the logical operators available in SQL.

Show Examples
Operator Description

ALL The ALL operator is used to compare a value to all values in another value set.

The AND operator allows the existence of multiple conditions in an SQL


AND
statement's WHERE clause.

The ANY operator is used to compare a value to any applicable value in the list
ANY
according to the condition.

BETWEEN The BETWEEN operator is used to search for values that are within a set of
values, given the minimum value and the maximum value.

The EXISTS operator is used to search for the presence of a row in a specified
EXISTS
table that meets certain criteria.

The IN operator is used to compare a value to a list of literal values that have been
IN
specified.

The LIKE operator is used to compare a value to similar values using wildcard
LIKE
operators.

The NOT operator reverses the meaning of the logical operator with which it is
NOT used. Eg: NOT EXISTS, NOT BETWEEN, NOT IN, etc. This is a negate
operator.

The OR operator is used to combine multiple conditions in an SQL statement's


OR
WHERE clause.

IS NULL The NULL operator is used to compare a value with a NULL value.

The UNIQUE operator searches every row of a specified table for uniqueness (no
UNIQUE
duplicates).

SQL CREATE DATABASE

The SQL CREATE DATABASE statement is used to create new SQL database.
Syntax:
Basic syntax of CREATE DATABASE statement is as follows:

CREATE DATABASE DatabaseName;

Always database name should be unique within the RDBMS.

SQL DROP DATABASE

The SQL DROP DATABASE statement is used to drop an existing database in SQL schema.
Syntax:
Basic syntax of DROP DATABASE statement is as follows:
DROP DATABASE DatabaseName;

SQL SELECT DATABASE, USE STATEMENT

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.

The SQL USE statement is used to select any existing database in SQL schema.
Syntax:
Basic syntax of USE statement is as follows:

USE DatabaseName;

SQL CREATE TABLE

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.


Syntax:
Basic syntax of CREATE TABLE statement is as follows:

CREATE TABLE table_name(


column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( one or more columns )
);

SQL DROP TABLE

The SQL DROP TABLE statement is used to remove a table definition and all data, indexes,
triggers, constraints, and permission specifications for that table.
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:
Basic syntax of DROP TABLE statement is as follows:
DROP TABLE table_name;

SQL INSERT QUERY

The SQL INSERT INTO Statement is used to add new rows of data to a table in the database.
Syntax:
There are two basic syntaxes of INSERT INTO statement as follows:

INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)]


VALUES (value1, value2, value3,...valueN);

Here, column1, column2,...columnN are the names of the columns in the table into which you want
to insert data.

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. The SQL INSERT INTO syntax would be as follows:

INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);

SQL SELECT QUERY

SQL SELECT statement is used to fetch the data from a database table which returns data in the
form of result table. These result tables are called result-sets.
Syntax:
The basic syntax of SELECT statement is as follows:

SELECT column1, column2, columnN FROM table_name;

Here, column1, column2...are the fields of a table whose values you want to fetch. If you want to
fetch all the fields available in the field, then you can use the following syntax:

SELECT * FROM table_name;

SQL WHERE CLAUSE

The SQL WHERE clause is used to specify a condition while fetching the data from single table or
joining with multiple tables.
If the given condition is satisfied then only it returns specific value from the table. You would use
WHERE clause to filter the records and fetching only necessary records.

The WHERE clause is not only used in SELECT statement, but it is also used in UPDATE, DELETE
statement, etc., which we would examine in subsequent chapters.

Syntax:
The basic syntax of SELECT statement with WHERE clause is as follows:

SELECT column1, column2, columnN


FROM table_name
WHERE [condition]

You can specify a condition using comparison or logical operators like >, <, =, LIKE, NOT, etc.
Below examples would make this concept clear.

AND OR CLAUSES

The SQL AND and OR operators are used to combine multiple conditions to narrow data in an SQL
statement. These two operators are called conjunctive operators.
These operators provide a means to make multiple comparisons with different operators in the same
SQL statement.

The AND Operator:


The AND operator allows the existence of multiple conditions in an SQL statement's WHERE
clause.
Syntax:
The basic syntax of AND operator with WHERE clause is as follows:

SELECT column1, column2, columnN


FROM table_name
WHERE [condition1] AND [condition2]...AND [conditionN];

UPDATE QUERY

The SQL UPDATE Query is used to modify the existing records in a table.
You can use WHERE clause with UPDATE query to update selected rows otherwise all the rows
would be affected.
Syntax:
The basic syntax of UPDATE query with WHERE clause is as follows:

UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];

SQL DELETE QUERY

The SQL DELETE Query is used to delete the existing records from a table.
You can use WHERE clause with DELETE query to delete selected rows, otherwise all the records
would be deleted.

Syntax:
The basic syntax of DELETE query with WHERE clause is as follows:

DELETE FROM table_name


WHERE [condition];

SQL LIKE CLAUSE

The SQL LIKE clause is used to compare a value to similar values using wildcard operators. There
are two wildcards used in conjunction with the LIKE operator:
 The percent sign (%)

 The underscore (_)

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

SELECT FROM table_name


WHERE column LIKE '_XXXX_

SQL TOP CLAUSE

The SQL TOP clause is used to fetch a TOP N number or X percent records from a table.
Note: All the databases do not support TOP clause. For example MySQL supports LIMIT clause to
fetch limited number of records and Oracle uses ROWNUM to fetch limited number of records.
Syntax:
The basic syntax of TOP clause with SELECT statement would be as follows:

SELECT TOP number|percent column_name(s)


FROM table_name
WHERE [condition]

Example:
Consider the CUSTOMERS table having the following records:

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | 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 |
+----+----------+-----+-----------+----------+

Following is an example on SQL server, which would fetch top 3 records from CUSTOMERS table:

SQL> SELECT TOP 3 * FROM CUSTOMERS;

This would produce the following result:

+----+---------+-----+-----------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+---------+-----+-----------+---------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
+----+---------+-----+-----------+---------+

If you are using MySQL server, then here is an equivalent example:

SQL> SELECT * FROM CUSTOMERS


LIMIT 3;

This would produce the following result:

+----+---------+-----+-----------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+---------+-----+-----------+---------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
+----+---------+-----+-----------+---------+

If you are using Oracle server, then here is an equivalent example:

SQL> SELECT * FROM CUSTOMERS


WHERE ROWNUM <= 3;

This would produce the following result:

+----+---------+-----+-----------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+---------+-----+-----------+---------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
+----+---------+-----+-----------+---------+

SQL ORDER BY CLAUSE

The SQL ORDER BY clause is used to sort the data in ascending or descending order, based on one
or more columns. Some database sorts query results in ascending order by default.
Syntax:
The basic syntax of ORDER BY clause is as follows:

SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];

SQL GROUP 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.
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

SQL DISTINCT KEYWORD

The SQL DISTINCT keyword is used in conjunction with SELECT statement to eliminate all the
duplicate records and fetching only unique records.
There may be a situation when you have multiple duplicate records in a table. While fetching such
records, it makes more sense to fetch only unique records instead of fetching duplicate records.

Syntax:
The basic syntax of DISTINCT keyword to eliminate duplicate records is as follows:

SELECT DISTINCT column1, column2,.....columnN


FROM table_name
WHERE [condition]

SQL SORTING RESULTS

The SQL ORDER BY clause is used to sort the data in ascending or descending order, based on one
or more columns. Some database sorts query results in ascending order by default.
Syntax:
The basic syntax of ORDER BY clause which would be used to sort result in ascending or
descending order is as follows:

SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];

You can use more than one column in the ORDER BY clause. Make sure whatever column you are
using to sort, that column should be in column-list.

You might also like