0% found this document useful (0 votes)
3 views36 pages

Mysql Notesdsfsdf

A Database Management System (DBMS) is software that manages data storage, retrieval, and security, facilitating data organization and manipulation. It can be classified into various types, including hierarchical, network, relational, and object-oriented DBMS, with relational DBMS (RDBMS) being the most common. SQL is the standard language used for managing and manipulating databases, allowing users to define, manipulate, and control data effectively.

Uploaded by

sandhyadevit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views36 pages

Mysql Notesdsfsdf

A Database Management System (DBMS) is software that manages data storage, retrieval, and security, facilitating data organization and manipulation. It can be classified into various types, including hierarchical, network, relational, and object-oriented DBMS, with relational DBMS (RDBMS) being the most common. SQL is the standard language used for managing and manipulating databases, allowing users to define, manipulate, and control data effectively.

Uploaded by

sandhyadevit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 36

Database Management System (DBMS)

A Database Management System (DBMS) is software that interacts with end-users, applications, and the
database itself to capture and analyze data. It manages data, the database engine, and the database
schema to facilitate the organization and manipulation of data.
A database is an organized collection of data. It is considered as a container of information.
In the manual system, you would maintain several files with different bits of information while in the
computerized system you would use database programs such as Microsoft Access, OpenOffice.org Base,
and MySQL, to organize the data as per your business need.
Database Management System :
A database management system is a software package with computer programs that controls the
creation, maintenance, and use of a database. for example Oracle, IBM DB2, Microsoft SQL Server,
Microsoft Access, PostgreSQL, MySQL, FoxPro, and SQLite.
Data can be organized into two types:
1. Flat File : Data is stored in a single table. Usually suitable for less amount of data.
2. Relational : Data is stored in multiple tables and the tables are linked using a common field.
Relational is suitable for medium to large amount of data.

Functions of a DBMS
 Data Storage, Retrieval, and Update: Manages how data is stored, retrieved, and updated.
 User Administration: Controls user access to the database.
 Data Integrity and Security: Ensures data integrity and security.
 Backup and Recovery: Provides tools for backing up and restoring data.
Note
DBMS ensures that data is consistently organized and remains easily accessible.
Types of DBMS
1. Hierarchical DBMS: Data is organized in a tree-like structure.
2. Network DBMS: Data is organized in a graph, allowing many-to-many relationships.
3. Relational DBMS (RDBMS): Data is organized in tables (relations). Examples include MySQL, PostgreSQL.
4. Object-Oriented DBMS: Data is stored in objects, similar to object-oriented programming.
Example
Example of RDBMS: Consider a school database system where data about students, teachers, and
classes are stored in tables. Each table has rows and columns representing different attributes.

Database Servers :
Database servers are dedicated computers that hold the actual databases and run only the DBMS and
related software.
Advantages of Database :
1) Reduces Data Redundancy : Database reduces data redundancy (duplication of data)
2) Sharing of Data : In a database, the users of the database can share the data among themselves.
3) Data Integrity : Data integrity means that the data is accurate and consistent in the database.
4) Data Security : Database provides data security as only authorized users are allowed to access the
database and their identity are authenticated by using a username and password.
5) Privacy : The privacy rule in a database states that only the authorized users can access a database
according to its privacy constraints.
6) Backup and Recovery : Database Management System automatically takes care of backup and
recovery.
Some key features of a database:
1) A database can have one or many tables.
2) Each table in a database contains information about one type of item.
3) Every table has a key field which ensures that there are 100% unique values throughout the database.
Relational DataBase Management System(RDBMS): A Database Management System that conforms at-
least half of the 12 rules defined by Dr. E.F. Codd (1970) in his research document. In a relational data
model, the data is organized into tables (i.e. Rows and Columns). These tables are called Relations. A
row in a table represents a relationship among a set of values. Since table is a collection of relationships
it is generally referred to using the mathematical term Relation.
Database Systems: Systems comprising of Databases and Database Management Systems are simply
referred as database systems.
Advantages of Data Base System:
1) Reduce data redundancy (duplication of data).
2) Control data inconsistency to a large extent.
3) Database facilitate sharing of data.
4) Enforce standards.
5) Centralized databases can ensure data security.

Examples of Common Database Management Systems: MySQL ,INGRES, POSTGRES, ORACLE, DB2.

Levels of Database Implementation:


1. Internal Level (Physical Level): It describes how the data are actually stored on the storage media.
2. Conceptual Level: It describes what data are actually stored in the database. It also describes the
relationships existing among data.
3. External Level (View Level): It is closest to the users and is concerned with the way in which the data
are viewed by individual users.
Normalization
Normalization is the process of organizing data in a database to reduce redundancy and improve data
integrity.
Normal Forms
1. First Normal Form (1NF): Ensures that the table has no repeating groups of data.
2. Second Normal Form (2NF): Ensures that the table is in 1NF and all non-key attributes are fully
functional dependent on the primary key.
3. Third Normal Form (3NF): Ensures that the table is in 2NF and all the attributes are functionally
dependent only on the primary key.
4. Boyce-Codd Normal Form (BCNF): BCNF is a stricter form of 3NF that ensures that each
determinant in a table is a candidate key. In other words, BCNF ensures that each non-key
attribute is dependent only on the candidate key.

