Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 44

WEB CLIENT

A Web client typically refers to the Web browser in the user's machine or mobile device. It may
also refer to extensions and helper applications that enhance the browser to support special
services from the site.

SERVER 

The Server is responsible for serving the web pages depending on the client/end-user
requirement. It can be either static or dynamic. 

CLIENT SERVER COMMUNICATION

 The user opens his web browser (client)


 The user starts browsing
 The client forwards this request to the server, for accessing their web page.
 The server then acknowledges the request and replies back to the client program. 
 The client then receives the page source and renders it.
 Now the user types into the search bar
 The client then submits data to the server
 The server processes the data and replies back with a related search result
 The client again renders it back for the user's view
 The user gets access to the requested link.

Server-side Programming 

Server-side programming can be explained as: 

It is the general name for the kind of program that runs directly on the server. 

Or we can say that server-side programming must deal with dynamic content. It runs on the server.
Most web pages are not static since they deal with searching databases. 

Server-side Uses

 It processes the user input


 Displays the requested pages
 Structure of web applications
 Interaction with servers/storages
 Interaction with databases
 Querying the database
 Encoding of data into HTML
 Operations over databases like delete, update.

Server-side Languages Example 


There are several languages that can be used for server-side programming:
  PHP
 ASP.NET (C# OR Visual Basic)
 C++
 Java and JSP
 Python
 Ruby on Rails and so on.

Client-side Programming 

Similarly to server-side programming, client-side programming is also the name of the entire program
that runs on the client.  

Or we can say that client-side programming mostly deals with the user interface with which the user
interacts in the web. It is mostly a browser, in the user's machine, that runs the code and is mainly done
in any scripting language like JavaScript (or we can use Flash instead of JavaScript or VNScript). 

Client-side Uses

 Makes interactive web pages


 Make stuff work dynamically
 Interact with temporary storage
 Works as an interface between user and server
 Sends requests to the server
 Retrieval of data from Server
 Interact with local storage
 Provides remote access for client-server program

Client-side Languages Example 


There are many client-side scripting languages too.

 JavaScript
 VBScript
 HTML (Structure)
 CSS (Designing)
 AJAX
 jQuery etc.

Clients and Servers

Your web browser is an example of a web client. The remote machine containing the document
you requested is called a web server. The client and server communicate using a special
language (a "protocol") called HTTP

Client and server relationship


To keep ourselves honest, we should get a little more specific now. Although we commonly
refer to the machine that contains the documents as the "server," the server isn't the hardware
itself, but just a program that runs on that machine. The web server listens on a port on the
network, and waits for client requests using the HTTP protocol. After the server responds to the
request (using HTTP), the network connection is dropped and the browser processes the
relevant data that it received, then displays it on your screen.

In practice, many clients can be using the same server at the same time, and one client can also
use many servers at the same time

Multiple clients and servers

As you can see, at the core of the Web is HTTP. If you master HTTP, you can request documents
from a server without needing to go through your browser. Similarly, you can return documents
to web browsers without being limited to the functionality of an existing web server. HTTP
programming takes you out of the realm of the everyday web user and into the world of the
web power user.

Types of servers

The following is a list of all the main types of servers:

1. Web server

An open-source web server is used for accessing the world wide web through public domain
software. These servers connect stored information from an internet website to your own
computer. Web servers store information for the internet that is retrieved via "HTTP" code and
sent to your web browser. This is one of the most widely used types of servers.

2. Proxy server

Proxy servers act as a bridge between a host server and a client server. A proxy sends data from
a website to your computer IP address after it passes through the proxy's server. This practice
adds a layer of security since the information is requested then transferred from the source to
the proxy server and never directly from a client to another user. A proxy server can filter out
various harmful internet entities.

3. Virtual machine (VM)

As their name suggests, virtual machines store and connect data strictly through virtual space.
To create a virtual machine, IT teams use a hypervisor, also known as a virtual machine monitor
(VMM), which is software that can run thousands of virtual machines through only one piece of
physical hardware. This method of server virtualization is widely used for data transfer and
storage because they are the most cost-effective type of server to run.

4. File transfer protocol (FTP) server

FTP servers are used to relocate files from one computer to another. Uploaded files move from
your computer to the server while downloaded files are extracted from the server onto your
device. File transfer protocol also refers to the method of using a server to connect one
computer to another in order to share data safely.

5. Application server

These servers connect clients to software applications through virtual server connections. This
allows users to bypass downloading data to their own hardware in order to access applications.
Application servers can effectively host large amounts of application data to many users at
once, making them ideal for businesses.
6. File server

A file server stores data files for multiple users. They allow for faster data retrieval and saving or
writing files to a computer. This is a basic type of server used commonly by organizations where
lots of users need access to files that are more conveniently and safely stored on a server than
a personal computer.

7. Database server

Database servers function as large storage spaces that organizations use and access to run
multiple programs to meet their needs. A database server can run independently of any
database architecture.

8. Mail server

A mail server stores and delivers mail for clients through email service platforms. Because mail
servers are set up to continually connect to a network, individual users can access their email
without running any systems through their own devices.

9. Print server

A print server connects remotely to local computers to print through a network. These servers
give businesses the ability to use a single printer to serve an entire department. Some printers
even come with their own built-in server ready to join a network once they're installed in an
office area.

10. Domain name system (DNS) server

These servers transform readable computer domain names into computer language IP
addresses. The DNS server takes search data from a user and finds the requested address to
deliver to the client device.

What is HTTPS

o HTTPS stands for Hypertext Transfer Protocol Secure. HTTPS has a secure transfer.
o It was developed by Netscape.
o HTTPS is used to encrypt or decrypt user HTTP page or HTTP page requests that are returned by
the webserver.
o HTTPS is first used in HTTP/1.1 and is defined in RFC 2616.
o In HTTPS, the standard port to transfer the information is 443.
o Using the HTTPS, sensitive information that we want to transfer from one user to another user
can be done securely.
o HTTPS protocol uses HTTP on connection encrypted by SSL (Secure Socket Layer) or TLS
(Transport Layer Security).
o HTTPS protects transmitted data from man-in-the-middle (MITM) attacks and eavesdropping.
o It is the default protocol for conduction financial transactions on the web.

Working of WEB

We will have a client on the left side and server on the right side. A user wants to see a website,
like www.javatpoint.com/java-tutorial. The user types the URL of a page using a client program,
usually a browser. But first, the computer of the user and the web server need to be physically
connected. That is the job of the internet. Using the TCP/IP protocol, it establishes a connection
using a combination of cable media or wireless media and does all the necessary work to
prepare the environment for the two computers to talk via the HTTP protocol.

When the connection establishes, the client sends a request called the HTTP message, but
because the HTTP is a connectionless protocol, so the client disconnects from the server and
waits for the response.

On the other side, the server processes the request, prepare the response, establish the
connection again, and send it back the response and again in the form of an HTTP message to
the client. Then the two computers completely disconnect.
Parts of a URL

A URL contains information that directs a browser to the resource that the user wishes to
access.

Computers that run webserver software make such resources available.

Let’s examine the components of the URL http://www.deitel.com/books/downloads.html

 The http:// indicates that the resource is to be obtained using the HTTP protocol.
 The middle portion, www.deitel.com, is the server’s fully qualified hostname—the name
of the server on which the resource resides. This computer usually is referred to as the
host, because it houses and maintains resources. The hostname www.deitel.com is
translated into an IP address—a unique numerical value that identifies the server much
as a telephone number uniquely defines a particular phoneline. More information on
IPaddresses is available at en.wikipedia.org/wiki/IP_address. This translation is
performed by a domain name system (DNS) server —a computer that maintains a
database of hostnames and their corresponding IP addresses—and the process is called
a DNS lookup .
 The remainder of the URL (i.e., /books/downloads.html)specifies both the name of the
requested resource (the XHTMLdocumentdownloads.html) and its path ,or location (
/books ), on the web server. The path could specify the location of an actual directory
on the web server’s file system. For security reasons, however, the path normally
specifies the location of a virtual directory. The server translates the virtual directory
into a real location on the server (or on another computer on the server’s network),
thus hiding the true location of the resource. Some resources are created dynamically
using other information stored on the server computer, such as a database. The
hostname in the URL for such a resource specifies the correct server; the path and
resource information identify the resource with which to interact to respond to the
client’s request.
APACHE WEB SERVER INSTALLATION

HTTP Response

HTTP Response sent by a server to the client. The response is used to provide the client with
the resource it requested. It is also used to inform the client that the action requested has been
carried out. It can also inform the client that an error occurred in processing its request.

An HTTP response contains the following things:

1. Status Line
2. Response Header Fields or a series of HTTP headers
3. Message Body

In the request message, each HTTP header is followed by a carriage returns line feed (CRLF).
After the last of the HTTP headers, an additional CRLF is used and then begins the message
body.

Status Line

In the response message, the status line is the first line. The status line contains three items:

a) HTTP Version Number

