Background: Alter Table
Background: Alter Table
SQL, Structured Query Language, is a programming language designed to manage data stored in
relational databases. SQL operates through simple, declarative statements. This keeps data
accurate and secure, and it helps maintain the integrity of databases, regardless of size.
Commands
ALTER TABLE
ALTER TABLE table_name
ADD column_name datatype;
AND
SELECT column_name(s)
FROM table_name
WHERE column_1 = value_1
AND column_2 = value_2;
AND is an operator that combines two conditions. Both conditions must be true for the row to be
included in the result set.
AS
SELECT column_name AS 'Alias'
FROM table_name;
AS is a keyword in SQL that allows you to rename a column or table using an alias.
AVG()
SELECT AVG(column_name)
FROM table_name;
AVG() is an aggregate function that returns the average value for a numeric column.
BETWEEN
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value_1 AND value_2;
The BETWEEN operator is used to filter the result set within a certain range. The values can be
numbers, text or dates.
CASE
SELECT column_name,
CASE
WHEN condition THEN 'Result_1'
WHEN condition THEN 'Result_2'
ELSE 'Result_3'
END
FROM table_name;
CASEstatements are used to create different outputs (usually in the SELECT statement). It is
SQL’s way of handling if-then logic.
COUNT()
SELECT COUNT(column_name)
FROM table_name;
COUNT() is a function that takes the name of a column as an argument and counts the number of
rows where the column is not NULL.
CREATE TABLE
CREATE TABLE table_name (
column_1 datatype,
column_2 datatype,
column_3 datatype
);
CREATE TABLE creates a new table in the database. It allows you to specify the name of the table
and the name of each column in the table.
DELETE
DELETE FROM table_name
WHERE some_column = some_value;
GROUP BY
SELECT column_name, COUNT(*)
FROM table_name
GROUP BY column_name;
GROUP BY is a clause in SQL that is only used with aggregate functions. It is used in
collaboration with the SELECT statement to arrange identical data into groups.
HAVING
SELECT column_name, COUNT(*)
FROM table_name
GROUP BY column_name
HAVING COUNT(*) > value;
HAVING was added to SQL because the WHERE keyword could not be used with aggregate
functions.
INNER JOIN
SELECT column_name(s)
FROM table_1
JOIN table_2
ON table_1.column_name = table_2.column_name;
An inner join will combine rows from different tables if the join condition is true.
INSERT
INSERT INTO table_name (column_1, column_2, column_3)
VALUES (value_1, 'value_2', value_3);
IS NULL and IS NOT NULL are operators used with the WHERE clause to test for empty values.
LIKE
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern;
LIKE is a special operator used with the WHERE clause to search for a specific pattern in a column.
LIMIT
SELECT column_name(s)
FROM table_name
LIMIT number;
LIMIT is a clause that lets you specify the maximum number of rows the result set will have.
MAX()
SELECT MAX(column_name)
FROM table_name;
MAX() is a function that takes the name of a column as an argument and returns the largest value
in that column.
MIN()
SELECT MIN(column_name)
FROM table_name;
MIN() is a function that takes the name of a column as an argument and returns the smallest
value in that column.
OR
SELECT column_name
FROM table_name
WHERE column_name = value_1
OR column_name = value_2;
OR is an operator that filters the result set to only include rows where either condition is true.
ORDER BY
SELECT column_name
FROM table_name
ORDER BY column_name ASC | DESC;
ORDER BY is a clause that indicates you want to sort the result set by a particular column either
alphabetically or numerically.
OUTER JOIN
SELECT column_name(s)
FROM table_1
LEFT JOIN table_2
ON table_1.column_name = table_2.column_name;
An outer join will combine rows from different tables even if the join condition is not met. Every
row in the left table is returned in the result set, and if the join condition is not met, then NULL
values are used to fill in the columns from the right table.
ROUND()
SELECT ROUND(column_name, integer)
FROM table_name;
ROUND() is a function that takes a column name and an integer as arguments. It rounds the values
in the column to the number of decimal places specified by the integer.
SELECT
SELECT column_name
FROM table_name;
SELECT statements are used to fetch data from a database. Every query will begin with SELECT.
SELECT DISTINCT
SELECT DISTINCT column_name
FROM table_name;
SELECT DISTINCT specifies that the statement is going to be a query that returns unique values
in the specified column(s).
SUM
SELECT SUM(column_name)
FROM table_name;
SUM() is a function that takes the name of a column as an argument and returns the sum of all the
values in that column.
UPDATE
UPDATE table_name
SET some_column = some_value
WHERE some_column = some_value;
WHERE
SELECT column_name(s)
FROM table_name
WHERE column_name operator value;
WHERE is a clause that indicates you want to filter the result set to include only rows where the
following condition is true.
WITH
SQL is incredibly powerful, and like every well-made development tool, it has a few commands
which it’s vital for a good developer to know. Here is a list of SQL queries that are really
important for coding & optimization. Each of the queries in our SQL tutorial is consequential to
almost every system that interacts with an SQL database.
With the SELECT command, users can define the columns that they want to get in the query
output. This command is also useful to get which column users want to see as the output table.
The SELECT statement is applied to pick data from a table. The data retrieved is put in a result
table, named the result-set. The output data is saved in a result table. This output table is also
termed as the result-set.
If you want to display all the attributes from a particular table, this is the right query to use:
The ordering of the result can also be set manually, using “asc ” for ascending and “desc” for
descending.
Ascending (ASC) is the default condition for the ORDER BY clause. In other words, if users
don’t specify ASC or DESC after the column name, then the result will be ordered in ascending
order only.
The SQL query below will select Name, Age columns from Patients table, then will filter them
by Age value to include records where Age is more than 40 and then will group records with
similar Age value and then finally will output them sorted by Name. The basic rule is that the
group by clause should always follow a where clause in a Select statement and must precede the
Order by clause.
Another sample of use of Group By: this expression will select records with a price lesser than
70 from Orders table, will group records with a similar price, will sort the output by price and
will also add the column COUNT(price) that will display how many records with similar price
were found:
Note: you should use the very same set of columns for both SELECT and GROUP BY
commands, otherwise you will get an error. Many thanks to Sachidannad for pointing out!
A view is a legitimate copy of a different table or sequence of tables. A view obtains its
information or data from the tables from previously created tables known as base tables. Base
tables are real tables. All procedures implemented on a view really modify the base table. Users
can use views just like the real or base tables. In view, users can apply various DDL, DML
commands such as update, insert into, and delete.
The following SQL query lists all the fields in a table’s primary key.
Primary, Unique, and Foreign are part of the constraints in SQL. Constraints are essential to the
scalability, compliance, and sincerity of the data. Constraints implement particular rules,
assuring the data adheres to the conditions outlined. For example, these are the laws imposed on
the columns of the database tables. These are applied to restrict the kind of data in the table. This
assures the efficiency and authenticity of the database.
18. Displaying Triggers
A Trigger is sort of an ‘event listener’ – i.e, it’s a pre-specified set of instructions that execute
when a certain event occurs. The list of defined triggers can be viewed using the following
query.
Improve your skills with SQL trainer (for beginner and advanced developers)
With this in mind, we can easily imagine an Orders table which likewise contains the indexed
customer ID field, along with details of each order placed by the customer. This table will
include the order Number, Quantity, Date, Item, and Price. In our first one of SQL examples,
imagine a situation where the zip and phone fields were transposed and all the phone numbers
were erroneously entered into the zip code field. We can easily fix this problem with the
following SQL statement:
The point of INNER JOIN, in this case, is to select records in the Customers table which have a
matching customer ID values in the Orders table and return only those records. Of course, there
are many types of JOIN, such as FULL, SELF, and LEFT, but for now, let’s keep things
interesting and move on to more diverse types of SQL queries.
The UNION keyword makes it possible to combine JOINS and other criteria to achieve very
powerful new table generation potential.
A SQL script is a collection of SQL elements and commands accumulated as a file in SQL
Scripts. This script file can include many SQL commands or PL/SQL codes. One can
utilize SQL Scripts to build, edit, design, execute, and delete files.
The — single line and the /* .. */ multi-line delimiters empower us to add useful comments to
scripts, but this is also used in another valuable way. Sometimes a section of code may not be in
use, but we don’t want to delete it, because we anticipate using it again. Here we can simply add
the comment delimiter to deactivate it momentarily:
1
2
3
4
5
/* This query below is commented so it won't execute*/
6 /*
7 SELECT item FROM Orders
8 WHERE date ALL = (SELECT Order_ID FROM Orders
9 WHERE quantity > 50)
1 */
0
/* the SQL query below the will be executed
1 ignoring the text after "--"
1 */
1
2 SELECT item -- single comment
1 FROM Orders -- another single comment
WHERE id
3 ALL = (SELECT ID FROM Orders
1 WHERE quantity > 25)
4
1
5
1
6
Although most databases are created using a UI such as Access or OpenOffice, it is important to
know how to create and delete databases and tables programmatically via code with SQL
statements. This is especially so when installing a new web app and the UI asks new users to
enter names for DBs to be added during installation.
Imagine that you decide to send a birthday card to your customers to show your appreciation for
their business, and so you want to add a birthday field to the Customers table. In these SQL
examples, you see how easy it is to modify existing tables with the ALTER statement:
If a table becomes corrupted with bad data you can quickly delete it like this:
Accurate indexing requires that the Primary Key column contains only unique values for this
purpose. This guarantees that JOIN statements will maintain integrity and produce valid matches.
Let’s create our Customers table again and establish the ID column as the Primary Key:
1CREATE TABLE Customers (
2ID int NOT NULL,
3Name varchar(80) NOT NULL,
4PRIMARY KEY (ID)
);
5
We can extend the functionality of the Primary Key so that it automatically increments from a
base. Change the ID entry above to add the AUTO_INCREMENT keyword as in the following
statement:
Performance pitfalls can be avoided in many ways. For example, avoid the time sinkhole of
forcing SQL Server to check the system/master database every time by using only a stored
procedure name, and never prefix it with SP_. Also setting NOCOUNT ON reduces the time
required for SQL Server to count rows affected by INSERT, DELETE, and other commands.
Using INNER JOIN with a condition is much faster than using WHERE clauses with conditions.
We advise developers to learn SQL server queries to an advanced level for this purpose. For
production purposes, these tips may be crucial to adequate performance. Notice that our tutorial
examples tend to favor the INNER JOIN.
This example will add any records from the year 2018 to the archive.
In cases where NULL values are allowed in a field, calculations on those values will produce
NULL results as well. This can be avoided by the use of the IFNULL operator. In this next
example, a value of zero is returned rather than a value of NULL when the calculation
encounters a field with a NULL value:
This line will return everything to the left of the second occurrence of “. ” and so, in this case, it
will return
1<a href="https://bytescout.com">www.bytescout.com</a>
Syntax
1SELECT COALESCE(NULL,NULL,'ByteScout',NULL,'Byte')
Output
ByteScout
Syntax
Output
27
1
2
3
4
5
6
7
8
9 SELECT eno,
1 dno,
0 salary,
DENSE_RANK() OVER (PARTITION BY dno ORDER BY salary) AS ranking
1
FROM employee;
1
1 ENO DNO SALARY RANKING
2 ---------- ---------- ---------- ----------
1 7933 10 1500 1
3 7788 10 2650 2
7831 10 6000 3
1 7362 20 900 1
4 7870 20 1200 2
1 7564 20 2575 3
5 7784 20 4000 4
1 7903 20 4000 4
7901 30 550 1
6 7655 30 1450 2
1 7522 30 1450 2
7 7844 30 1700 3
1 7493 30 1500 4
7698 30 2850 5
8
1
9
2
0
2
1
2
2
44. Query_partition_clause
The query_partition_clause breaks the output set into distributions, or collections, of data. The
development of the analytic query is limited to the confines forced by these partitions, related to
the process a GROUP BY clause modifies the performance of an aggregate function. If the
query_partition_clause is eliminated, the entire output collection is interpreted as a separate
partition.
The following query applies an OVER clause, so the average displayed is based on all the
records of the output set.
1
2
3
4
5
6
7
8 SELECT eno, dno, salary,
9 AVG(salary) OVER () AS avg_sal
FROM employee;
1
0
EO DNO SALARY AVG_SAL
1 ---------- ---------- ---------- ----------
1 7364 20 900 2173.21428
1 7494 30 1700 2173.21428
2 7522 30 1350 2173.21428
7567 20 3075 2173.21428
1 7652 30 1350 2173.21428
3 7699 30 2950 2173.21428
1 7783 10 2550 2173.21428
4 7789 20 3100 2173.21428
1 7838 10 5100 2173.21428
7845 30 1600 2173.21428
5 7877 20 1200 2173.21428
1 7901 30 1050 2173.21428
6 7903 20 3100 2173.21428
1 7935 10 1400 2173.21428
7
1
8
1
9
2
0
For example,
The above SQL query will give you the last eight records from the employee table where
rownum is a pseudo column. It indexes the data in an output set.
46. LAG
The LAG is applied to get data from a prior row. This is an analytical function. For example, the
following query gives the salary from the prior row to compute the difference between the salary
of the current row and that of the prior row. In this query, the ORDER BY of the LAG
function is applied. The default is 1 if you do not define offset. The arbitrary default condition
is given if the offset moves past the range of the window. The default is null if you do not define
default.
Syntax
1SELECT dtno,
2 eno,
3 emname,
4 job,
5 salary,
LAG(sal, 1, 0) OVER (PARTITION BY dtno ORDER BY salary) AS salary_prev
6
FROM employee;
7
Output
47. LEAD
The LEAD is also an analytical query that is applied to get data from rows extra down the output
set. The following query gives the salary from the next row to compute the deviation between the
salary of the prevailing row and the subsequent row. The default is 1 if you do not define offset.
The arbitrary default condition is given if the offset moves past the range of the window. The
default is null if you do not define default.
1 SELECT eno,
empname,
2
job,
3 salary,
4 LEAD(salary, 1, 0) OVER (ORDER BY salary) AS salary_next,
5 LEAD(salary, 1, 0) OVER (ORDER BY salary) - salary AS salary_diff
6 FROM employee;
7
8 ENO EMPNAME JOB SALARY SALARY_NEXT SALARY_DIFF
---------- ---------- --------- ---------- ---------- ----------
9 7369 STEVE CLERK 800 950 150
1 7900 JEFF CLERK 950 1100 150
0 7876 ADAMS CLERK 1100 1250 150
1 7521 JOHN SALESMAN 1250 1250 0
1 7654 MARK SALESMAN 1250 1300 50
7934 TANTO CLERK 1300 1500 200
1 7844 MATT SALESMAN 1500 1600 100
2 7499 ALEX SALESMAN 1600 2450 850
1 7782 BOON MANAGER 2450 2850 400
3 7698 BLAKE MANAGER 2850 2975 125
7566 JONES MANAGER 2975 3000 25
1
7788 SCOTT ANALYST 3000 3000 0
4 7902 FORD ANALYST 3000 5000 2000
1 7839 KING PRESIDENT 5000 0 -5000
5
1
6
1
7
1
8
1
9
2
0
2
1
2
2
2
3
2
4
48. PERCENT_RANK
The PERCENT_RANK analytic query. The ORDER BY clause is necessary for this query.
Excluding a partitioning clause from the OVER clause determines the entire output set is
interpreted as a separate partition. The first row of the standardized set is indicated 0 and the
last row of the set are indicated 1. For example, the SQL query example gives the following
output.
Syntax
1SELECT
2 prdid, SUM(amount),
3 PERCENT_RANK() OVER (ORDER BY SUM(amount) DESC) AS percent_rank
4 FROM sales
5 GROUP BY prdid
ORDER BY prdid;
6
Output
49. MIN
Utilizing a blank OVER clause converts the MIN into an analytic function. This is also an
analytical query. In this, the entire result set is interpreted as a single partition. It gives you the
minimum salary for all employees and their original data. For example, the following query is
displaying the use of MIN in the Select query.
1 SELECT eno,
2
3
4
5
6
7
8
9
1
empname,
0 dtno,
1 salary,
1 MIN(salary) OVER (PARTITION BY dtno) AS min_result
1 FROM employee;
2
1 ENO EMPNAME DTNO SALARY MIN_RESULT
3 ---------- ---------- ---------- ---------- ---------------
7782 CLARK 10 2450 1300
1 7839 KING 10 5000 1300
4 7934 MILLER 10 1300 1300
1 7566 JONES 20 2975 800
5 7902 FORD 20 3000 800
7876 ADAMS 20 1100 800
1
7369 SMITH 20 800 800
6 7788 SCOTT 20 3000 800
1 7521 WARD 30 1250 950
7 7844 TURNER 30 1500 950
1 7499 ALLEN 30 1600 950
7900 JAMES 30 950 950
8 7698 BLAKE 30 2850 950
1 7654 MARTIN 30 1250 950
9
2
0
2
1
2
2
2
3
50. MAX
Using a blank row OVER clause converts the MAX into an analytic function. The lack of a
partitioning clause indicates the entire output set is interpreted as a separate partition. This
gives the maximum salary for all employees and their original data. For example, the following
query displays the use of MAX in the select query.
1 SELECT eno,
2 empname,
3
4
5
6
7
8
9
1
0
dtno,
1 salary,
1 MAX(salary) OVER () AS max_result
1 FROM employee;
2
1 ENO EMPNAME DTNO SALARY MAX_RESULT
3 ---------- ---------- ---------- ---------- ----------
7369 SMITH 20 800 3000
1 7499 ALLEN 30 1600 3000
4 7521 WARD 30 1250 3000
1 7566 JONES 20 2975 3000
5 7654 MARTIN 30 1250 3000
1 7698 BLAKE 30 2850 3000
7782 CLARK 10 2450 3000
6 7788 SCOTT 20 3000 3000
1 7839 KING 10 5000 3000
7 7844 TURNER 30 1500 3000
1 7876 ADAMS 20 1100 3000
8 7900 JAMES 30 950 3000
7902 FORD 20 3000 3000
1 7934 MILLER 10 1300 3000
9
2
0
2
1
2
2
2
3
For example, the following query gives the 20 rows with 10 different values:
1 SELECT price
2 FROM sales_order
3 ORDER BY price;
4
PRICE
5
----------
6 100
7 100
8 200
9 200
300
1 300
0 400
1 400
1 500
1 500
600
2
1 PRICE
3 ----------
1 600
4 700
700
1 800
5 800
1 900
6 900
1 1000
1000
7
1 20 rows selected.
8
1
9
2
0
2
1
2
2
2
3
2
4
2
5
2
6
2
7
2
8
2
9
3
0
3
1
Example
1SELECT empid,
2 name,
3 dno,
4 salary,
5 job,
CORR(SYSDATE - joiningdate, salary) OVER () AS my_corr_val
6FROM employee;
7
Example
1SELECT empid,
2 name,
3 dno,
4 salary,
5 NTILE(6) OVER (ORDER BY salary) AS container_no
FROM employee;
6
If there is more than one account after dropping nulls, the STDDEV function gives the result of
the STDDEV_SAMP. Using an empty OVER clause converts the STDDEV query result into an
analytic query. The absence of a partitioning indicates the entire output set is interpreted as a
particular partition, so we accept the standard deviation of the salary and the primary data.
The MEASURES clause specifies the column result that will be provided for each match.
Syntax
Example
1DEFINE
2 UP AS UP.products_sold > PREV(UP.products_sold),
3 FLAT AS FLAT.products_sold = PREV(FLAT.products_sold),
4 DOWN AS DOWN.products_sold < PREV(DOWN.products_sold)
57. FIRST_VALUE
The simplest way to get analytic functions is to begin by studying aggregate functions. An
aggregate function collects or gathers data from numerous rows into a unique result row. For
instance, users might apply the AVG function to get an average of all the salaries in the
EMPLOYEE table. Let’s take a look at how First_Value can be used. The primary explanation
for the FIRST_VALUE analytic function is displayed below.
Syntax:
1FIRST_VALUE
2 { (expr) [NULLS ]
3 | (expr [NULLS ])
4 }
OVER (analytic clause)
5
Example
1SELECT eno,
2 dno,
3 salary,
4 FIRST_VALUE(salary) IGNORE NULLS
5 OVER (PARTITION BY dno ORDER BY salary) AS lowest_salary_in_dept
FROM employee;
6
58. LAST_VALUE
The primary explanation for the LAST_VALUE analytic query or function is displayed below.
1Syntax: LAST_VALUE
2 { (expr) [ { NULLS ]
3 | (expr [ NULLS ])
4 OVER (analytic clause)
The LAST_VALUE analytic query is related to the LAST analytic function. The function
enables users to get the last output from an organized column. Applying the default windowing
the output can be surprising. For example,
1SELECT eno,
2 dno,
3 salary,
4 LAST_VALUE(salary) IGNORE NULLS
5 OVER (PARTITION BY dno ORDER BY salary) AS highest_salary_in_dept
FROM employee;
6
59. Prediction
The design sample foretells the gender and age of clients who are most expected to adopt an
agreement card (target = 1). The PREDICTION function takes the price matrix correlated with
the design and applies for marital status, and house size as predictors. The syntax of the
PREDICTION function can also apply a piece of arbitrary GROUPING information when
getting a partitioned model.
1
2
3
SELECT client_gender, COUNT(*) AS ct, ROUND(AVG(age)) AS average_age
4 FROM mining_data_shop
5 WHERE PREDICTION(sample COST MODEL
6 USING client_marital_status, house_size) = 1
7 GROUP BY client_gender
ORDER BY client_gender;
8
9
CUST_GENDER CNT AVG_AGE
1 ------------ ---------- --------
0
1
1