Data Model: A way by which data structures and their relationships are analyzed.
Different Data Models:
1. Relational data model
2. Network data model
3. Hierarchical data model
Relational data model: In this model data is organized into tabular structures called relations. A
database may contain many relations providing a better classification of data based on its nature and
use. Multiple relations are then linked/ associated together on some common key data values (foreign
key).
Network Data Model: In this model data is represented by collections of records and relationships
among data are represented by links. A record is collection of fields i.e. attributes, each of which
contents only one data value.
Hierarchical data model: In this model records are organized as trees, data is represented by collection
of records connected to one another through links.
Basics of Relational Model Relation: A tabular structure containing data. To be a relation it must satisfy
following four conditions:
■ Atomicity: At every row-column intersection (Cell) there must be an atomic value i.e. a value that can
not be further subdivided.
■ No duplicity: No two rows of relation will be identical i.e. in any two rows value in at least one column
must be different.
■ Ordering of rows is immaterial.
■ Ordering of columns is immaterial.

Important Terms :

Table/Relation
Everything in a relational database is stored in the form of relations. The RDBMS database uses tables to
store data. A table is a collection of related data entries and contains rows and columns to store data.
Each table represents some real-world objects such as person, place, or event about which information
is collected. The organized collection of data into a relational table is known as the logical view of the
database.
Properties of a Relation:
 Each relation has a unique name by which it is identified in the database.
 Relation does not contain duplicate tuples.
 The tuples of a relation have no specific order.
 All attributes in a relation are atomic, i.e., each cell of a relation contains exactly one value.
Properties of a row:
 No two tuples are identical to each other in all their entries.
 All tuples of the relation have the same format and the same number of entries.
 The order of the tuple is irrelevant. They are identified by their content, not by their position.
column/attribute
A column is a vertical entity in the table which contains all information associated with a specific field in
a table.
Properties of an Attribute:
 Every attribute of a relation must have a name.
 Null values are permitted for the attributes.
 Default values can be specified for an attribute automatically inserted if no other value is
specified for an attribute.
 Attributes that uniquely identify each tuple of a relation are the primary key.
data item/Cells
The smallest unit of data in the table is the individual data item. It is stored at the intersection of tuples
and attributes.
Properties of data items:
 Data items are atomic.
 The data items for an attribute should be drawn from the same domain.
Degree:
The total number of attributes that comprise a relation is known as the degree of the table.
Cardinality:
The total number of tuples at any one time in a relation is known as the table's cardinality. The relation
whose cardinality is 0 is called an empty table.
Domain:
The domain refers to the possible values each attribute can contain. It can be specified using standard
data types such as integers, floating numbers, etc. For example, An attribute entitled Marital_Status
may be limited to married or unmarried values.
NULL Values
The NULL value of the table specifies that the field has been left blank during record creation. It is
different from the value filled with zero or a field that contains space.
Data Integrity
There are the following categories of data integrity exist with each RDBMS:
Entity integrity: It specifies that there should be no duplicate rows in a table.
Domain integrity: It enforces valid entries for a given column by restricting the type, the format, or the
range of values.
Referential integrity specifies that rows cannot be deleted, which are used by other records.
User-defined integrity: It enforces some specific business rules defined by users. These rules are
different from the entity, domain, or referential integrity.
1) Primary Key : A primary key is a unique value that identifies a row in a table. It helps the database to
search for a record.
2) Composite Primary Key : When primary key constraint is applied on one or more columns then it is
known as Composite Primary Key.
3) Foreign key : The foreign key identifies a column or set of columns in one (referencing) table that
refers to a column or set of columns in another (referenced) table.

Tuple: A row in a relation is called a tuple.


Attribute: A column in a relation is called an attribute.
Domain: Domain of an attribute refers to the set of all the possible values for that attribute.
Candidate Key: A set of one or more minimal attributes used to uniquely identify a tuple in the relation
and which can act as Primary Key. A relation can have multiple candidate keys.
Alternate Key: Candidate keys that not chosen as primary key are the alternate keys.
Difference between DBMS and RDBMS
Although DBMS and RDBMS both are used to store information in physical database but there are some
remarkable differences between them.
The main differences between DBMS and RDBMS are given below:
No. DBMS RDBMS
1) DBMS applications store data as file. RDBMS applications store data in a tabular form.
In DBMS, data is generally stored in
In RDBMS, the tables have an identifier called primary key
2) either a hierarchical form or a
and the data values are stored in the form of tables.
navigational form.
3) Normalization is not present in DBMS. Normalization is present in RDBMS.
4) DBMS does not apply any security with RDBMS defines the integrity constraint for the purpose of
ACID (Atomocity, Consistency, Isolation and Durability)
regards to data manipulation.
property.
DBMS uses file system to store data, so in RDBMS, data values are stored in the form of tables, so
5) there will be no relation between the a relationship between these data values will be stored in
tables. the form of a table as well.
DBMS has to provide some uniform RDBMS system supports a tabular structure of the data
6) methods to access the stored and a relationship between them to access the stored
information. information.
DBMS does not support distributed
7) RDBMS supports distributed database.
database.
DBMS is meant to be for small
RDBMS is designed to handle large amount of data. it
8) organization and deal with small data. it
supports multiple users.
supports single user.
Examples of DBMS are file systems, xml Example of RDBMS are mysql, postgre, sql server, oracle
9)
etc. etc.