It is used to show the HTTP specification to which the server has tried to make the message
comply.

Example

1. HTTP-Version = HTTP/1.1  

b) Status Code

It is a three-digit number that indicates the result of the request. The first digit defines the class
of the response. The last two digits do not have any categorization role. There are five values
for the first digit, which are as follows:
Code and Description

1xx: Information

It shows that the request was received and continuing the process.

2xx: Success

It shows that the action was received successfully, understood, and accepted.

3xx: Redirection

It shows that further action must be taken to complete the request.

4xx: Client Error

It shows that the request contains incorrect syntax, or it cannot be fulfilled.

5xx: Server Error

It shows that the server failed to fulfil a valid request.

c) Reason Phrase

It is also known as the status text. It is a human-readable text that summarizes the meaning of
the status code.

An example of the response line is as follows:

1. HTTP/1.1 200 OK  

Here,

o HTTP/1.1 is the HTTP version.


o 200 is the status code.
o OK is the reason phrase.

Response Header Fields

The HTTP Headers for the response of the server contain the information that a client can use
to find out more about the response, and about the server that sent it. This information is used
to assist the client with displaying the response to a user, with storing the response for the use
of future, and with making further requests to the server now or in the future.
1. response-header = Accept-Ranges            
2.                   | Age                     
3.                   | ETag                     
4.                   | Location                
5.                   | Proxy-Authenticate       
6.                   | Retry-After              
7.                   | Server             
8.                   | Vary                    
9.                   | WWW-Authenticate      

