0% found this document useful (0 votes)
48 views13 pages

SQL

A database contains tables that store data in a structured format of columns and rows. A table can have multiple columns but each row must have a unique primary key value. SQL is used to manage databases, with commands to retrieve, insert, update and delete data from tables. It provides tools like SELECT to query data and WHERE to filter results.

Uploaded by

Fatima Farooq
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
48 views13 pages

SQL

A database contains tables that store data in a structured format of columns and rows. A table can have multiple columns but each row must have a unique primary key value. SQL is used to manage databases, with commands to retrieve, insert, update and delete data from tables. It provides tools like SELECT to query data and WHERE to filter results.

Uploaded by

Fatima Farooq
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 13

A database is a collection of data that is organized in a manner that facilitates ease of

access, as well as efficient management and updating. It is made up of tables that store
relevant information.

A table stores and displays data in a structured format consisting of columns and rows.

Databases often contain multiple tables, each designed for a specific purpose.

A table has a specified number of columns but can have any number of rows.

A primary key is a field in the table that uniquely identifies the table records.

The primary key's main features:


 It must contain a unique value for each row.
 It cannot contain NULL values.

Tables are limited to ONE primary key each.

The primary key's value must be different for each row.

SQL stands for Structured Query Language.

SQL is used to access and manipulate a database.

MySQL is a program that understands SQL.

SQL can:
 Insert, update, or delete records in a database.
 Create new databases, table, stored procedures and views.
 Retrieve data from a database, etc.

SQL is an ANSI (American National Standards Institute) standard, but there are
different versions of the SQL language.

Most SQL database programs have their own proprietary extensions in addition to the
SQL standard, but all of them support the major commands.

The SQL SHOW statement displays information contained in the database and its
tables.
This helpful tool lets you keep track of your database contents and remind yourself
about the structure of your tables.

The SHOW DATABASES command lists the databases managed by the server.

To try out the SQL commands, install the MySQL engine and the PHPMyAdmin tool.

The easiest way to get MySQL and PHPMyAdmin is to install free tools like XAMPP or
WAMP, which include all necessary installers.

The SHOW TABLES command is used to display all of the tables in the currently
selected MySQL database.

SHOW COLUMNS displays information about the columns in a given table.

SHOW COLUMNS displays the following values for each table column:
 Field: column name
 Type: column data type
 Key: indicates whether the column is indexed
 Default: default value assigned to the column
 Extra: may contain any additional information that is available about a given
column

The SELECT statement is used to select data from a database.

The result is stored in a result table, which is called the result-set.

A query may retrieve information from selected columns or from all columns in the
table.

To create a simple SELECT statement, specify the name(s) of the column(s) you need
from the table. The syntax of the SQL SELECT Statement:
SELECT column_list
FROM table_name;
 column_list includes one or more columns from which data is retrieved
 table_name is the name of the table from which the information is retrieved

A SELECT statement retrieves zero or more rows from one or more database tables.

SQL allows to run multiple queries or commands at the same time.


SQL is case insensitive.
Remember to end each SQL statement with a semicolon to indicate that the statement is
complete and ready to be interpreted.

A single SQL statement can be placed on one or more text lines.

Multiple SQL statements can be combined on a single text line.

Combined with proper spacing and indenting, breaking up the commands into logical
lines will make your SQL statements much easier to read and maintain.

To retrieve all of the information contained in your table, place an asterisk (*) sign after
the SELECT command, rather than typing in each column names separately. In SQL,
the asterisk means all.

The SQL DISTINCT keyword is used in conjunction with SELECT to eliminate all
duplicate records and return only unique ones.

The basic syntax of DISTINCT is as follows:


SELECT DISTINCT column_name(s)
FROM table_name;

By default, all results that satisfy the conditions specified in the SQL statement are
returned. However, sometimes we need to retrieve just a subset of records. In MySQL,
this is accomplished by using the LIMIT keyword. The syntax for LIMIT is as follows:
SELECT column_name(s)
FROM table_name
LIMIT number_of_records;

You can also pick up a set of records from a particular offset using the following syntax:
SELECT column_name(s)
FROM table_name
LIMIT offset, number_of_records;

MySQL starts counting from zero, meaning that the offset of the first row is 0, not 1.

In SQL, you can provide the table name prior to the column name, by separating them
with a dot as follows:
SELECT table_name.column_name
FROM table_name;

The term for the above-mentioned syntax is called the "fully qualified name" of that
column. This form of writing is especially useful when working with multiple tables
that may share the same column names.

ORDER BY is used with SELECT to sort the returned data. The syntax for ORDER BY
is as follows:
SELECT * FROM table_name
ORDER BY column_name;

By default, the ORDER BY keyword sorts the results in ascending order. ORDER BY
can sort retrieved data by multiple columns. When using ORDER BY with more than
one column, separate the list of columns to follow ORDER BY with commas. The
ORDER BY command starts ordering in the same sequence as the columns. It will order
by the first column listed, then by the second, and so on.

The WHERE clause is used to extract only those records that fulfill a specified criterion.
The syntax for the WHERE clause:
SELECT column_name(s)
FROM table_name
WHERE condition;

Comparison Operators and Logical Operators are used in the WHERE clause to filter
the data to be selected. The following comparison operators can be used in the WHERE
clause:
Operator Description
= Equal
!= Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range

The BETWEEN operator selects values within a range. The first value must be lower
bound and the second value, the upper bound. The syntax for the BETWEEN clause is
as follows:
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;

When working with text columns, surround any text that appears in the statement with
single quotation marks ('). If your text contains an apostrophe (single quote), you
should use two single quote characters to escape the apostrophe.

Logical operators can be used to combine two Boolean values and return a result of
true, false, or null. The following operators can be used:
Operator Description
AND TRUE if both expressions are TRUE
OR TRUE if either expression is TRUE
IN TRUE if the operand is equal to one of a list of expressions
NOT Returns TRUE if the expression is not TRUE

When retrieving data using a SELECT statement, use logical operators in the WHERE
clause to combine multiple conditions.

If you want to select rows that satisfy all of the given conditions, use the logical
operator, AND. You can combine as many conditions as needed to return the desired
results.

If you want to select rows that satisfy at least one of the given conditions, you can use
the logical OR operator.

The SQL AND and OR conditions may be combined to test multiple conditions in a
query. These two operators are called conjunctive operators. When combining these
conditions, it is important to use parentheses, so that the order to evaluate each
condition is known. You can nest as many conditions as you need.

The IN operator is used when you want to compare a column with more than one
value.

The NOT IN operator allows you to exclude a list of specific values from the result set.

The CONCAT function is used to concatenate two or more text values and returns the
concatenating string. A concatenation results in a new column. The default column
name will be the CONCAT function. You can assign a custom name to the resulting
column using the AS keyword. And when you run the query, the column name appears
to be changed.

Arithmetic operators perform arithmetical operations on numeric operands. The


Arithmetic operators include addition(+), subtraction(-), multiplication(*) and
division(/). Parentheses can be used to force an operation to take priority over any other
operators. They are also used to improve code readability.

The UPPER function converts all letters in the specified string to uppercase.

The LOWER function converts the string to lowercase.

If there are characters in the string that are not letters, UPPER and LOWER functions
will have no effect on them.

The SQRT function returns the square root of given value in the argument.

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

The SUM function is used to calculate the sum for a column's values.

The DESC keyword sorts results in descending order.

The ASC sorts the results in ascending order.

A sub-query is a query within another query. Enclose the sub-query in parentheses.


There is no semicolon at the end of the sub-query, as it is part of our single query.

The LIKE keyword is useful when specifying a search condition within your WHERE
clause as follows:
SELECT column_name(s)
FROM table_name
WHERE column_name
LIKE pattern;

SQL pattern matching enables you to use "_" to match any single character and "%" to
match an arbitrary number of characters (including zero characters). The % wildcard
can be used multiple times within the same pattern.
The MIN function is used to return the minimum value of an expression in a SELECT
statement.

All of the SQL functions can be combined together to create a single expression.

One of the most beneficial features of SQL is the ability to combine data from two or
more tables. In SQL, "joining tables" means combining data from two or more tables. A
table join creates a temporary table showing the data from the joined tables.

Specify multiple table names in the FROM clause by comma-separating them.

Custom names can be used for tables as well. You can shorten the join statements by
giving the tables "nicknames".

The following are the types of JOIN that can be used in MySQL:
 INNER JOIN
 LEFT JOIN
 RIGHT JOIN

INNER JOIN is equivalent to JOIN. It returns rows when there is a match between the
tables. The syntax is:
SELECT table1.column_name, table2.column_name
FROM table1 INNER JOIN table2
ON table1.column_name = table2.column_name;

The ON keyword for specifying the inner join condition.

The image below demonstrates how INNER JOIN works:

Only the records matching the join condition are returned.

The LEFT JOIN returns all rows from the left table, even if there are no matches in the
right table. This means that if there are no matches for the ON clause in the table on the
right, the join will still return the rows from the first table in the result. The basic syntax
of LEFT JOIN is as follows:
SELECT table1.column1, table2.column2
FROM table1 LEFT OUTER JOIN table2
ON table1.column_name = table2.column_name;

The image below demonstrates how LEFT JOIN works:

If no match is found for a particular row, NULL is returned.

The RIGHT JOIN returns all rows from the right table, even if there are no matches in
the left table. The basic syntax of RIGHT JOIN is as follows:
SELECT table1.column1, table2.column2
FROM table1 RIGHT OUTER JOIN table2
ON table1.column_name = table2.column_name;

The OUTER keyword is optional, and can be omitted.

Occasionally, you might need to combine data from multiple tables into one
comprehensive dataset. This may be for tables with similar data within the same
database or maybe there is a need to combine similar data across databases or even
across servers. To accomplish this, use the UNION and UNION ALL operators.

UNION combines multiple datasets into a single dataset, and removes any existing
duplicates.

UNION ALL combines multiple datasets into one dataset, but does not remove
duplicate rows.

UNION ALL is faster than UNION, as it does not perform the duplicate removal
operation over the data set.
The UNION operator is used to combine the result-sets of two or more SELECT
statements. The duplicates will be removed. All SELECT statements within the UNION
must have the same number of columns. The columns must also have the same data
types. Also, the columns in each SELECT statement must be in the same order.

The syntax of UNION is as follows:


SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;

If your columns don't match exactly across all queries, you can use a NULL (or any
other) value such as:
SELECT FirstName, LastName, Company FROM businessContacts
UNION
SELECT FirstName, LastName, NULL FROM otherContacts;

UNION ALL selects all rows from each table and combines them into a single table. The
result set includes the duplicate rows as well.

The INSERT INTO statement is used to add new rows of data to a table in the
database. The SQL INSERT INTO syntax is as follows:
INSERT INTO table_name
VALUES (value1, value2, value3,...);

Make sure the order of the values is in the same order as the columns in the table. When
inserting records into a table using the SQL INSERT statement, you must provide a
value for every column that does not have a default value, or does not support NULL.
Alternatively, you can specify the table's column names in the INSERT INTO
statement:
INSERT INTO table_name (column1, column2, column3, ...,columnN)
VALUES (value1, value2, value3,...valueN);

You can specify your own column order, as long as the values are specified in the same
order as the columns. It is also possible to insert data into specific columns only.

The UPDATE statement allows us to alter data in the table. The basic syntax of an
UPDATE query with a WHERE clause is as follows:
UPDATE table_name
SET column1=value1, column2=value2, ...
WHERE condition;
You specify the column and its new value in a comma-separated list after the SET
keyword. If you omit the WHERE clause, all records in the table will be updated. It is
also possible to UPDATE multiple columns at the same time by comma-separating
them. You can specify the column order any way you like in the SET clause.

The DELETE statement is used to remove data from your table. DELETE queries work
much like UPDATE queries:
DELETE FROM table_name
WHERE condition;

If you omit the WHERE clause, all records in the table will be deleted. The DELETE
statement removes the data from the table permanently.

The CREATE TABLE statement is used to create a new table. Creating a basic table
involves naming the table and defining its columns and each column's data type. The
basic syntax for the CREATE TABLE statement is as follows:
CREATE TABLE table_name
(
column_name1 data_type(size),
column_name2 data_type(size),
column_name3 data_type(size),
....
columnN data_type(size)
);

 The column_names specify the names of the columns we want to create.


 The data_type parameter specifies what type of data the column can hold.
 The size parameter specifies the maximum length of the table's column.

varchar is the datatype that stores characters. You specify the number of characters in
the parentheses after the type. Data types specify the type of data for a particular
column. The most common data types:
 Numeric:
o INT - A normal-sized integer that can be signed or unsigned.
o FLOAT(M,D) - A floating-point number that cannot be unsigned. You can
optionally define the display length (M) and the number of decimals (D).
o DOUBLE(M,D) - A double precision floating-point number that cannot be
unsigned. You can optionally define the display length (M) and the number of
decimals (D).
 Date and Time:
o DATE - A date in YYYY-MM-DD format.
o DATETIME - A date and time combination in YYYY-MM-DD HH:MM:SS
format.
o TIMESTAMP - A timestamp, calculated from midnight, January 1, 1970
o TIME - Stores the time in HH:MM:SS format.
 String Type:
o CHAR(M) - Fixed-length character string. Size is specified in parenthesis. Max
255 bytes.
o VARCHAR(M) - Variable-length character string. Max size is specified in
parenthesis.
o BLOB - "Binary Large Objects" and are used to store large amounts of binary
data, such as images or other types of files.
o TEXT - Large amount of text data.

Choosing the correct data type for your columns is the key to good database design.

PRIMARY KEY ensures that a column has a unique identity. It is defined during table
creation. Specify the column name in the parentheses of the PRIMARY KEY keyword.

SQL constraints are used to specify rules for table data. The following are commonly
used SQL constraints:
 NOT NULL - Indicates that a column cannot contain any NULL value.
 UNIQUE - Does not allow to insert a duplicate value in a column. The UNIQUE
constraint maintains the uniqueness of a column in a table. More than one UNIQUE
column can be used in a table.
 PRIMARY KEY - Enforces the table to accept unique data for a specific column and
this constraint create a unique index for accessing the table faster.
 CHECK - Determines whether the value is valid or not from a logical expression.
 DEFAULT - While inserting data into a table, if no value is supplied to a column,
then the column gets the value set as DEFAULT.

During table creation, specify column level constraint(s) after the data type of that
column.
AUTO_INCREMENT allows a unique number to be generated when a new record is
inserted into a table. By default, the starting value for AUTO_INCREMENT is 1, and it
will increment by 1 for each new record.

The ALTER TABLE command is used to add, delete, or modify columns in an existing
table. You would also use the ALTER TABLE command to add and drop various
constraints on an existing table. The following SQL code adds a new column:
ALTER TABLE table_name
ADD column_name data_type;

All rows will have the default value in the newly added column, which, in this case, is
NULL.

The following SQL code demonstrates how to delete a column:


ALTER TABLE table_name
DROP COLUMN column_name;

The column, along with all of its data, will be completely removed from the table.

To delete the entire table, use the DROP TABLE command:


DROP TABLE table_name;

The ALTER TABLE command is also used to rename columns:


ALTER TABLE table_name
CHANGE old_column_name new_column_name data_type(size);

You can rename the entire table using the RENAME command:
RENAME TABLE old_table_name
TO new_table_name;

In SQL, a VIEW is a virtual table that is based on the result-set of an SQL statement. A
view contains rows and columns, just like a real table. The fields in a view are fields
from one or more real tables in the database. Views allow us to:
 Structure data in a way that users or classes of users find natural or intuitive.
 Restrict access to the data in such a way that a user can see and (sometimes) modify
exactly what they need and no more.
 Summarize data from various tables and use it to generate reports.

To create a VIEW:
CREATE VIEW view_name AS
SELECT column_name(s) FROM table_name WHERE condition;

The SELECT query can be as complex as you need it to be. It can contain multiple
JOINS and other commands. You can query the VIEW as you would query an actual
table. A VIEW always shows up-to-date data. The database engine uses the view's SQL
statement to recreate the data each time a user queries a view.

You can UPDATE a VIEW by using the following syntax:


CREATE OR REPLACE VIEW view_name AS
SELECT column_name(s) FROM table_name
WHERE condition;

You can DELETE a VIEW with the DROP VIEW command:


DROP VIEW view_name;

It is sometimes easier to drop a table and recreate it instead of using the ALTER TABLE
statement to change the table’s definition.

You might also like