Structured Query Language (SQL)


SQL is a standard programming language specifically designed for managing and manipulating
databases. It is used to perform various operations on data stored in a relational database.
SQL Commands
SQL commands can be classified into the following:
Data Definition Language (DDL): A database scheme is defined by set of definitions, which are
expressed, by a special set of commands called Data Definition Language (DDL). They are used to create
tables, databases, identify data items, provide unique names to the data items and to define the length
and provide the range of values that each data item can assume. They are CREATE TABLE, ALTER TABLE
and DROP TABLE commands.

Data Manipulation Language (DML): The data manipulation language (DML) handles operations such as
entering rows into a table, changing data, deleting rows, and extracting data from rows and tables. With
DML, one does not change the table’s structure, but rather its contents. It contains commands like
INSERT, UPDATE and DELETE.

Transaction Control Language (TCL): A transaction is a one complete unit of work. A transaction is
successfully completed if and only if all its constituent steps are successfully completed. To manage and
control the transactions, the transaction control commands are used. e.g. COMMIT, ROLLBACK,
SAVEPOINT.

INTRODUCTION TO MYSQL
MySQL: It is an Open Source RDBMS Software that uses Structured Query Language. It is available free
of cost. Key Features of MySQL:
1. High Speed.
2. Ease of Use.
3. Available Free of Cost.
4. Supports standards based SQL.
5. Provides portability.
6. High Security.
7. Provides many data types.
8. Handles large database.

MySQL Data Types: Every column (or data item) should belong to a unique domain (known as data
type). These data types help to describe the kind of information a particular column holds. MySQL
supports the ANSI SQL data types. Some of the commonly used data types along with their
characteristics are as follows:

Data Types :
Datatypes are used to identify which type of data (value) we are going to store in the database. Data
types in OpenOffice base are broadly classified into five categories listed below.
1. Numeric Types
2. Alphanumeric Types
3. Binary Types
4. Date time
5. Other Variable types
Numeric Types :
Numeric data types in a database can be used for storing information such as mobile number, roll
number, door number etc. The different types of numeric data types available are listed here.

Alphanumeric Types :
This data type is used to store information which has alphabets as well as numbers for example address,
book summary field etc. The different types of Alphanumeric Types available are listed here.
Binary Types :
Binary data types are used for storing data in binary formats. Binary data types in a database can be
using for storing photos, music files, etc.
DATE TIME :
Date time data types in a database can be used for storing information such as date of birth, date of
admission, date of product sale, etc.

WORKING WITH SQL


To work on MySQL, you need to open or create the database first:
To Create/Open Database:
mysql> CREATE DATABASE <name of database>;
Now the database with the given name will be created. One must be connected to the database before
using it, as below:
mysql> use <name of database>;

Creating Tables
Tables are defined with the CREATE TABLE command. When tables are created its columns are named,
data types and sizes supplied for each column. At least one column must be specified.
Syntax:
CREATE TABLE <TableName>(<ColumnName1> <Data Type1>,
<ColumnName2> <Data Type2>,…….,<ColumnNameN> <Data Type N>);
Example:
mysql> CREATE TABLE Students
(
RollNo DECIMAL(3),
Name VARCHAR(25)
);
Once the table is created we can insert the record in it, edit or delete existing records, and also we can
search for desired record in a very comprehensive way using the SQL Select statement.
Creating tables with SQL Constraints:
^ A Constraint is a condition or check applicable on a field or set of fields.
^ Data constraints are the rules that are defined when a table is created.
^ They can also be defined or modified after creating the tables.
^ When constraints are defined any data entering in the table is first checked to satisfy the condition
specified in particular constraint if it is, only then table data can be updated. If data updation/ insertion
is violating the defined constraints, database rejects the data (entire record is rejected).
^ When a constraint is applied to a single column, it is called a column level constraint but if a constraint
is applied on a combination of columns it is called a table constraint.
Following Constraints can be defined on a table in SQL:
Constraints name Description

PRIMARY KEY Used to create a primary key.

UNIQUE to create a unique key.


NOT NULL to define that column will not accept null values.

FOREIGN KEY/ REFERENCES to define referential integrity with another table.

DEFAULT to define the columns default value.

CHECK to define the custom rule.


Not Null and Default constraints can be applied only at column level rest all constraints can be applied
on both column level and table levels.

SQL Commands: Constraints Used In Database

Constraints are used in a database to specify the rules for data in a table. The following are the different
types of constraints:

 NOT NULL
 UNIQUE
 CHECK
 DEFAULT
 INDEX

NOT NULL

This constraint ensures that a column cannot have a NULL value.

Example

1 --NOT NULL on Create Table

3 CREATE TABLE Employee_Info

4 (

5 EmployeeID int NOT NULL,

6 EmployeeName varchar(255) NOT NULL,

7 Emergency ContactName varchar(255),

8 PhoneNumber int NOT NULL,

9 Address varchar(255),
10 City varchar(255),

11 Country varchar(255)

12 );