The name of the Response-header field can be extended reliably only in combination with a
change in the version of the protocol.

Message Body

The response's message body may be referred to for convenience as a response body.

The body of the message is used for most responses. The exceptions are where a server is using
certain status codes and where the server is responding to a client request, which asks for the
headers but not the response body.

For a response to a successful request, the body of the message contains either some
information about the status of the action which is requested by the client or the resource
which is requested by the client. For the response to an unsuccessful request, the body of the
message might provide further information about some action the client needs to take to
complete the request successfully or about the reason for the error.
APACHE WEB SERVER directory structure.

 / – Root
 Every single file and directory starts from the root directory.
 Only root user has write privilege under this directory.
 Please note that /root is root user’s home directory, which is not same as /.

2. /bin – User Binaries

 Contains binary executables.


 Common linux commands you need to use in single-user modes are located under this
directory.
 Commands used by all the users of the system are located here.
 For example: ps, ls, ping, grep, cp.

3. /sbin – System Binaries

 Just like /bin, /sbin also contains binary executables.


 But, the linux commands located under this directory are used typically by system
aministrator, for system maintenance purpose.
 For example: iptables, reboot, fdisk, ifconfig, swapon

4. /etc – Configuration Files

 Contains configuration files required by all programs.


 This also contains startup and shutdown shell scripts used to start/stop individual
programs.
 For example: /etc/resolv.conf, /etc/logrotate.conf

PORT

A port is a virtual point where network connections start and end. Ports are software-based and
managed by a computer's operating system. Each port is associated with a specific process or
service. Ports allow computers to easily differentiate between different kinds of traffic: emails
go to a different port than webpages, for instance, even though both reach a computer over the
same Internet connection.

What is a port number?

Ports are standardized across all network-connected devices, with each port assigned a
number. Most ports are reserved for certain protocols — for example, all Hypertext Transfer
Protocol (HTTP) messages go to port 80. While IP addresses enable messages to go to and from
specific devices, port numbers allow targeting of specific services or applications within those
devices.

Default Port Numbers

Difference between Port 80 & 8080

 Both port 80 and 8080 are used for web applications.

 However port 80 is the primary port which is used by a web client like your web
browser. Also when a web developer deploys any web application, they primarily bind
the app to the port 80.

 Or in other words web servers open port 80 to listen to all the connection requests


coming from the web browser.
 Therefore when a web browser is locating for a website say wwwgoogle.com it itself
knows that the remote web server is listening for all the requests on port 80

 when port 80 is responsible for managing all the requests, then what is the need for
port 8080.

 port 8080 is an alternative to port 80.

 port 8080, can be used to deploy a proxy caching server.

APACHEWEB SERVER INSTALLATION

To install an Apache HTTP Server:

Step 1:

1. Navigate to Apache Website - (httpd.apache.org)


