Sie sind auf Seite 1von 21

Lecture 1 Overview

Front End is UI (user interface)

Backend used for functionality of website

Two Things in Backend

 Programming language
 Database

Programming language used as interface between database and user interface

Data base

 Mongo DB
 SQL

SQL

Structured Query Language, Command Base language, Server-side language for every line we need
server.

Four Things from which we Make Web Application

LAMP

 Linux By Default
 APACHE Server
 MYSQL database
 PHP

Apache: Web server meant to serve Static Webpage, open source

Tomcat: Also static webpage server, but less efficient then apache, open source

Filezilla: Free software to transferring files over internet

Mercury: Mail transport System ,Standard mail server

XAMPP Server Installation:

Download it from File hippoInstall in C ( continue install if error or notification occur) turn off Skype
during installation and loading as well run the file for C/Xampp folder/xamp control-exe(run this)--.
Start sql and Apache
Database name : phpmyadmin

Localhost/phpmyadmin

SQL:Structured Query Language


Database Computer Language design for storing, retrieving and management of data in relational
database:

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.

What SQL Do:

 Execute Queries against database


 Retrieve data from Database
 Insert record
 Delete Record
 Update record
 Create new data base
 Create table
 Create storing procedure
 Create views
 Set permissions

To Built Website That show data from Database, Four things required

 RDMS (MySql, Sybase, Microsoft Access, oracle, Informix)


 Sql Server
 Scripting language (PHP or ASP)
 HTML/CSS
RDBMS:

Relational Database Management system, in this data stored in object called table consists of data
entries each entry consist of rows and column.

Table broken into small entities called field which contain information about every record

Rows of table called record, information of each individual entry

Column vertical entity consist information about each field

SQL Constraint

Constraint are rule that enforce on data column on table, either be column or table level ensure
accuracy and reliability.

Common used constraint

 NOT NULL: Ensure the column has no null value (blank)


 DEFAULT: Provide default value when None is specified
 UNIQUE: Ensure all values in column are different
 PRIMARY: uniquely identifies each record in table
 FOREIGN: uniquely identifies each record in any other database
 CHECK: Ensure all values in column satisfy certain conditions
 INDEX creates and retrieves data from database.

STATEMENT START KEY WORDS

 SELECT
 UPDATE
 INSERT
 CREATE
 ALERT
 DROP
 DELETE
 USE
 SHOW

All statement end with semicolons(;)


SQL DATA TYPES

Numeric

 Int (for small work)


 Bigint (for Large work)
 Smallint
 Tinyint
 Bit
 Decimal
 Numeric
 Money
 Smallmoney
 Float (approximate numeric data)
 Real (approximate Numeric Data)

Date and Time

 Datetime
 Smalldatetime
 Date
 Time

Character String

 CHAR (fixed length string 255 characters)


 VARCHAR (variable length 65535 characters)
 TEXT (use when length is unknown)
 Nchar(for fixed length binary)
 Nvarchar
 Image (variable length binary)

Others

 Sql_variant : store values of server supported data types


 Timestamp: stored database unique number that get update every time row update
 Uniqueidentifier: store global unique identifier
 Xml: store xml data
 Table: store result for later processing
SQL OPERATORS

Arithmetic

(+ / * - %)

Comparison