13

14 --NOT NULL on ALTER TABLE

15

16 ALTER TABLE Employee_Info

17 MODIFY PhoneNumber int NOT NULL;

UNIQUE

This constraint ensures that all the values in a column are unique.

Example

1 --UNIQUE on Create Table

3 CREATE TABLE Employee_Info

4 (

5 EmployeeID int NOT NULL UNIQUE,

6 EmployeeName varchar(255) NOT NULL,

7 Emergency ContactName varchar(255),

8 PhoneNumber int NOT NULL,

9 Address varchar(255),

10 City varchar(255),

11 Country varchar(255)

12 );

13
14 --UNIQUE on Multiple Columns

15

16 CREATE TABLE Employee_Info

17 (

18 EmployeeID int NOT NULL,

19 EmployeeName varchar(255) NOT NULL,

20 Emergency ContactName varchar(255),

21 PhoneNumber int NOT NULL,

22 Address varchar(255),

23 City varchar(255),

24 Country varchar(255),

25 CONSTRAINT UC_Employee_Info UNIQUE(Employee_ID, PhoneNumber)

26 );

27

28 --UNIQUE on ALTER TABLE

29

30 ALTER TABLE Employee_Info

31 ADD UNIQUE (Employee_ID);

32

33 --To drop a UNIQUE constraint

34

35 ALTER TABLE Employee_Info

36 DROP CONSTRAINT UC_Employee_Info;

CHECK

This constraint ensures that all the values in a column satisfy a specific condition.
Example

1 --CHECK Constraint on CREATE TABLE

3 CREATE TABLE Employee_Info

4 (

5 EmployeeID int NOT NULL,

6 EmployeeName varchar(255),

7 Emergency ContactName varchar(255),

8 PhoneNumber int,

9 Address varchar(255),

10 City varchar(255),

11 Country varchar(255) CHECK (Country=='India')

12 );

13

14 --CHECK Constraint on multiple columns

15

16 CREATE TABLE Employee_Info

17 (

18 EmployeeID int NOT NULL,

19 EmployeeName varchar(255),

20 Emergency ContactName varchar(255),

21 PhoneNumber int,

22 Address varchar(255),

23 City varchar(255),

24 Country varchar(255) CHECK (Country = 'India' AND Cite = 'Hyderabad')


25 );

26

27 --CHECK Constraint on ALTER TABLE

28

29 ALTER TABLE Employee_Info

30 ADD CHECK (Country=='India');

31

32 --To give a name to the CHECK Constraint

33

34 ALTER TABLE Employee_Info

35 ADD CONSTRAINT CheckConstraintName CHECK (Country=='India');

36

37 --To drop a CHECK Constraint

38

39 ALTER TABLE Employee_Info

40 DROP CONSTRAINT CheckConstraintName;

DEFAULT

This constraint consists of a set of default values for a column when no value is specified.

Example

1 --DEFAULT Constraint on CREATE TABLE

3 CREATE TABLE Employee_Info

4 (

5 EmployeeID int NOT NULL,


6 EmployeeName varchar(255),

7 Emergency ContactName varchar(255),

8 PhoneNumber int,

9 Address varchar(255),

10 City varchar(255),

11 Country varchar(255) DEFAULT 'India'

12 );

13

14 --DEFAULT Constraint on ALTER TABLE

15

16 ALTER TABLE Employee_Info

17 ADD CONSTRAINT defau_Country

18 DEFAULT 'India' FOR Country;

19

20 --To drop the Default Constraint

21

22 ALTER TABLE Employee_Info

23 ALTER COLUMN Country DROP DEFAULT;

INDEX

This constraint is used to create indexes in the table, through which you can create and retrieve data
from the database very quickly.

Syntax

--Create an Index where duplicate values are allowed


CREATE INDEX IndexName
ON TableName (Column1, Column2, ...ColumnN);

--Create an Index where duplicate values are not allowed


CREATE UNIQUE INDEX IndexName
ON TableName (Column1, Column2, ...ColumnN);
Example

1 CREATE INDEX idex_EmployeeName

2 ON Persons (EmployeeName);

4 --To delete an index in a table

6 DROP INDEX Employee_Info.idex_EmployeeName;

Now, let us look into the next part of this article i.e. DML Commands.

Upcoming Batches For Microsoft SQL Server Training Certification Course Online

Course Name Date Details

Class Starts on 22nd


Microsoft SQL Server Training Certification View
February,2025
Course Online Details
SAT&SUN (Weekend Batch)

DML commands in SQL

This section of the article will give you an insight into the commands through which you can manipulate
the database. The commands are as follows:


 USE
 INSERT INTO
 UPDATE
 DELETE
 SELECT

Apart from these commands, there are also other manipulative operators/functions such as:


 Operators
 Aggregate Functions
 NULL Functions
 Aliases & Case Statement

USE
The USE statement is used to select the database on which you want to perform operations.

Syntax

USE DatabaseName;
Example

1 USE Employee;

INSERT INTO

This statement is used to insert new records into the table.

Syntax

INSERT INTO TableName (Column1, Column2, Column3, ...,ColumnN)


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

--If you don't want to mention the column names then use the below syntax

INSERT INTO TableName