2. Click on "Download" link for the latest stable version
3. After being redirect to the download page, Select: "Files for Microsoft Windows"
4. Select one of the websites that provide binary distribution (for example: Apache
Lounge)
5. After being redirect to "Apache Lounge" website
(https://www.apachelounge.com/download/), Select: Apache x.x.xx Win64 link
6. After downloaded, unzip the file httpd-x.x.xx-Win64-VC15.zip into C:/
Step 2:

1. Open a command prompt: Run as Administrator


2. Navigate to directory c:/Apache24/bin
3. Add Apache as a  Windows Service:  httpd.exe -k install -n "Apache HTTP Server"  
4. In the event of the following error follow Step 3 otherwise jump to Step 4: "The
program can't start because VCRUNTIME140.dll is missing from your computer. Try
reinstalling the program to fix this problem"
5. If after configuring Apache as a Windows service it fails to start and reports this error
"Windows could not start the Apache HTTP Server on Local Computer." It is likely that
Apache is not able to use the default port (normally 80) because another process is
using the same port.  Open an Administrative command prompt and issue the
command "netstat -anbo".  If another process is using the port which Apache is
configured to listen on, modify the Listen port in the httpd.conf file of the Apache
installation to use a port that is not already taken by another process. Or alter the
process holding the port to use a different port so Apache can listen on this port..
Step 3:
1. Open Windows Services and start Apache HTTP Server
2. Open a Web browser and type the machine IP in the address bar and hit Enter

What exactly is XAMPP?

XAMPP is an abbreviation for cross-platform, Apache, MySQL, PHP and Perl, and it allows you to
build WordPress site offline, on a local web server on your computer. This simple and
lightweight solution works on Windows, Linux, and Mac – hence the “cross-platform” part.

Since WordPress isn’t a stand-alone application, XAMPP provides two essential components for
its installation – Apache, which is used to create the local server, and MySQL which you can use
as a database for your website.

You may be wondering why and how developers are using WordPress local server. The answer
is simple – it allows them to create a local copy of the site in which they can try out new plugin
updates before implementing them on its live version.

This way they can prevent and spot potential errors and issues that might occur.

Now it’s time to dive deeper into this XAMPP tutorial and learn how to locally host a website on
Windows, Mac, or Linux.

Step One: How to install XAMPP?


The first step in setting up XAMPP: go to the Apache Friends website and download the file for
the platform you are using. You will see separate download links for Windows, Linux and OS X.
Note that there is no 64-bit version for Windows, but the 32-bit one works perfectly fine.

The file size is not that large (around 110MB).

After downloading it, launch the installer and XAMPP setup will begin.

Step Two: Initial Installation Steps

Sometimes, depending on your operating system, you may receive a security warning. Don’t
worry, XAMPP is safe to install. When setup wizard pops up, click “Next”, and in the next
window, you will be asked to select components you want to install.

Options like Apache and PHP are required and are installed automatically. Since our goal is to
host WordPress locally, you must check MySQL and phpMyAdmin boxes. You can uncheck the
rest if you want to.

Next, select the folder where you would like to install XAMPP on your computer. It’s up to you
if you want to create a new folder or use the default path (C:\Program Files\XAMPP).

After choosing the install directory, you will be asked to install Bitnami. The extension makes
installing third-party CMS programs WordPress, Joomla!, Drupal without a hassle. In this
XAMPP tutorial we will manually install WordPress, so uncheck “Learn more about Bitnami for
XAMPP” and click “Next”.

Step Three: XAMPP Setup


Finally, after going through all those installation hassles, XAMPP is ready to install. But, wait,
there’s more! During the installation, you may encounter security/firewall warnings. Make sure
you check “Private networks, such as my home or work network”, and click “Allow Access”.

That will create a rule for XAMPP in your security system, and allow it to work. Now, where
were we? Ah, yes!

After the installation, you will be asked if you would like to start the XAMPP Control Panel.
Leave the box checked and click “Finish”. The Control Panel will now open.

Step Four: Running XAMPP

If you accidentally unchecked the box, don’t worry. You can go to your XAMPP folder on your
computer and manually run XAMPP Control Panel.

Note: Before using XAMPP, check that you don’t have conflicting applications that are using the
same ports running in the background. Skype is a perfect example. Exit those applications are
restart XAMPP.
If the installation didn’t run into any errors, the control panel would show black and blue text
below the list of the panel’s components (Apache, MySQL etc.). All of the elements have their
separate Start/Stop, Admin, Config, and Logs buttons.

Run Apache and MySQL by clicking their Start buttons. If the components started without
problems, you would see a green background behind their names. Congratulations! You have
successfully installed XAMPP server on your computer.

You are now ready to install WordPress XAMPP local server.

Step Five: Your First Database

With XAMPP up and running, it’s time to teach you how to install WordPress, but before we do
that, you will need to create a database first. Open your XAMPP Control Panel and click on the
“Admin” button of the MySQL section, which will lead you to the phpMyADmin page.

Alternatively, you can reach this page by typing “http://localhost/phpmyadmin/” (without the
quotation marks) into your browser. 

Find “Databases” link on the top of the page, and right under it you will find “Create Database”.
Enter the desired name and click “Create”.
Step Six: How to install WordPress on XAMPP?

Finally, the juicy part! Straight to the point – download the latest version of WordPress from
the platforms official website and extract the zipped file to your desktop (or folder of your
choice – but it won’t stay there for long).

Copy the extracted content and paste it into the “htdocs” folder which is in the folder where
you have installed XAMPP (default address is: C:/Program Files/XAMPP/htdocs)

Open up your browser and type: http://localhost/wordpress/ in the address bar. A screen will
show up, asking you to select a language. Then, after clicking “Continue”, another screen will
appear asking you the following information:
 Database Name
 Database Username
 Database Password
 Database Host.

It’s completely fine if you don’t know all the information, that’s why we are here. Bravely click
“Let’s go!” button, and type in the following information in the boxes:
 Database Name – Write the name of the database you created in step five
 User Name: root
 Password: Leave this field empty. Delete any default text if needed, and
 Database Host: localhost
 Table Prefix: wp_
Click “Submit”, then “Run the install” button. After a few minutes, you will see the “Site Title”
field. Go ahead and enter the title of your first test site.

Under the “Username” and “Password” fields, create yourself an admin account. Make sure
you save or memorize what you typed in since you will need this information to log in. Enter a
valid e-mail address into “Your E-mail” field.

Last but not least, “Privacy” can be used to hide your site from those nasty search engines.
After double checking what you typed in and selected, click “Install WordPress”. If everything
works smoothly, a success page will be displayed.

Click the “Log In” button and enter your credentials. That will lead you to the admin dashboard
of your WordPress website.

SQL
SQL Introduction

SQL is a database computer language designed for the retrieval and management of data in a
relational database. SQL stands for Structured Query Language. 

SQL is Structured Query Language, which is a computer language for storing, manipulating and
retrieving data stored in a relational database.
SQL is the standard language for Relational Database System. All the Relational Database
Management Systems (RDMS) like MySQL, MS Access, Oracle, Sybase, Informix, Postgres and
SQL Server use SQL as their standard database language.

Applications of SQL

As mentioned before, SQL is one of the most widely used query language over the databases.
I'm going to list few of them here:
 Allows users to access data in the relational database management systems.
 Allows users to describe the data.
 Allows users to define the data in a 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.
RDBMS

What is RDBMS?

RDBMS stands for Relational Database Management System. RDBMS is the basis for SQL, and


for all modern database systems like MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft
Access.
A Relational database management system (RDBMS) is a database management system
(DBMS) that is based on the relational model as introduced by E. F. Codd.

What is a table?

The data in an RDBMS is stored in database objects which are called as tables. This table is
basically a collection of related data entries and it consists of numerous columns and rows.
Remember, a table is the most common and simplest form of data storage in a relational
database. The following program is an example of a CUSTOMERS table −

+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+

What is a field?

Every table is broken up into smaller entities called fields. The fields in the CUSTOMERS table
consist of ID, NAME, AGE, ADDRESS and SALARY.
A field is a column in a table that is designed to maintain specific information about every
record in the table.
What is a Record or a Row?

A record is also called as a row of data is each individual entry that exists in a table. For
example, there are 7 records in the above CUSTOMERS table. Following is a single row of data
or record in the CUSTOMERS table −

+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
+----+----------+-----+-----------+----------+
A record is a horizontal entity in a table.

What is a column?

A column is a vertical entity in a table that contains all information associated with a specific
field in a table.
For example, a column in the CUSTOMERS table is ADDRESS, which represents location
description and would be as shown below −

+-----------+
| ADDRESS |
+-----------+
| Ahmedabad |
| Delhi |
| Kota |
| Mumbai |
| Bhopal |
| MP |
| Indore |
+----+------+

SQL - Data Types

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

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

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.

Strings Data Types


Sr.No. DATA TYPE & Description

1 char
Maximum length of 8,000 characters.( Fixed length non-Unicode characters)

2 varchar
Maximum of 8,000 characters.(Variable-length non-Unicode data).

3 varchar(max)
Maximum length of 2E + 31 characters, Variable-length non-Unicode data (SQL Server 2005 only).

4 text
Variable-length non-Unicode data with a maximum length of 2,147,483,647 characters.

SQL COMMANDS
SQL - CREATE Database
The SQL CREATE DATABASE statement is used to create a new SQL database.

Syntax

The basic syntax of this CREATE DATABASE statement is as follows −


CREATE DATABASE DatabaseName;

Example

If you want to create a new database <testDB>, then the CREATE DATABASE statement would
be as shown below −

SQL> CREATE DATABASE testDB;


Make sure you have the admin privilege before creating any database. Once a database is
created, you can check it in the list of databases as follows −
SQL> SHOW DATABASES;
+--------------------+
| Database |
+--------------------+
| information_schema |
| AMROOD |
| TUTORIALSPOINT |
| mysql |
| orig |
| test |
| testDB |

SQL - DROP or DELETE Database


The SQL DROP DATABASE statement is used to drop an existing database in SQL schema.

Syntax

The basic syntax of DROP DATABASE statement is as follows −


DROP DATABASE DatabaseName;

Example

If you want to delete an existing database <testDB>, then the DROP DATABASE statement
would be as shown below −

SQL> DROP DATABASE testDB;

SQL Commands
o SQL commands are instructions. It is used to communicate with the database. It is also
used to perform specific tasks, functions, and queries of data.
o SQL can perform various tasks like create a table, add data to tables, drop the table,
modify the table, set permission for users.

Types of SQL Commands

There are five types of SQL commands: DDL, DML, DCL, TCL, and DQL.
1. Data Definition Language (DDL)
o DDL changes the structure of the table like creating a table, deleting a table, altering a
table, etc.
o All the command of DDL are auto-committed that means it permanently save all the
changes in the database.

Here are some commands that come under DDL:

o CREATE
o ALTER
o DROP
o TRUNCATE

a. CREATE It is used to create a new table in the database.

Syntax:
CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,....]);  

Example:

CREATE TABLE EMPLOYEE(
Name VARCHAR2(20), Email VARCHAR2(100), DOB DATE);  

b. DROP: It is used to delete both the structure and record stored in the table.

Syntax

DROP TABLE table_name;  

Example

DROP TABLE EMPLOYEE;  

c. ALTER: It is used to alter the structure of the database. This change could be either to modify
the characteristics of an existing attribute or probably to add a new attribute.

Syntax:

To add a new column in the table

ALTER TABLE table_name ADD column_name COLUMN-definition;    

To modify existing column in the table:

ALTER TABLE table_name MODIFY(column_definitions....);  

Example:

ALTER TABLE STU_DETAILS ADD(ADDRESS VARCHAR2(20));  
ALTER TABLE STU_DETAILS MODIFY (NAME VARCHAR2(20));  
d. TRUNCATE: It is used to delete all the rows from the table and free the space containing the
table.

Syntax:

TRUNCATE TABLE table_name;  

Example:

TRUNCATE TABLE EMPLOYEE;  

2. Data Manipulation Language


o DML commands are used to modify the database. It is responsible for all form of
changes in the database.
o The command of DML is not auto-committed that means it can't permanently save all
the changes in the database. They can be rollback.

Here are some commands that come under DML:

o INSERT
o UPDATE
o DELETE

a. INSERT: The INSERT statement is a SQL query. It is used to insert data into the row of a table.

Syntax:

INSERT INTO TABLE_NAME    
(col1, col2, col3,.... col N)  
VALUES (value1, value2, value3, .... valueN);  

Or

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

Example:
INSERT INTO javatpoint (Author, Subject) VALUES ("Sonoo", "DBMS");  

b. UPDATE: This command is used to update or modify the value of a column in the table.

Syntax:

UPDATE table_name SET [column_name1= value1,...column_nameN = valueN] [WHERE CONDIT
ION]   

Example:

UPDATE students    
SET User_Name = 'Sonoo'    
WHERE Student_Id = '3'  

c. DELETE: It is used to remove one or more row from a table.

Syntax:

DELETE FROM table_name [WHERE condition];  

Example

DELETE FROM javatpoint  
WHERE Author="Sonoo";  

3. Data Control Language

DCL commands are used to grant and take back authority from any database user.

Here are some commands that come under DCL:

o Grant
o Revoke

a. Grant: It is used to give user access privileges to a database.

Example

GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_USER;  
b. Revoke: It is used to take back permissions from the user.

Example

REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;  

4. Transaction Control Language

TCL commands can only use with DML commands like INSERT, DELETE and UPDATE only.

These operations are automatically committed in the database that's why they cannot be used
while creating tables or dropping them.

Here are some commands that come under TCL:

o COMMIT
o ROLLBACK
o SAVEPOINT

a. Commit: Commit command is used to save all the transactions to the database.

Syntax:

COMMIT;  

Example:

DELETE FROM CUSTOMERS  
WHERE AGE = 25;  
COMMIT;  

b. Rollback: Rollback command is used to undo transactions that have not already been saved
to the database.

Syntax:

ROLLBACK;  

Example:
DELETE FROM CUSTOMERS  
WHERE AGE = 25;  
ROLLBACK;  

c. SAVEPOINT: It is used to roll the transaction back to a certain point without rolling back the
entire transaction.

Syntax:

SAVEPOINT SAVEPOINT_NAME;  

5. Data Query Language

DQL is used to fetch the data from the database.

It uses only one command:

o SELECT

a. SELECT: This is the same as the projection operation of relational algebra. It is used to select
the attribute based on the condition described by WHERE clause.

Syntax:

SELECT expressions    

FROM TABLES    

WHERE conditions;  

For example:

SELECT emp_name  
FROM employee  
WHERE age > 20;
______________________________________________________________________________

What is a NULL value?


A NULL value in a table is a value in a field that appears to be blank, which means a field with a
NULL value is a field with no value.
It is very important to understand that a NULL value is different than a zero value or a field
that contains spaces. A field with a NULL value is the one that has been left blank during a
record creation.

SQL Constraints

Constraints are the rules enforced on data columns on a 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 can either be column level or table level. Column level constraints are applied only
to one column whereas, table level constraints are applied to the entire table.
Following are some of the most commonly used constraints available in SQL −
 NOT NULL Constraint − Ensures that a column cannot have a NULL value.
 DEFAULT Constraint − Provides a default value for a column when none is specified.
 UNIQUE Constraint − Ensures that all the values in a column are different.
 PRIMARY Key − Uniquely identifies each row/record in a database table.
 FOREIGN Key − Uniquely identifies a row/record in any another database table.
 CHECK Constraint − The CHECK constraint ensures that all values in a column satisfy
certain conditions.

SQL - NOT NULL Constraint


By default, a column can hold NULL values. If you do not want a column to have a NULL value,
then you need to define such a constraint on this column specifying that NULL is now not
allowed for that column.
A NULL is not the same as no data, rather, it represents unknown data.

Example

For example, the following SQL query creates a new table called CUSTOMERS and adds five
columns, three of which, are ID NAME and AGE, In this we specify not to accept NULLs −

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 the
SALARY column in Oracle and MySQL, you would write a query like the one that is shown in the
following code block.

ALTER TABLE CUSTOMERS


MODIFY SALARY DECIMAL (18, 2) NOT NULL;

SQL - 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, the SALARY column is set to 5000.00 by default, so in case the 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)
);

The UNIQUE Constraint prevents two records from having identical values in a column. In the
CUSTOMERS table, for example, you might want to prevent two or more people from having
an identical age.

Example
For example, the following SQL query creates a new table called CUSTOMERS and adds five
columns. Here, the AGE column is set to UNIQUE, so that you cannot have two records with
the 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)
);

SQL - Primary Key


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.

Create Primary Key

Here is the syntax to define the ID attribute as a primary key in a CUSTOMERS table.
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)
);

SQL - Foreign Key

A foreign key is a key used to link two tables together. This is sometimes also called as a
referencing key.
A Foreign Key is a column or a combination of columns whose values match a Primary Key in a
different table.
The relationship between 2 tables matches the Primary Key in one of the tables with a Foreign
Key in the second table.
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).

Example
Consider the structure of the following two tables.
CUSTOMERS table

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)
);
ORDERS table

CREATE TABLE ORDERS (


ID INT NOT NULL,
DATE DATETIME,
CUSTOMER_ID INT references CUSTOMERS(ID),
AMOUNT double,
PRIMARY KEY (ID)
);

SQL - 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 the table.

Example
For example, the following program creates a new table called CUSTOMERS and adds five
columns. Here, we add a CHECK with AGE column, so that you cannot have any CUSTOMER
who is 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)
);

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 databases sort the query results in an ascending order by default.

Syntax

The basic syntax of the ORDER BY clause 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 the column-list.

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 |
+----+----------+-----+-----------+----------+
The following code block has an example, which would sort the result in an ascending order by
the NAME and the SALARY −

SQL> SELECT * FROM CUSTOMERS


ORDER BY NAME, SALARY;
This would produce the following result −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
+----+----------+-----+-----------+----------+
The following code block has an example, which would sort the result in the descending order
by NAME.

SQL> SELECT * FROM CUSTOMERS


ORDER BY NAME DESC;
This would produce the following result −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
+----+----------+-----+-----------+----------+

SQL - Group By
The SQL GROUP BY clause is used in collaboration with the SELECT statement to arrange
identical data into groups. This GROUP BY clause follows the WHERE clause in a SELECT
statement and precedes the ORDER BY clause.

Syntax

The basic syntax of a GROUP BY clause is shown in the following code block. 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

Consider the CUSTOMERS table is 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 |
+----+----------+-----+-----------+----------+
If you want to know the total amount of the salary on each customer, then the GROUP BY
query would be as follows.

SQL> SELECT NAME, SUM(SALARY) FROM CUSTOMERS


GROUP BY NAME;
This would produce the following result −
+----------+-------------+
| NAME | SUM(SALARY) |
+----------+-------------+
| Chaitali | 6500.00 |
| Hardik | 8500.00 |
| kaushik | 2000.00 |
| Khilan | 1500.00 |
| Komal | 4500.00 |
| Muffy | 10000.00 |
| Ramesh | 2000.00 |
+----------+-------------+
Now, let us look at a table where the CUSTOMERS table has the following records with
duplicate names −

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Ramesh | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | kaushik | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Now again, if you want to know the total amount of salary on each customer, then the GROUP
BY query would be as follows −

SQL> SELECT NAME, SUM(SALARY) FROM CUSTOMERS


GROUP BY NAME;
This would produce the following result −
+---------+-------------+
| NAME | SUM(SALARY) |
+---------+-------------+
| Hardik | 8500.00 |
| kaushik | 8500.00 |
| Komal | 4500.00 |
| Muffy | 10000.00 |
| Ramesh | 3500.00 |
+---------+-------------+

How To Create New MySQL User and Grant Privileges

1. Before you can create a new MySQL user, you need to open a terminal window and launch
the MySQL shell as the root user. To do so, enter the following command:

sudo mysql –u root –p

2. Type in the root password for this account and press Enter.
The prompt should change to show that you are in the mysql> shell.

3. Next, create a new MySQL user with:

CREATE USER 'username' IDENTIFIED BY 'password';

Replace username and password with a username and password of your choice.

Alternatively, you can set up a user by specifying the machine hosting the database.

 If you are working on the machine with MySQL, use username@localhost to define the
user.
 If you are connecting remotely, use username@ip_address, and
replace ip_address with the actual address of the remote system hosting MySQL.

Therefore, the command will be:

CREATE USER 'username'@'localhost' IDENTIFIED BY 'password';

or

CREATE USER 'username'@'ip_address' IDENTIFIED BY 'password';

You can also create a user that can connect from any machine with the command:

CREATE USER 'username'@'%' IDENTIFIED BY 'password';

Grant Permissions in MySQL


Before logging in with a new account, make sure you have set the permissions for the user.

Permissions are actions that the user is allowed to perform in the database. Depending on how
much authority you want your user to have, you can grant them one, several or all of the
following privileges:

 All Privileges: The user account has full access to the database


 Insert: The user can insert rows into tables
 Delete: The user can remove rows from tables
 Create: The user can create entirely new tables and databases
 Drop: The user can drop (remove) entire tables and databases
 Select: The user gets access to the select command, to read the information in the
databases
 Update: The user can update table rows
 Grant Option: The user can modify other user account privileges

The basic syntax used to grant privileges to a user account is:

GRANT permission_type ON database.table TO 'username'@'localhost';

For example, to grant insert privileges to a MySQL user you would run the command:

GRANT INSERT ON *.* TO 'username'@'localhost';

You can replace the privilege level according to your needs. Run the command for each
privilege you wish to grant.

If you want to limit the user’s access to a specific database, name that database before the dot.
Likewise, you can restrict a user’s access to a particular table by naming it after the dot, as in
the command below:

GRANT INSERT *database_name.table_name* TO 'username'@'localhost';


 

You might also like