(= != <> > < <= >= !< !>

Logical

 ALL (Compare all values)


 AND
 ANY (compare any applicable value)
 BETWEEN( between min and max values)
 EXISTS(presence of value)
 IN (compare with list of specified values)
 LIKE(compare similar values)
 NOT( reverse the logic)
 OR
 IS NULL(compare with null value)
 UNIQUE (search every row for uniqueness)
Create Database Stepwise Procedure
1. Run Xampp control.exe
2. Run Sql and Apache
3. In browser write localhost/phpmyadmin/ (new server base screen open)
4. Click new
5. Create database name
o No spaces
o Not start with number
o No special characters
6. Enter Table name and specify no of columns
7. Specify the fields name, there type, auto increment, null index, length, uniqueness (primarykey).
8. Insert Data Into Table using SQL Query click SQL tab then

INSERT INTO tablename(fieldname 1, fieldname2,---)VALUES (“value1”,”value2”,-------)

9. Values added in sequence of filed name

Another Method

1. CREATE DATABASE database name


2. CREATE TABLE table name (col1name datatype constraint,

Col2name dattype constraint,---------

PRIMARY KEY (on one column)

);

Export Database
1. Select database
2. Select table
3. Click export tab
4. Name file
5. Format sql
6. Dump some or dump all rows (your selection)
7. First data base
CREATE TABLE IF NOT EXITS
If you create that that is already exist the it makes an error to avoid this use query IF NOT EXISTS

3. CREATE TABLE IF NOT EXISTS table name (col1name datatype constraint,

Col2name dattype constraint,---------

PRIMARY KEY (on one column)

);

Foreign key concept:

FOREIGN KEY (dept_id) REFERENCES departments(dept_id)

Check Constraint

salary INT NOT NULL CHECK (salary >= 3000 AND salary <= 10000),

Default concept

country VARCHAR(30) NOT NULL DEFAULT 'Australia'

ALTER TABLE STATEMENT


Modify the existing table

Adding the new column

ALTER TABLE table_name ADD column_name data_type constraints;

Changing column position

ALTER TABLE table_name


MODIFY column_name column_definition AFTER column_name;

Adding Constraint

ALTER TABLE table_name ADD UNIQUE (column_name,...);

Removing Column

ALTER TABLE table_name DROP COLUMN column_name;


Changing data type

ALTER TABLE table_name MODIFY column_name new_data_type;

Rename table

ALTER TABLE current_table_name RENAME new_column_name;

SELECT STATEMENT
Fetch data from data from table and show the result in form of table

SELECT * FROM table_name;

To select specific columns

SELECT col1, col2, col3 FROM table;

Select Where Clause

SELECT column1, column2, columnN


FROM table_name
WHERE colname
SELECT * FROM table_name WHERE colname= “value”;

SELECT * FROM table_name WHERE condition;

Where clause also used with update and delete statement

Update

UPDATE "table_name"
SET "column_1" = [new value]
WHERE "condition";

Delete

DELETE FROM "table_name"


WHERE "condition";

select
Where statement allow LIKE ,BETWEEN, IN OPERATORS

SELECT * FROM table_name WHERE colname= “value” AND Colname=”value”

SELECT * FROM table_name WHERE colname BETWEEN “value” AND ”value”

SELECT column_list FROM table_name


WHERE column_name IN (value1, value2,.);

LIKE:

SELECT column_list FROM table_name WHERE column_name LIKE “% i%”;

Wildcard
Is used to match string pattern

 % sign indicate (zero, multiple or null characters)


 _ sign indicate ( single num of character)

Wildcard is used with LIKE statement.

‘200% ---- value start with 200

%200%----- any value that have 200 in any position

‘_00%’---- any value that have 0 in 2nd and 3rd positon

‘%2’---- value end with 2

‘2_%_%’---- start with 2 and end with 3 characters in length

Order by

To store the result in ascending or decending order

SELECT column_list FROM table_name ORDER BY column_name ASC|DESC;

 SELECT * FROM TABLE ORDER BY COLNAME ASC;


SQL - TOP, LIMIT or ROWNUM Clause
TOP

SELECT TOP number|percent column_name(s)


FROM table_name
WHERE [condition]

FETCH TOP NUM OR PERCENTAGE FROM TABLE

SELECT column_name(s)
FROM table_name
WHERE condition
LIMIT number;

Retrieving Distinct Values


When fetching data from a database table, the result set may contain duplicate
rows or values. If you want to remove these duplicate values you can specify the
keyword DISTINCT directly after the SELECT keyword, as demonstrated below:

SELECT DISTINCT column_list FROM table_name;

SELECT UNIQUE column_list FROM table_name; // work same as distinct

Update Existing Data

UPDATE table_name
SET column1_name = ‘value1’, column2_name =’ value2’,...
WHERE condition;

Delete Data

DELETE FROM persons;

DELETE FROM table_name WHERE condition;


TRUNCATE TABLE
Delete all rows of the table

Also reset the auto increment value

TRUNCATE TABLE tablename;

Delete internal data of the table

Drop
Permanently remove data base or table

DROP DATABASE demo;

DROP TABLE persons;

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.

SELECT column1, column2


FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2
ORDER BY column1, column2

EXAMPLE IS group by class in school, group same repletion name (city, country, class etc)

Select column and group by column name should be same

Always used with aggregate functions

The IS NULL Operator


Used to test empty null cell
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NSELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NULL;

The SQL Aggregate Functions


The MIN() function returns the smallest value of the selected column.

The MAX() function returns the largest value of the selected column.

AVG()

SUM()

COUNT()

MINUS()

SELECT SUM(column) FROM table

GroupBY:

The GROUP BY clause is used to tell SQL what level of granularity


the aggregate function should be calculated in.

More than one column can be specified in the GROUP BY clause, and
more than one function can be included.
SELECT Store_Name, SUM(Sales)
FROM Store_Information
GROUP BY Store_Name;
The SQL HAVING Clause
The HAVING clause was added to SQL because the WHERE keyword could not
be used with aggregate functions.

HAVING is often coupled with the presence of the GROUP BY clause,


although it is possible to have a HAVING clause without the GROUP
BY clause.

The HAVING clause is used to filter the result set based on the result of an
aggregate function. It is typically located near or at the end of the SQL
statement.

SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);

Select---from---where----having----orderby

The SQL IN Operator


The IN operator allows you to specify multiple values in a WHERE clause.

The IN operator is a shorthand for multiple OR conditions


Always used with where caluse

SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);

SQL - Alias Syntax


You can rename a table or a column temporarily by giving another name known as Alias.
The use of table aliases is to rename a table in a specific SQL statement. The renaming is a
temporary change and the actual table name does not change in the database. The column
aliases are used to rename a table's columns for the purpose of a particular SQL query.

An alias only exists for the duration of the query

SELECT colName AS newname FROM tablename

User can understand the complet name of column easily

SQL JOIN
A JOIN clause is used to combine rows from two or more tables, based on a
related column between them.

SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate


FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;

 SELECT t1 .column1, t1.column2, t2. Column1, t2.column2


 FROM table1 AS t1 INNER JOIN table2 AS t2
 ON t1.dept_id = t2.dept_id ORDER BY column1;

SELECT seconddetail.Name, firstdetail.Address,firstdetail.Age FROM


firstdetail INNER JOIN seconddetail ON firstdetail.Rollno= seconddetail.id;

Above statement select the column1 and clumn2 from table 1 and column1 and column 2 from table 2

then ON query check the matc h t1 dep wit t2 dep inner join only shows thos department which are
matches.

Left Join: show all data of left table and match data of right table, left table data
that do not match column represent Null

Right Join show all data of right table and match data of left table, right table data
that do not match column represent Null

Full join show all data of right and left tables, data that do not match column
represent Null

SQL - Indexes

Indexes are special lookup tables that the database search engine can use to speed up
data retrieval.

User cannot see the indexes they just used to speed up searches.

Not scan full table only scan specific area search


Index clustered and non clustered

Clustered (primary key)

 One on the table


 Sort data of primary key column
 Data unique
 index

Non-Clustered

 more than one index in tables


 can name one index to two columns
 separate table is make for index, actual remain the same
 with column name it make row address, because when search the specific
data it show the complete row on table of that data.

CREATE INDEX index name


ON table (col name);

CREATE INDEX index name


ON table (col1, col2); // index on combination of column

To drop index

ALTER TABLE table_name


DROP INDEX index_name;

SHOW INDEXES FROM table_name;

1 SHOW INDEXES FROM table_name


2 IN database_name;

SELECT * FROM tablename USE INDEX (index name) WHERE column name LIKE
‘salman%’

Constraint:
Not Null; ensure value is not null

Unique; ensure all value in column are differenet

Primary Key; combination of not null and unique

Foreign key: same column in other table, cannot delete data of first table,
make relation between table

Can be null or duplicate

Columnameoftable2 INT FOREIGN KEY REFERENCES table1(coloftable1name)

To delete foreign key

ALTER TABLE tablename2 DROP CONSTRAINT FOREIGN KEY

To add foreign key to already establish table

ALTER TABLE tablename ADD FOREIGN KEY (keyname) REFERENCE tablename (colname)

Check Constraint (name= salman)--- check the condition other wise erro

Default (value)---- if we do not put value table put default value

SQL UNION , INTERSECT,EXCEPT


Show the result of two or more table in one table

SELECT * FROM table1 UNION SELECT * FROM table 2

Union:

 no of column of tables must be same


 data type must be same
 show data in sorting order
 remove data duplication
Union ALL

United tables but after first table entries show the second table
entries

Intersect: Show entry which is common in both tables

SELECT * FROM table1 INTERSECT SELECT * FROM table 2

Except: Show entry which is not common in both tables

SELECT * FROM table1 EXCEPT SELECT * FROM table 2

SQL - Views
View same sql query

Act as virtual table ( change apply on view effect the original table)

Used for security purpose to show the specific column and row to the
user/employee.

CREATE VIEW vwname AS SELECT * FROM firstdetail AS A INNER JOIN seconddetail


AS B ON B.id=A.Rollno; //create views

SELECT*FROM vwnname // show view

---------COLUMN SECURITY-----------

CREATE VIEW vwname2 AS SELECT A.*, B.id, B.nam FROM firstdetail AS A INNER
JOIN seconddetail AS B ON B.id=A.Rollno;

// select/show all colum of table A and id and nam column of B.


-------ALTER THE VIEW--------

ALTER VIEW vwname2 AS SELECT A.*, B.id, B.eml FROM firstdetail as A INNER
JOIN seconddetail AS B ON B.id=A.Rollno; // alter the views

-----------ROW SECURITY---------

CREATE VIEW vwname2 AS SELECT A.*, B.id, B.nam FROM firstdetail AS A INNER
JOIN seconddetail AS B ON B.id=A.Rollno WHERE age=”31”; // where hide rows

--------DROP THE VIEW-------------

DROP VIEW viewname // drop the view

--------Update THE VIEW-------------

UPDATE vwname2 SET Name="salman1011" WHERE id="1";

--------INSERT IN VIEW-------------

INSERT INTO viewname VALUES (“ VALU1”, “VALU2”,-----)


SQL SUBQUERY

Called inner or Nested query

Embedded in where clause

Work as condition

Return data that is used by main query

SELECT * FROM tablename WHERE col-id IN (SELECT col-id FROM tablename where
COL>1000/)

 col-id and table name must be same


 only one column used inside the subquery
 IN operator is used for subquery
 ORDERBY query can not used inside subquery used in main query
 We can use subquery with two tables
 Update and delete with subquery
 Can display particular columns with subquery, particular column in main
query.

Case Statement
EXISTS is a Boolean operator used in a subquery to test whether the inner
query returns any row. If it does, then the outer query proceeds. If not, the
outer query does not execute, and the entire SQL statement returns nothing.

SELECT "column_name1"
FROM "table_name1"
WHERE EXISTS
(SELECT *
FROM "table_name2"
WHERE "condition");
Case Statement

SELECT Name, Email, Address, Age , CASE WHEN name='salman' THEN'hello salman'
ELSE 'hello' END AS 'greeting' FROM firstdetail

Identity concepty
(Userid int PRIMARY KEY IDENTITY(2,1),

Id start with 2 not 1, through this we change the starting id

SQL STRING FUNCTION

The CAST function in SQL converts data from one data type to another. For
example, we can use the CAST function to convert numeric data into
character string data.
CAST (field name AS [data type]) from table

Das könnte Ihnen auch gefallen