VALUES (Value1, Value2, Value3, ...);
Example

1 INSERT INTO Employee_Info(EmployeeID, EmployeeName, Emergency ContactName, PhoneNumber, Addres

2 VALUES ('06', 'Sanjana','Jagannath', '9921321141', 'Camel Street House No 12', 'Chennai', 'India

4 INSERT INTO Employee_Info

5 VALUES ('07', 'Sayantini','Praveen', '9934567654', 'Nice Road 21', 'Pune', 'India');

UPDATE

This statement is used to modify the records already present in the table.

Syntax

UPDATE TableName
SET Column1 = Value1, Column2 = Value2, ...
WHERE Condition;
Example
1 UPDATE Employee_Info

2 SET EmployeeName = 'Aahana', City= 'Ahmedabad'

3 WHERE EmployeeID = 1;

DELETE

This statement is used to delete the existing records in a table.

Syntax

DELETE FROM TableName WHERE Condition;


Example

1 DELETE FROM Employee_Info

2 WHERE EmployeeName='Preeti';

SELECT

This statement is used to select data from a database and the data returned is stored in a result table,
called the result-set.

Syntax

SELECT Column1, Column2, ...ColumN


FROM TableName;

--(*) is used to select all from the table


SELECT * FROM table_name;

-- To select the number of records to return use:


SELECT TOP 3 * FROM TableName;
Example

1 SELECT EmployeeID, EmployeeName

2 FROM Employee_Info;

4 --(*) is used to select all from the table

5 SELECT * FROM Employee_Info;


6

7 -- To select the number of records to return use:

8 SELECT TOP 3 * FROM Employee_Info;

Apart from just using the SELECT keyword individually, you can use the following keywords with the
SELECT statement:


 DISTINCT
 ORDER BY
 GROUP BY
 HAVING Clause
 INTO

The ‘SELECT DISTINCT’ Statement

This statement is used to return only different values.

Syntax
SELECT DISTINCT Column1, Column2, ...ColumnN
FROM TableName;
Example
1 SELECT DISTINCT PhoneNumber FROM Employee_Info;

The ‘ORDER BY’ Statement

The ‘ORDER BY’ statement is used to sort the required results in ascending or descending order. The
results are sorted in ascending order by default. Yet, if you wish to get the required results in descending
order, you have to use the DESC keyword.

Syntax
SELECT Column1, Column2, ...ColumnN
FROM TableName
ORDER BY Column1, Column2, ... ASC|DESC;
Example
1 -- Select all employees from the 'Employee_Info' table sorted by EmergencyCon

2 SELECT * FROM Employee_Info

3 ORDER BY EmergencyContactName;

5 -- Select all employees from the 'Employee_Info' table sorted by EmergencyContactName


SELECT * FROM Employee_Info
6
ORDER BY EmergencyContactName DESC;
7

8
-- Select all employees from the 'Employee_Info' table sorted by EmergencyContactName
9
SELECT * FROM Employee_Info
10
ORDER BY EmergencyContactName, EmployeeName;
11

12
/* Select all employees from the 'Employee_Info' table sorted by EmergencyContactName in Descending or
13
order: */
14
SELECT * FROM Employee_Info
15
ORDER BY EmergencyContactName ASC, EmployeeName DESC;

Find out our MS SQL Course in Top Cities

India India

SQL Training in Bangalore SQL Course in Pune

SQL Training in Chennai SQL Course in Mumbai

SQL Training in
SQL Course in Kolkata
hyderabad

The ‘GROUP BY’ Statement

This ‘GROUP BY’ statement is used with the aggregate functions to group the result-set by one or more
columns.

Syntax
SELECT Column1, Column2,..., ColumnN
FROM TableName
WHERE Condition
GROUP BY ColumnName(s)
ORDER BY ColumnName(s);
Example
1 -- To list the number of employees from each city.

2
3 SELECT COUNT(EmployeeID), City

4 FROM Employee_Info

5 GROUP BY City;

The ‘HAVING’ Clause

The ‘HAVING’ clause is used in SQL because the WHERE keyword cannot be used everywhere.

Syntax
SELECT ColumnName(s)
FROM TableName
WHERE Condition
GROUP BY ColumnName(s)
HAVING Condition
ORDER BY ColumnName(s);
Example
/* To list the number of employees in each city. The employees should be sorted high to low and only thos
1
more than 5 employees:*/
2

3
SELECT COUNT(EmployeeID), City
4
FROM Employee_Info
5
GROUP BY City
6
HAVING COUNT(EmployeeID) > 2
7
ORDER BY COUNT(EmployeeID) DESC;

The ‘SELECT INTO’ Statement

The ‘SELECT INTO’ statement is used to copy data from one table to another.

Syntax
SELECT *
INTO NewTable [IN ExternalDB]
FROM OldTable
WHERE Condition;
Example
1 -- To create a backup of database 'Employee'

2 SELECT * INTO EmployeeBackup

3 FROM Employee;
4

5 --To select only few columns from Employee

6 SELECT EmployeeName, PhoneNumber INTO EmployeeContactDetails

7 FROM Employee;

9 SELECT * INTO BlrEmployee

10 FROM Employee

11 WHERE City = 'Bangalore';

Now, as I mentioned before, let us move onto our next section in this article on SQL Commands, i.e. the
Operators.

Operators in SQL

The different set of operators available in SQL are as follows:

Let us look into each one of them, one by one.

Arithmetic Operators

Operator Description

% Modulous [A % B]
/ Division [A / B]

* Multiplication [A * B]

– Subtraction [A – B]

+ Addition [A + B]

Bitwise Operators

Operator Description

^ Bitwise Exclusive OR (XOR) [A ^ B]

| Bitwise OR [A | B]

& Bitwise AND [A & B]

Comparison Operators

Operator Description

<> Not Equal to [A < > B]

<= Less than or equal to [A <= B]

>= Greater than or equal to [A >= B]

< Less than [A < B]

> Greater than [A > B]

= Equal to [A = B]

Compound Operators

Operator Description

|*= Bitwise OR equals [A |*= B]

^-= Bitwise Exclusive equals [A ^-= B]

&= Bitwise AND equals [A &= B]

%= Modulo equals [A %= B]

/= Divide equals [A /= B]
*= Multiply equals [A*= B]

-= Subtract equals [A-= B]

+= Add equals [A+= B]

Logical Operators

The Logical operators present in SQL are as follows:


 AND
 OR
 NOT
 BETWEEN
 LIKE
 IN
 EXISTS
 ALL
 ANY

AND Operator
This operator is used to filter records that rely on more than one condition. This operator displays the
records, which satisfy all the conditions separated by AND, and give the output TRUE.

Syntax

SELECT Column1, Column2, ..., ColumnN


FROM TableName
WHERE Condition1 AND Condition2 AND Condition3 ...;
Example

1 SELECT * FROM Employee_Info

2 WHERE City='Mumbai' AND City='Hyderabad';</pre>

OR Operator
This operator displays all those records which satisfy any of the conditions separated by OR and give the
output TRUE.

Syntax

SELECT Column1, Column2, ..., ColumnN


FROM TableName
WHERE Condition1 OR Condition2 OR Condition3 ...;
Example
1 SELECT * FROM Employee_Info

2 WHERE City='Mumbai' OR City='Hyderabad';

NOT Operator
The NOT operator is used, when you want to display the records which do not satisfy a condition.

Syntax

SELECT Column1, Column2, ..., ColumnN


FROM TableName
WHERE NOT Condition;
Example

1 SELECT * FROM Employee_Info

2 WHERE NOT City='Mumbai';

NOTE: You can also combine the above three operators and write a query as follows:

1 SELECT * FROM Employee_Info

2 WHERE NOT Country='India' AND (City='Bangalore' OR City='Hyderabad');

NOTE: You can also combine the above three operators and write a query as follows:

1 SELECT * FROM Employee_Info

2 WHERE NOT Country='India' AND (City='Bangalore' OR City='Hyderabad');

BETWEEN Operator
The BETWEEN operator is used, when you want to select values within a given range. Since this is an
inclusive operator, both the starting and ending values are considered.

Syntax

SELECT ColumnName(s)
FROM TableName
WHERE ColumnName BETWEEN Value1 AND Value2;
Example

1 SELECT * FROM Employee_Salary

2 WHERE Salary BETWEEN 40000 AND 50000;

LIKE Operator
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column of a table.
There are mainly two wildcards that are used in conjunction with the LIKE operator:
 % – It matches 0 or more character.
 _ – It matches exactly one character.

Syntax

SELECT ColumnName(s)
FROM TableName
WHERE ColumnName LIKE pattern;
Refer to the following table for the various patterns that you can mention with the LIKE operator.

Like Operator Condition Description

WHERE CustomerName LIKE ‘v% Finds any values that start with “v”

WHERE CustomerName LIKE ‘%v’ Finds any values that end with “v”

WHERE CustomerName LIKE ‘%and%’ Finds any values that have “and” in any position

Finds any values that have “q” in the second


WHERE CustomerName LIKE ‘_q%’
position.

Finds any values that start with “u” and are at


WHERE CustomerName LIKE ‘u_%_%’
least 3 characters in length

Finds any values that start with “m” and end


WHERE ContactName LIKE ‘m%a’
with “a”

Example

1 SELECT * FROM Employee_Info

2 WHERE EmployeeName LIKE 'S%';

IN Operator
This operator is used for multiple OR conditions. This allows you to specify multiple values in a WHERE
clause.

Syntax

SELECT ColumnName(s)
FROM TableName
WHERE ColumnName IN (Value1,Value2...);
Example

1 SELECT * FROM Employee_Info

2 WHERE City IN ('Mumbai', 'Bangalore', 'Hyderabad');


NOTE: You can also use IN while writing Nested Queries.

EXISTS Operator
The EXISTS operator is used to test if a record exists or not.

Syntax

SELECT ColumnName(s)
FROM TableName
WHERE EXISTS
(SELECT ColumnName FROM TableName WHERE condition);
Example

1 SELECT EmergencyContactName

2 FROM Employee_Info

3 WHERE EXISTS (SELECT EmergencyContactName FROM Employee_Info WHERE EmployeeId = 05 AND City = 'K

ALL Operator
The ALL operator is used with a WHERE or HAVING clause and returns TRUE if all of the subquery values
meet the condition.

Syntax

SELECT ColumnName(s)
FROM TableName
WHERE ColumnName operator ALL
(SELECT ColumnName FROM TableName WHERE condition);
Example

1 SELECT EmployeeName

2 FROM Employee_Info

3 WHERE EmployeeID = ALL (SELECT EmployeeID FROM Employee_Info WHERE City = 'Hyderabad');

ANY Operator
Similar to the ALL operator, the ANY operator is also used with a WHERE or HAVING clause and returns
true if any of the subquery values meet the condition.

Syntax

SELECT ColumnName(s)
FROM TableName
WHERE ColumnName operator ANY
(SELECT ColumnName FROM TableName WHERE condition);
Example
1 SELECT EmployeeName

2 FROM Employee_Info

3 WHERE EmployeeID = ANY (SELECT EmployeeID FROM Employee_Info WHERE City = 'Hyderabad' OR City =

Next, in this article on SQL Commands, let us look into the various Aggregate Functions provided in SQL.

Aggregate Functions

This section of the article will include the following functions:


 MIN()
 MAX()
 COUNT()
 SUM()
 AVG()

MIN() Function

The MIN function returns the smallest value of the selected column in a table.

Syntax
SELECT MIN(ColumnName)
FROM TableName
WHERE Condition;
Example
1 SELECT MIN(EmployeeID) AS SmallestID

2 FROM Employee_Info;

MAX() Function

The MAX function returns the largest value of the selected column in a table.

Databases Training

MICROSOFT SQL SERVER TRAINING CERTIFICATION COURSE ONLINE


Microsoft SQL Server Training Certification Course Online
Reviews

5(1600)
SQL ESSENTIALS TRAINING
SQL Essentials Training
Reviews

5(4650)

MONGODB CERTIFICATION COURSE


MongoDB Certification Course
Reviews

4(6850)

MYSQL DBA CERTIFICATION TRAINING


MySQL DBA Certification Training
Reviews

5(2900)

TERADATA CERTIFICATION TRAINING


Teradata Certification Training
Reviews

5(1200)

APACHE CASSANDRA CERTIFICATION TRAINING


Apache Cassandra Certification Training
Reviews

5(9)
Next

Syntax
SELECT MAX(ColumnName)
FROM TableName
WHERE Condition;
Example
1 SELECT MAX(Salary) AS LargestFees

2 FROM Employee_Salary;

COUNT() Function

The COUNT function returns the number of rows which match the specified criteria.

Syntax
SELECT COUNT(ColumnName)
FROM TableName
WHERE Condition;
Example
1 SELECT COUNT(EmployeeID)

2 FROM Employee_Info;

SUM() Function

The SUM function returns the total sum of a numeric column that you choose.

Syntax
SELECT SUM(ColumnName)
FROM TableName
WHERE Condition;
Example
1 SELECT SUM(Salary)

2 FROM Employee_Salary;

AVG() Function

The AVG function returns the average value of a numeric column that you choose.

Syntax
SELECT AVG(ColumnName)
FROM TableName
WHERE Condition;
Example
1 SELECT AVG(Salary)
2
FROM Employee_Salary;

NULL Functions

The NULL functions are those functions which let you return an alternative value if an expression is
NULL. In the SQL Server, the function is ISNULL().

Example

1 SELECT EmployeeID * (Month_Year_of_Salary + ISNULL(Salary, 0))

2 FROM Employee_Salary;

Aliases & Case Statement

In this section of this article on SQL Commands, you will go through the Aliases and Case statement one
after the other.

Aliases

Aliases are used to give a column/table a temporary name and only exists for a duration of the query.

Syntax
--Alias Column Syntax

SELECT ColumnName AS AliasName


FROM TableName;

--Alias Table Syntax

SELECT ColumnName(s)
FROM TableName AS AliasName;
Example
1 SELECT EmployeeID AS ID, EmployeeName AS EmpName

2 FROM Employee_Info;

4 SELECT EmployeeName AS EmpName, EmergencyContactName AS [Contact Name]

5 FROM Employee_Info;

Case Statement
This statement goes through all the conditions and returns a value when the first condition is met. So, if
no conditions are TRUE, it returns the value in the ELSE clause. Also, if no conditions are true and there
is no ELSE part, then it returns NULL.

Syntax
CASE
WHEN Condition1 THEN Result1
WHEN Condition2 THEN Result2
WHEN ConditionN THEN ResultN
ELSE Result
END;
Example
1 SELECT EmployeeName, City

2 FROM Employee_Info

3 ORDER BY

4 (CASE

5 WHEN City IS NULL THEN 'Country is India by default'

6 ELSE City

7 END);

Now, that I have told you a lot about DML commands in this article on SQL Commands, let me just tell
you in short about Nested Queries, Joins, Set Operations, and Dates & Auto Increment.

Nested Queries

Nested queries are those queries which have an outer query and inner subquery. So, basically, the
subquery is a query which is nested within another query such as SELECT, INSERT, UPDATE or DELETE.
Refer to the image below:
Joins

JOINS are used to combine rows from two or more tables, based on a related column between those
tables. The following are the types of joins:

 INNER JOIN: This join returns those records which have matching values in both the tables.
 FULL JOIN: This join returns all those records which either have a match in the left or the right
table.
 LEFT JOIN: This join returns records from the left table, and also those records which satisfy the
condition from the right table.
 RIGHT JOIN: This join returns records from the right table, and also those records which satisfy
the condition from the left table.

Refer to the image below.

INNER JOIN

Syntax
SELECT ColumnName(s)
FROM Table1
INNER JOIN Table2 ON Table1.ColumnName = Table2.ColumnName;
Example SELECT Technologies.TechID, Employee_Info.EmployeeName

FROM Technologies

INNER JOIN Employee_Info ON Technologies.EmpID = Employee_Info.EmpID;

FULL JOIN

Syntax

SELECT ColumnName(s)
FROM Table1
FULL OUTER JOIN Table2 ON Table1.ColumnName = Table2.ColumnName;
Example

SELECT Employee_Info.EmployeeName, Technologies.TechID

FROM Employee_Info

FULL OUTER JOIN Orders ON Employee_Info.EmpID=Employee_Salary.EmpID

ORDER BY Employee_Info.EmployeeName;

LEFT JOIN

Syntax

SELECT ColumnName(s)
FROM Table1
LEFT JOIN Table2 ON Table1.ColumnName = Table2.ColumnName;
Example

SELECT Employee_Info.EmployeeName, Technologies.TechID

FROM Employee_Info

LEFT JOIN Technologies ON Employee_Info.EmployeeID = Technologies.EmpIDID

ORDER BY Employee_Info.EmployeeName;

RIGHT JOIN

Syntax
SELECT ColumnName(s)
FROM Table1
RIGHT JOIN Table2 ON Table1.ColumnName = Table2.ColumnName;

Example

SELECT Technologies.TechID FROM Technologies

RIGHT JOIN Employee_Info ON Technologies.EmpID = Employee_Info.EmployeeID

ORDER BY Technologies.TechID;

Set Operations

There are mainly three set operations:UNION, INTERSECT, EXCEPT. You can refer to the image below to
understand the set operations in SQL.

UNION

This operator is used to combine the result-set of two or more SELECT statements.

Syntax

SELECT ColumnName(s) FROM Table1


UNION
SELECT ColumnName(s) FROM Table2;

INTERSECT

This clause used to combine two SELECT statements and return the intersection of the data-sets of both
the SELECT statements.

Syntax

SELECT Column1 , Column2 ....


FROM TableName
WHERE Condition

INTERSECT

SELECT Column1 , Column2 ....


FROM TableName
WHERE Condition

EXCEPT
This operator returns those tuples that are returned by the first SELECT operation, and are not returned
by the second SELECT operation.

Syntax

SELECT ColumnName
FROM TableName

EXCEPT

SELECT ColumnName
FROM TableName;
Next, in this article, let us look into the date functions and auto-increment fields.

DCL Commands in SQL

This section of the article will give you an insight into the commands which aDMLre used to enforce
database security in multiple user database environments. The commands are as follows:


 GRANT
 REVOKE

GRANT

This command is used to provide access or privileges on the database and its objects to the users.

Syntax

GRANT PrivilegeName
ON ObjectName
TO {UserName |PUBLIC |RoleName}
[WITH GRANT OPTION];
where,

 PrivilegeName – Is the privilege/right/access granted to the user.


 ObjectName – Name of a database object like TABLE/VIEW/STORED PROC.
 UserName – Name of the user who is given the access/rights/privileges.
 PUBLIC – To grant access rights to all users.
 RoleName – The name of a set of privileges grouped together.
 WITH GRANT OPTION – To give the user access to grant other users with rights.

REVOKE

This command is used to withdraw the user’s access privileges given by using the GRANT command.
Syntax

REVOKE PrivilegeName
ON ObjectName
FROM {UserName |PUBLIC |RoleName}
Example

Views

A view in SQL is a single table, which is derived from other tables. So, a view contains rows and columns
similar to a real table and has fields from one or more table.

The ‘CREATE VIEW’ statement

This statement is used to create a view, from a table.

Syntax

CREATE VIEW ViewName AS


SELECT Column1, Column2, ..., ColumnN
FROM TableName
WHERE Condition;

The ‘CREATE OR REPLACE VIEW’ statement

This statement is used to update a view.

Syntax

CREATE VIEW OR REPLACE ViewName AS


SELECT Column1, Column2, ..., ColumnN
FROM TableName
WHERE Condition;

This statement is used to delete a view.

Syntax

DROP VIEW ViewName;


Example

TCL Commands in SQL

This section of the article will give you an insight into the commands which are used to manage
transactions in the database. The commands are as follows:
COMMIT

This command is used to save the transaction into the database.

Syntax

COMMIT;

ROLLBACK

This command is used to restore the database to the last committed state.

Syntax

ROLLBACK;
NOTE: When you use ROLLBACK with SAVEPOINT, then you can directly jump to a savepoint in an
ongoing transaction. Syntax: ROLLBACK TO SavepointName;

SAVEPOINT

This command is used to temporarily save a transaction. So if you wish to rollback to any point, then
you can save that point as a ‘SAVEPOINT’.

Syntax

SAVEPOINT SAVEPOINTNAME;

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy