1. POSTGRESQL command
sory nih ga sempet rapihin isinya…kl yg baca nga ngerti maap yaaa =P….
lagian ini tutor gabungan dari tutor yg ada di google…tujuan gw pasang disini yaa buat gw sendiri jg sih
kl lagi lupa command postgres tinggal gw buka blog gw aja hehehehe…. tp kl ada temens yang merasa senang jg dgn isinya yaa…gw jd tambah seneng aja.hehehe
buat database baru:
# createdb test
CREATE DATABASE
atau
postgres=# CREATE DATABASE testaja;
delete database:
# destroydb test
DROP DATABASE test
buat user baru:
postgres=# CREATE USER ganteng WITH PASSWORD ‘passwordaja’;
Create a user with no password:
CREATE USER jonathan;
Create a user with a password:
CREATE USER davide WITH PASSWORD ‘jw8s0F4′;
Create a user with a password that is valid until the end of 2004. After one second has ticked in 2005, the password is no longer valid.
CREATE USER miriam WITH PASSWORD ‘jw8s0F4′ VALID UNTIL ’2005-01-01′;
Create an account where the user can create databases:
CREATE USER manuel WITH PASSWORD ‘jw8s0F4′ CREATEDB;
Altering users
If you want to change a user you can use the ALTER USER SQL command, which is similar to the CREATE USER command except you can’t change the sysid.
ALTER USER name [ [ WITH ]
[ ENCRYPTED | UNENCRYPTED ] PASSWORD ‘password’
| CREATEDB | NOCREATEDB
| CREATEUSER | NOCREATEUSER
| VALID UNTIL ‘abstime’ ]
Say we wanted to allow alice to create databases:
template1=# ALTER USER alice CREATEDB;
ALTER USER
You can also rename users using:
ALTER USER name RENAME TO newname;
To rename bob to colin we could use:
template1=# ALTER USER bob RENAME TO colin;
ALTER USER
Changing a user password
One of the most common reasons for wanting to alter a user is to change the user’s password
template1=# ALTER USER colin WITH PASSWORD ‘letmein’;
ALTER USER
Checking pg_users again, we can see the changes:
alice | 101 | t | f | f | ******** | |
colin | 102 | f | f | f | ******** | 2030-01-31 00:00:0
Delete a user:
$ dropuser SuperDude
delete user:
# dropuser ganteng
Groups
Groups are entirely optional in postgresql. They are only used to simplify granting and revoking privileges for the db admin, and users do not need to be a member of any group.
Creating Groups
Unlike creating users, you can only create groups using SQL. The command is:
CREATE GROUP name [ [ WITH ]
SYSID gid
| USER username [, ...]]
If we wanted to create a group with alice as an initial member, we can use:
template1=# CREATE GROUP sales WITH USER alice;
CREATE GROUP
Adding or removing users from groups
You can add or remove users from groups after they have been created using the ALTER GROUP command:
ALTER GROUP groupname [ADD|DROP] USER username [, ... ]
Imagine we wanted to add bob to the sales group and remove alice:
template1=# ALTER GROUP sales ADD USER bob;
ALTER GROUP
template1=# ALTER GROUP sales DROP USER alice;
ALTER GROUP
Viewing groups
We can see group membership by viewing the pg_group system table. In this example I’ve added alice back into the sales group.
template1=# select * from pg_group ;
groname | grosysid | grolist
———+———-+———
sales | 100 | {102,101}
(1 row)
The grolist column shows a list of user ids that are in the group. If you want to see the usernames in a particular group you can use:
template1=# select usename from pg_user, (select grolist from pg_group where groname = ‘sales’) as groups where usesysid = ANY(grolist) ;
usename
———
alice
bob
(2 rows)
Renaming Groups
You can also rename groups using:
ALTER GROUP groupname RENAME TO newname
To rename sales to presales we would use:
template1=# ALTER GROUP sales RENAME TO presales;
ALTER GROUP
Removing Groups
Removing groups can be done using DROP GROUP
template1=# DROP GROUP presales;
DROP GROUP
Authentication and Authorisation
PostgreSQL has two levels of authorisation, one at the database level, called host based authentication, and one at a finer level on tables, views and sequences.
Host-Based Authentication using pg_hba.conf
The host-based authentication is controlled by the pg_hba.conf file and defines which users can connect to which database and how they can connect to it. The file is a list of declarations, which are searched in order until one of the lines match. They list the access method, the database they are trying to connect to, the user trying to connect and the authentication method being used.
Access methods
There are three different access methods:
local
This is for a user connecting via the unix socket on the local machine. A line for this method will be in the form:
local DATABASE USER METHOD [OPTION]
host
This is matches connections over a TCP/IP network connection
host DATABASE USER IP-ADDRESS IP-MASK METHOD [OPTION]
host DATABASE USER IP-ADDRESS/CIDR-MASK METHOD [OPTION]
hostnossl, hostssl
This is for users connecting over a non-encrypted or an encrypted TCP/IP connection using SSL. This is so that you can treat secure and non-secure connections differently. For example you might be happy to have clear text passwords over SSL, but only allow MD5 over non-secure connections.
hostnossl DATABASE USER IP-ADDRESS IP-MASK METHOD [OPTION]
hostnossl DATABASE USER IP-ADDRESS/CIDR-MASK METHOD [OPTION]
hostssl DATABASE USER IP-ADDRESS IP-MASK METHOD [OPTION]
hostssl DATABASE USER IP-ADDRESS/CIDR-MASK METHOD [OPTION]
You can list several databases by separating them by commas. There are two special database names, all and sameuser. all allows the person to connect to all databases on the server. sameuser allows the user to connect to a database with the same name as the user connecting. You can also supply a filename which lists databases they can connect to by using @filename where filename is a file in the same directory as the pg_hba.conf.
You can also list several users by separating them by commas. You can specify groups by prefixing the name with a +. Again you can use a filename with users in by using @filename where filename is a file in the same directory as pg_hba.conf. There is the special username all, which matches any user.
Authentication Methods
trust
This method allows any user to connect without a password. This should be avoided unless you know what you are doing as it could be a security risk.
reject
This is the reverse of trust, as it rejects any one. This is particularly useful where you want to enable access to a range of addresses, but want to block a particular host in that range.
host sales alice 10.0.0.128 255.255.255.255 reject
host sales alice 10.0.0.0 255.255.0.0 md5
password
This method allows someone to connect providing they have given the correct password for their user in the pg_shadow table. If the password field in that table is null, then they will be rejected. The password is sent in cleartext, so you probably only want to enable this for hostssl connections.
crypt
This is like password, except it is encrypted with the trivial unix crypt encryption. This is not a very strong encryption, so I suggest you don’t use this.
md5
This is like crypt and password, except it uses the stronger MD5 to encrypt the password. If you have to use non-ssl connections, I recommend you using this method.
ident
With network connections, this method uses the ident protocol (RFC1413) to check which user on the remote system owns the network connection being used to talk to the server. This is easy to spoof, so you shouldn’t reply on this for unsecured networks. I would recommend against it on all networks.
With local connections, it uses the unix user connecting to the unix socket and is much more secure. This allows local users to connect without a password.
This is the only method that requires an option, which is the name of a map in pg_ident.conf, which maps remote users to postgresql users. The format of pg_ident.conf is:
map unixuser postgresuser
This allows you to have the same remote user map to different postgres users when they connect to different databases,
There is a special map name called sameuser, which uses the same remote username for the postgresql name.
krb4, krb5
These allow you to use kerberos authentication.
pam
This method allows you to authenticate users against the local system’s pam (pluggable authentication modules) subsystem.
For local connections, I would recommend ident, password, crypt or md5. For hostssl connections any of the password methods will work, but md5 is preferable. For host and hostnossl, I can only recommend md5 and hostssl should be used in preference to host and hostnossl.
local all postgres ident sameuser
hostssl all postgres 0.0.0.0 0.0.0.0 md5
local sameuser all ident sameuser
hostssl sameuser all 10.0.0.0 255.255.255.0 md5
hostssl sales alice 10.0.0.1/32 md5
Permissions
Every object (tables, views and sequences) have an owner, which is the person that created it. The owner, or a superuser, can set permissions on the object. Permissions are made up of a user or group name and a set of rights. These rights described in the table below.
Library versionsPrivilege short name Description
SELECT r Can read data from the object.
INSERT a Can insert data into the object.
UPDATE w Can change data in the object.
DELETE d Can delete data from the object.
RULE R Can create a rule on the table
REFERENCES x Can create a foreign key to a table. Need this on both sides of the key.
TRIGGER t Can create a trigger on the table.
TEMPORARY T Can create a temporary table.
EXECUTE X Can run the function.
USAGE U Can use the procedural language.
ALL All appropriate privileges. For tables, this equates to arwdRxt
You can apply these privileges to users, groups or a special target called PUBLIC, which is any user on the system.
Viewing privileges
You can view permissions using the \z command in psql. You can use \d to view the owner.
sales=# \dp
Access privileges for database “sales”
Schema | Table | Access privileges
——–+—————————-+————————————-
public | inventory | {postgres=a*r*w*d*R*x*t*/postgres,
bob=rw/postgres,
“group sales=rwd/postgres”}
public | inventory_inventory_id_seq |
public | suppliers | {postgres=a*r*w*d*R*x*t*/postgres,
alice=arwdRxt/postgres,
bob=r/postgres}
public | suppliers_supplier_id_seq |
(4 rows)
In this example, we can see that postgres has all privileges to both tables. Bob has read and write and sales group has read, write and delete on the inventory table. Alice has all privileges and bob has read on the suppliers table. The * for postgres means that they have the privilege to grant that privilege. The /postgres tells you who granted those privileges.
Adding privileges
You can assign privileges using the GRANT command.
GRANT { { SELECT | INSERT | UPDATE | DELETE | RULE | REFERENCES | TRIGGER }
[,...] | ALL [ PRIVILEGES ] }
ON [ TABLE ] tablename [, ...]
TO { username | GROUP groupname | PUBLIC } [, ...] [ WITH GRANT OPTION ]
The WITH GRANT OPTION allows you give the person you are granting the privileges the ability to grant that privilege themselves. We can give bob the ability to make any changes to the data in suppliers using:
GRANT INSERT, UPDATE, DELETE ON TABLE suppliers TO bob;
Removing privileges
You can also remove privileges using the REVOKE which has the same syntax as the GRANT.
REVOKE [ GRANT OPTION FOR ]
{ { SELECT | INSERT | UPDATE | DELETE | RULE | REFERENCES | TRIGGER }
[,...] | ALL [ PRIVILEGES ] }
ON [ TABLE ] tablename [, ...]
FROM { username | GROUP groupname | PUBLIC } [, ...]
[ CASCADE | RESTRICT ]
GRANT OPTION FOR allows you to remove the ability to grant privileges to others, and not the privileges themselves. Suppose you want to remove privileges from bob, and anyone he has granted it to, we can use the CASCADE option.
REVOKE INSERT UPDATE DELETE ON TABLE suppliers FROM bob CASCASE
Column Level Privileges
PostgreSQL doesn’t directly support privileges at the column level but you can fake the, using views. To do this, you create a view with all the columns you want that person to see and grant them privileges to view that view.
Changing Ownership
It is possible to change the ownership of objects using the ALTER TABLE:
ALTER TABLE suppliers OWNER TO bob;
This can be time consuming to do if you have a lot of tables. A quicker, but possibly dodgy way to fix this is to use the following untested SQL command. You need to set relowner to the sysid of the new owner, which you can find by checking pg_shadow.
UPDATE pg_class SET relowner = 100
WHERE pg_namespace.oid = pg_class.relnamespace
AND pg_namespace.nspname = ‘public’;
===========================================================
Examples
Create table films and table distributors:
CREATE TABLE films (
code CHARACTER(5) CONSTRAINT firstkey PRIMARY KEY,
title CHARACTER VARYING(40) NOT NULL,
did DECIMAL(3) NOT NULL,
date_prod DATE,
kind CHAR(10),
len INTERVAL HOUR TO MINUTE
);
CREATE TABLE distributors (
did DECIMAL(3) PRIMARY KEY DEFAULT NEXTVAL(‘serial’),
name VARCHAR(40) NOT NULL CHECK (name <> ”)
);
Create a table with a 2-dimensional array:
CREATE TABLE array (
vector INT[][]
);
Define a unique table constraint for the table films. Unique table constraints can be defined on one or more columns of the table:
CREATE TABLE films (
code CHAR(5),
title VARCHAR(40),
did DECIMAL(3),
date_prod DATE,
kind VARCHAR(10),
len INTERVAL HOUR TO MINUTE,
CONSTRAINT production UNIQUE(date_prod)
);
Define a check column constraint:
CREATE TABLE distributors (
did DECIMAL(3) CHECK (did > 100),
name VARCHAR(40)
);
Define a check table constraint:
CREATE TABLE distributors (
did DECIMAL(3),
name VARCHAR(40)
CONSTRAINT con1 CHECK (did > 100 AND name <> ”)
);
Define a primary key table constraint for the table films. Primary key table constraints can be defined on one or more columns of the table.
CREATE TABLE films (
code CHAR(5),
title VARCHAR(40),
did DECIMAL(3),
date_prod DATE,
kind VARCHAR(10),
len INTERVAL HOUR TO MINUTE,
CONSTRAINT code_title PRIMARY KEY(code,title)
);
Define a primary key constraint for table distributors. The following two examples are equivalent, the first using the table constraint syntax, the second the column constraint notation.
CREATE TABLE distributors (
did DECIMAL(3),
name CHAR VARYING(40),
PRIMARY KEY(did)
);
CREATE TABLE distributors (
did DECIMAL(3) PRIMARY KEY,
name VARCHAR(40)
);
This assigns a literal constant default value for the column name, and arranges for the default value of column did to be generated by selecting the next value of a sequence object. The default value of modtime will be the time at which the row is inserted.
CREATE TABLE distributors (
name VARCHAR(40) DEFAULT ‘luso films’,
did INTEGER DEFAULT NEXTVAL(‘distributors_serial’),
modtime TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Define two NOT NULL column constraints on the table distributors, one of which is explicitly given a name:
CREATE TABLE distributors (
did DECIMAL(3) CONSTRAINT no_null NOT NULL,
name VARCHAR(40) NOT NULL
);
Define a unique constraint for the name column:
CREATE TABLE distributors (
did DECIMAL(3),
name VARCHAR(40) UNIQUE
);
The above is equivalent to the following specified as a table constraint:
CREATE TABLE distributors (
did DECIMAL(3),
name VARCHAR(40),
UNIQUE(name)
);
UPDATE DATA
———–
To perform an update, you need three pieces of information:
1. The name of the table and column to update,
2. The new value of the column,
3. Which row(s) to update.
Recall from section 3 Data Definition that SQL does not, in general, provide a unique identifier for rows. Therefore it is not necessarily possible to directly specify which row to update. Instead, you specify which conditions a row must meet in order to be updated. Only if you have a primary key in the table (no matter whether you declared it or not) can you reliably address individual rows, by choosing a condition that matches the primary key. Graphical database access tools rely on this fact to allow you to update rows individually.
For example, this command updates all products that have a price of 5 to have a price of 10:
UPDATE products SET price = 10 WHERE price = 5;
This may cause zero, one, or many rows to be updated. It is not an error to attempt an update that does not match any rows.
Let’s look at that command in detail. First is the key word UPDATE followed by the table name. As usual, the table name may be schema-qualified, otherwise it is looked up in the path. Next is the key word SET followed by the column name, an equals sign and the new column value. The new column value can be any scalar expression, not just a constant. For example, if you want to raise the price of all products by 10% you could use:
UPDATE products SET price = price * 1.10;
As you see, the expression for the new value can refer to the existing value(s) in the row. We also left out the WHERE clause. If it is omitted, it means that all rows in the table are updated. If it is present, only those rows that match the WHERE condition are updated. Note that the equals sign in the SET clause is an assignment while the one in the WHERE clause is a comparison, but this does not create any ambiguity. Of course, the WHERE condition does not have to be an equality test. Many other operators are available (see section 7 Functions and Operators). But the expression needs to evaluate to a Boolean result.
You can update more than one column in an UPDATE command by listing more than one assignment in the SET clause. For example:
UPDATE mytable SET a = 5, b = 3, c = 1 WHERE a > 0;
DELETE DATA
———–
So far we have explained how to add data to tables and how to change data. What remains is to discuss how to remove data that is no longer needed. Just as adding data is only possible in whole rows, you can only remove entire rows from a table. In the previous section we explained that SQL does not provide a way to directly address individual rows. Therefore, removing rows can only be done by specifying conditions that the rows to be removed have to match. If you have a primary key in the table then you can specify the exact row. But you can also remove groups of rows matching a condition, or you can remove all rows in the table at once.
You use the DELETE command to remove rows; the syntax is very similar to the UPDATE command. For instance, to remove all rows from the products table that have a price of 10, use
DELETE FROM products WHERE price = 10;
If you simply write
DELETE FROM products;
then all rows in the table will be deleted! Caveat programmer.
5.1 Overview
The process of retrieving or the command to retrieve data from a database is called a query. In SQL the SELECT command is used to specify queries. The general syntax of the SELECT command is
SELECT select_list FROM table_expression [sort_specification]
The following sections describe the details of the select list, the table expression, and the sort specification.
A simple kind of query has the form
SELECT * FROM table1;
Assuming that there is a table called table1, this command would retrieve all rows and all columns from table1. (The method of retrieval depends on the client application. For example, the psql program will display an ASCII-art table on the screen, while client libraries will offer functions to extract individual values from the query result.) The select list specification * means all columns that the table expression happens to provide. A select list can also select a subset of the available columns or make calculations using the columns. For example, if table1 has columns named a, b, and c (and perhaps others) you can make the following query:
SELECT a, b + c FROM table1;
(assuming that b and c are of a numerical data type). See section 5.3 Select Lists for more details.
FROM table1 is a particularly simple kind of table expression: it reads just one table. In general, table expressions can be complex constructs of base tables, joins, and subqueries. But you can also omit the table expression entirely and use the SELECT command as a calculator:
SELECT 3 * 4;
This is more useful if the expressions in the select list return varying results. For example, you could call a function this way:
SELECT random();
example:
select * from produk order by produk_no desc;
–> liat data yg ada di tabel produk berdasar kolom produk_no yg di sort descending
————————————————————————————
SELECT — retrieve rows from a table or view
Synopsis
SELECT [ ALL | DISTINCT [ ON ( expression [, ...] ) ] ]
* | expression [ AS output_name ] [, ...]
[ FROM from_item [, ...] ]
[ WHERE condition ]
[ GROUP BY expression [, ...] ]
[ HAVING condition [, ...] ]
[ { UNION | INTERSECT | EXCEPT } [ ALL ] select ]
[ ORDER BY expression [ ASC | DESC | USING operator ] [,
...] ]
[ LIMIT { count | ALL } ]
[ OFFSET start ]
[ FOR { UPDATE | SHARE } [ OF table_name [, ...] ] [
NOWAIT ] [...] ]
where from_item can be one of:
[ ONLY ] table_name [ * ] [ [ AS ] alias [ ( column_alias
[, ...] ) ] ]
( select ) [ AS ] alias [ ( column_alias [, ...] ) ]
function_name ( [ argument [, ...] ] ) [ AS ] alias [ (
column_alias [, ...] | column_definition [, ...] ) ]
function_name ( [ argument [, ...] ] ) AS (
column_definition [, ...] )
from_item [ NATURAL ] join_type from_item [ ON
join_condition | USING ( join_column [, ...] ) ]
Description
SELECT retrieves rows from zero or more tables. The general processing of SELECT is as follows:
1. All elements in the FROM list are computed. (Each element in the FROM list is a real or virtual table.) If more than one element is specified in the FROM list, they are cross-joined together. (See FROM Clause below.)
2. If the WHERE clause is specified, all rows that do not satisfy the condition are eliminated from the output. (See WHERE Clause below.)
3. If the GROUP BY clause is specified, the output is divided into groups of rows that match on one or more values. If the HAVING clause is present, it eliminates groups that do not satisfy the given condition. (See GROUP BY Clause and HAVING Clause below.)
4. The actual output rows are computed using the SELECT output expressions for each selected row. (See SELECT List below.)
5. Using the operators UNION, INTERSECT, and EXCEPT, the output of more than one SELECT statement can be combined to form a single result set. The UNION operator returns all rows that are in one or both of the result sets. The INTERSECT operator returns all rows that are strictly in both result sets. The EXCEPT operator returns the rows that are in the first result set but not in the second. In all three cases, duplicate rows are eliminated unless ALL is specified. (See UNION Clause, INTERSECT Clause, and EXCEPT Clause below.)
6. If the ORDER BY clause is specified, the returned rows are sorted in the specified order. If ORDER BY is not given, the rows are returned in whatever order the system finds fastest to produce. (See ORDER BY Clause below.)
7. DISTINCT eliminates duplicate rows from the result. DISTINCT ON eliminates rows that match on all the specified expressions. ALL (the default) will return all candidate rows, including duplicates. (See DISTINCT Clause below.)
8. If the LIMIT or OFFSET clause is specified, the SELECT statement only returns a subset of the result rows. (See LIMIT Clause below.)
9. If FOR UPDATE or FOR SHARE is specified, the SELECT statement locks the selected rows against concurrent updates. (See FOR UPDATE/FOR SHARE Clause below.)
You must have SELECT privilege on a table to read its values. The use of FOR UPDATE or FOR SHARE requires UPDATE privilege as well.
Parameters
FROM Clause
The FROM clause specifies one or more source tables for the SELECT. If multiple sources are specified, the result is the Cartesian product (cross join) of all the sources. But usually qualification conditions are added to restrict the returned rows to a small subset of the Cartesian product.
The FROM clause can contain the following elements:
table_name
The name (optionally schema-qualified) of an existing table or view. If ONLY is specified, only that table is scanned. If ONLY is not specified, the table and all its descendant tables (if any) are scanned. * can be appended to the table name to indicate that descendant tables are to be scanned, but in the current version, this is the default behavior. (In releases before 7.1, ONLY was the default behavior.) The default behavior can be modified by changing the sql_inheritance configuration option.
alias
A substitute name for the FROM item containing the alias. An alias is used for brevity or to eliminate ambiguity for self-joins (where the same table is scanned multiple times). When an alias is provided, it completely hides the actual name of the table or function; for example given FROM foo AS f, the remainder of the SELECT must refer to this FROM item as f not foo. If an alias is written, a column alias list can also be written to provide substitute names for one or more columns of the table.
select
A sub-SELECT can appear in the FROM clause. This acts as though its output were created as a temporary table for the duration of this single SELECT command. Note that the sub-SELECT must be surrounded by parentheses, and an alias must be provided for it. A VALUES command can also be used here.
function_name
Function calls can appear in the FROM clause. (This is especially useful for functions that return result sets, but any function can be used.) This acts as though its output were created as a temporary table for the duration of this single SELECT command. An alias may also be used. If an alias is written, a column alias list can also be written to provide substitute names for one or more attributes of the function’s composite return type. If the function has been defined as returning the record data type, then an alias or the key word AS must be present, followed by a column definition list in the form ( column_name data_type [, ... ] ). The column definition list must match the actual number and types of columns returned by the function.
join_type
One of
* [ INNER ] JOIN
* LEFT [ OUTER ] JOIN
* RIGHT [ OUTER ] JOIN
* FULL [ OUTER ] JOIN
* CROSS JOIN
For the INNER and OUTER join types, a join condition must be specified, namely exactly one of NATURAL, ON join_condition, or USING (join_column [, ...]). See below for the meaning. For CROSS JOIN, none of these clauses may appear. A JOIN clause combines two FROM items. Use parentheses if necessary to determine the order of nesting. In the absence of parentheses, JOINs nest left-to-right. In any case JOIN binds more tightly than the commas separating FROM items. CROSS JOIN and INNER JOIN produce a simple Cartesian product, the same result as you get from listing the two items at the top level of FROM, but restricted by the join condition (if any). CROSS JOIN is equivalent to INNER JOIN ON (TRUE), that is, no rows are removed by qualification. These join types are just a notational convenience, since they do nothing you couldn’t do with plain FROM and WHERE. LEFT OUTER JOIN returns all rows in the qualified Cartesian product (i.e., all combined rows that pass its join condition), plus one copy of each row in the left-hand table for which there was no right-hand row that passed the join condition. This left-hand row is extended to the full width of the joined table by inserting null values for the right-hand columns. Note that only the JOIN clause’s own condition is considered while deciding which rows have matches. Outer conditions are applied afterwards. Conversely, RIGHT OUTER JOIN returns all the joined rows, plus one row for each unmatched right-hand row (extended with nulls on the left). This is just a notational convenience, since you could convert it to a LEFT OUTER JOIN by switching the left and right inputs. FULL OUTER JOIN returns all the joined rows, plus one row for each unmatched left-hand row (extended with nulls on the right), plus one row for each unmatched right-hand row (extended with nulls on the left).
ON join_condition
join_condition is an expression resulting in a value of type boolean (similar to a WHERE clause) that specifies which rows in a join are considered to match.
USING (join_column [, ...])
A clause of the form USING ( a, b, … ) is shorthand for ON left_table.a = right_table.a AND left_table.b = right_table.b …. Also, USING implies that only one of each pair of equivalent columns will be included in the join output, not both.
NATURAL
NATURAL is shorthand for a USING list that mentions all columns in the two tables that have the same names.
WHERE Clause
The optional WHERE clause has the general form
WHERE condition
where condition is any expression that evaluates to a result of type boolean. Any row that does not satisfy this condition will be eliminated from the output. A row satisfies the condition if it returns true when the actual row values are substituted for any variable references.
GROUP BY Clause
The optional GROUP BY clause has the general form
GROUP BY expression [, ...]
GROUP BY will condense into a single row all selected rows that share the same values for the grouped expressions. expression can be an input column name, or the name or ordinal number of an output column (SELECT list item), or an arbitrary expression formed from input-column values. In case of ambiguity, a GROUP BY name will be interpreted as an input-column name rather than an output column name.
Aggregate functions, if any are used, are computed across all rows making up each group, producing a separate value for each group (whereas without GROUP BY, an aggregate produces a single value computed across all the selected rows). When GROUP BY is present, it is not valid for the SELECT list expressions to refer to ungrouped columns except within aggregate functions, since there would be more than one possible value to return for an ungrouped column.
HAVING Clause
The optional HAVING clause has the general form
HAVING condition
where condition is the same as specified for the WHERE clause.
HAVING eliminates group rows that do not satisfy the condition. HAVING is different from WHERE: WHERE filters individual rows before the application of GROUP BY, while HAVING filters group rows created by GROUP BY. Each column referenced in condition must unambiguously reference a grouping column, unless the reference appears within an aggregate function.
The presence of HAVING turns a query into a grouped query even if there is no GROUP BY clause. This is the same as what happens when the query contains aggregate functions but no GROUP BY clause. All the selected rows are considered to form a single group, and the SELECT list and HAVING clause can only reference table columns from within aggregate functions. Such a query will emit a single row if the HAVING condition is true, zero rows if it is not true.
SELECT List
The SELECT list (between the key words SELECT and FROM) specifies expressions that form the output rows of the SELECT statement. The expressions can (and usually do) refer to columns computed in the FROM clause. Using the clause AS output_name, another name can be specified for an output column. This name is primarily used to label the column for display. It can also be used to refer to the column’s value in ORDER BY and GROUP BY clauses, but not in the WHERE or HAVING clauses; there you must write out the expression instead.
Instead of an expression, * can be written in the output list as a shorthand for all the columns of the selected rows. Also, one can write table_name.* as a shorthand for the columns coming from just that table.
UNION Clause
The UNION clause has this general form:
select_statement UNION [ ALL ] select_statement
select_statement is any SELECT statement without an ORDER BY, LIMIT, FOR UPDATE, or FOR SHARE clause. (ORDER BY and LIMIT can be attached to a subexpression if it is enclosed in parentheses. Without parentheses, these clauses will be taken to apply to the result of the UNION, not to its right-hand input expression.)
The UNION operator computes the set union of the rows returned by the involved SELECT statements. A row is in the set union of two result sets if it appears in at least one of the result sets. The two SELECT statements that represent the direct operands of the UNION must produce the same number of columns, and corresponding columns must be of compatible data types.
The result of UNION does not contain any duplicate rows unless the ALL option is specified. ALL prevents elimination of duplicates. (Therefore, UNION ALL is usually significantly quicker than UNION; use ALL when you can.)
Multiple UNION operators in the same SELECT statement are evaluated left to right, unless otherwise indicated by parentheses.
Currently, FOR UPDATE and FOR SHARE may not be specified either for a UNION result or for any input of a UNION.
INTERSECT Clause
The INTERSECT clause has this general form:
select_statement INTERSECT [ ALL ] select_statement
select_statement is any SELECT statement without an ORDER BY, LIMIT, FOR UPDATE, or FOR SHARE clause.
The INTERSECT operator computes the set intersection of the rows returned by the involved SELECT statements. A row is in the intersection of two result sets if it appears in both result sets.
The result of INTERSECT does not contain any duplicate rows unless the ALL option is specified. With ALL, a row that has m duplicates in the left table and n duplicates in the right table will appear min(m,n) times in the result set.
Multiple INTERSECT operators in the same SELECT statement are evaluated left to right, unless parentheses dictate otherwise. INTERSECT binds more tightly than UNION. That is, A UNION B INTERSECT C will be read as A UNION (B INTERSECT C).
Currently, FOR UPDATE and FOR SHARE may not be specified either for an INTERSECT result or for any input of an INTERSECT.
EXCEPT Clause
The EXCEPT clause has this general form:
select_statement EXCEPT [ ALL ] select_statement
select_statement is any SELECT statement without an ORDER BY, LIMIT, FOR UPDATE, or FOR SHARE clause.
The EXCEPT operator computes the set of rows that are in the result of the left SELECT statement but not in the result of the right one.
The result of EXCEPT does not contain any duplicate rows unless the ALL option is specified. With ALL, a row that has m duplicates in the left table and n duplicates in the right table will appear max(m-n,0) times in the result set.
Multiple EXCEPT operators in the same SELECT statement are evaluated left to right, unless parentheses dictate otherwise. EXCEPT binds at the same level as UNION.
Currently, FOR UPDATE and FOR SHARE may not be specified either for an EXCEPT result or for any input of an EXCEPT.
ORDER BY Clause
The optional ORDER BY clause has this general form:
ORDER BY expression [ ASC | DESC | USING operator ] [, ...]
expression can be the name or ordinal number of an output column (SELECT list item), or it can be an arbitrary expression formed from input-column values.
The ORDER BY clause causes the result rows to be sorted according to the specified expressions. If two rows are equal according to the leftmost expression, the are compared according to the next expression and so on. If they are equal according to all specified expressions, they are returned in an implementation-dependent order.
The ordinal number refers to the ordinal (left-to-right) position of the result column. This feature makes it possible to define an ordering on the basis of a column that does not have a unique name. This is never absolutely necessary because it is always possible to assign a name to a result column using the AS clause.
It is also possible to use arbitrary expressions in the ORDER BY clause, including columns that do not appear in the SELECT result list. Thus the following statement is valid:
SELECT name FROM distributors ORDER BY code;
A limitation of this feature is that an ORDER BY clause applying to the result of a UNION, INTERSECT, or EXCEPT clause may only specify an output column name or number, not an expression.
If an ORDER BY expression is a simple name that matches both a result column name and an input column name, ORDER BY will interpret it as the result column name. This is the opposite of the choice that GROUP BY will make in the same situation. This inconsistency is made to be compatible with the SQL standard.
Optionally one may add the key word ASC (ascending) or DESC (descending) after any expression in the ORDER BY clause. If not specified, ASC is assumed by default. Alternatively, a specific ordering operator name may be specified in the USING clause. ASC is usually equivalent to USING < and DESC is usually equivalent to USING >. (But the creator of a user-defined data type can define exactly what the default sort ordering is, and it might correspond to operators with other names.)
The null value sorts higher than any other value. In other words, with ascending sort order, null values sort at the end, and with descending sort order, null values sort at the beginning.
Character-string data is sorted according to the locale-specific collation order that was established when the database cluster was initialized.
DISTINCT Clause
If DISTINCT is specified, all duplicate rows are removed from the result set (one row is kept from each group of duplicates). ALL specifies the opposite: all rows are kept; that is the default.
DISTINCT ON ( expression [, ...] ) keeps only the first row of each set of rows where the given expressions evaluate to equal. The DISTINCT ON expressions are interpreted using the same rules as for ORDER BY (see above). Note that the “first row” of each set is unpredictable unless ORDER BY is used to ensure that the desired row appears first. For example,
SELECT DISTINCT ON (location) location, time, report
FROM weather_reports
ORDER BY location, time DESC;
retrieves the most recent weather report for each location. But if we had not used ORDER BY to force descending order of time values for each location, we’d have gotten a report from an unpredictable time for each location.
The DISTINCT ON expression(s) must match the leftmost ORDER BY expression(s). The ORDER BY clause will normally contain additional expression(s) that determine the desired precedence of rows within each DISTINCT ON group.
LIMIT Clause
The LIMIT clause consists of two independent sub-clauses:
LIMIT { count | ALL }
OFFSET start
count specifies the maximum number of rows to return, while start specifies the number of rows to skip before starting to return rows. When both are specified, start rows are skipped before starting to count the count rows to be returned.
When using LIMIT, it is a good idea to use an ORDER BY clause that constrains the result rows into a unique order. Otherwise you will get an unpredictable subset of the query’s rows–you may be asking for the tenth through twentieth rows, but tenth through twentieth in what ordering? You don’t know what ordering unless you specify ORDER BY.
The query planner takes LIMIT into account when generating a query plan, so you are very likely to get different plans (yielding different row orders) depending on what you use for LIMIT and OFFSET. Thus, using different LIMIT/OFFSET values to select different subsets of a query result will give inconsistent results unless you enforce a predictable result ordering with ORDER BY. This is not a bug; it is an inherent consequence of the fact that SQL does not promise to deliver the results of a query in any particular order unless ORDER BY is used to constrain the order.
FOR UPDATE/FOR SHARE Clause
The FOR UPDATE clause has this form:
FOR UPDATE [ OF table_name [, ...] ] [ NOWAIT ]
The closely related FOR SHARE clause has this form:
FOR SHARE [ OF table_name [, ...] ] [ NOWAIT ]
FOR UPDATE causes the rows retrieved by the SELECT statement to be locked as though for update. This prevents them from being modified or deleted by other transactions until the current transaction ends. That is, other transactions that attempt UPDATE, DELETE, or SELECT FOR UPDATE of these rows will be blocked until the current transaction ends. Also, if an UPDATE, DELETE, or SELECT FOR UPDATE from another transaction has already locked a selected row or rows, SELECT FOR UPDATE will wait for the other transaction to complete, and will then lock and return the updated row (or no row, if the row was deleted). For further discussion see section 10 Concurrency Control.
To prevent the operation from waiting for other transactions to commit, use the NOWAIT option. SELECT FOR UPDATE NOWAIT reports an error, rather than waiting, if a selected row cannot be locked immediately. Note that NOWAIT applies only to the row-level lock(s)—the required ROW SHARE table-level lock is still taken in the ordinary way (see section 10 Concurrency Control). You can use the NOWAIT option of LOCK if you need to acquire the table-level lock without waiting.
FOR SHARE behaves similarly, except that it acquires a shared rather than exclusive lock on each retrieved row. A shared lock blocks other transactions from performing UPDATE, DELETE, or SELECT FOR UPDATE on these rows, but it does not prevent them from performing SELECT FOR SHARE.
If specific tables are named in FOR UPDATE or FOR SHARE, then only rows coming from those tables are locked; any other tables used in the SELECT are simply read as usual. A FOR UPDATE or FOR SHARE clause without a table list affects all tables used in the command. If FOR UPDATE or FOR SHARE is applied to a view or sub-query, it affects all tables used in the view or sub-query.
Multiple FOR UPDATE and FOR SHARE clauses can be written if it is necessary to specify different locking behavior for different tables. If the same table is mentioned (or implicitly affected) by both FOR UPDATE and FOR SHARE clauses, then it is processed as FOR UPDATE. Similarly, a table is processed as NOWAIT if that is specified in any of the clauses affecting it.
FOR UPDATE and FOR SHARE cannot be used in contexts where returned rows can’t be clearly identified with individual table rows; for example they can’t be used with aggregation.
Caution: Avoid locking a row and then modifying it within a later savepoint or PL/pgSQL exception block. A subsequent rollback would cause the lock to be lost. For example,
BEGIN;
SELECT * FROM mytable WHERE key = 1 FOR UPDATE;
SAVEPOINT s;
UPDATE mytable SET … WHERE key = 1;
ROLLBACK TO s;
After the ROLLBACK, the row is effectively unlocked, rather than returned to its pre-savepoint state of being locked but not modified. This hazard occurs if a row locked in the current transaction is updated or deleted, or if a shared lock is upgraded to exclusive: in all these cases, the former lock state is forgotten. If the transaction is then rolled back to a state between the original locking command and the subsequent change, the row will appear not to be locked at all. This is an implementation deficiency which will be addressed in a future release of PostgreSQL.
Caution: It is possible for a SELECT command using both LIMIT and FOR UPDATE/SHARE clauses to return fewer rows than specified by LIMIT. This is because LIMIT is applied first. The command selects the specified number of rows, but might then block trying to obtain lock on one or more of them. Once the SELECT unblocks, the row might have been deleted or updated so that it does not meet the query WHERE condition anymore, in which case it will not be returned.
Examples
To join the table films with the table distributors:
SELECT f.title, f.did, d.name, f.date_prod, f.kind
FROM distributors d, films f
WHERE f.did = d.did
title | did | name | date_prod | kind
——————-+—–+————–+————+———-
The Third Man | 101 | British Lion | 1949-12-23 | Drama
The African Queen | 101 | British Lion | 1951-08-11 | Romantic
…
To sum the column len of all films and group the results by kind:
SELECT kind, sum(len) AS total FROM films GROUP BY kind;
kind | total
———-+——-
Action | 07:34
Comedy | 02:58
Drama | 14:28
Musical | 06:42
Romantic | 04:38
To sum the column len of all films, group the results by kind and show those group totals that are less than 5 hours:
SELECT kind, sum(len) AS total
FROM films
GROUP BY kind
HAVING sum(len) < interval ’5 hours’;
kind | total
———-+——-
Comedy | 02:58
Romantic | 04:38
The following two examples are identical ways of sorting the individual results according to the contents of the second column (name):
SELECT * FROM distributors ORDER BY name;
SELECT * FROM distributors ORDER BY 2;
did | name
—–+——————
109 | 20th Century Fox
110 | Bavaria Atelier
101 | British Lion
107 | Columbia
102 | Jean Luc Godard
113 | Luso films
104 | Mosfilm
103 | Paramount
106 | Toho
105 | United Artists
111 | Walt Disney
112 | Warner Bros.
108 | Westward
The next example shows how to obtain the union of the tables distributors and actors, restricting the results to those that begin with the letter W in each table. Only distinct rows are wanted, so the key word ALL is omitted.
distributors: actors:
did | name id | name
—–+————– —-+—————-
108 | Westward 1 | Woody Allen
111 | Walt Disney 2 | Warren Beatty
112 | Warner Bros. 3 | Walter Matthau
… …
SELECT distributors.name
FROM distributors
WHERE distributors.name LIKE ‘W%’
UNION
SELECT actors.name
FROM actors
WHERE actors.name LIKE ‘W%’;
name
—————-
Walt Disney
Walter Matthau
Warner Bros.
Warren Beatty
Westward
Woody Allen
This example shows how to use a function in the FROM clause, both with and without a column definition list:
CREATE FUNCTION distributors(int) RETURNS SETOF distributors
AS $$
SELECT * FROM distributors WHERE did = $1;
$$ LANGUAGE SQL;
SELECT * FROM distributors(111);
did | name
—–+————-
111 | Walt Disney
CREATE FUNCTION distributors_2(int) RETURNS SETOF record AS $$
SELECT * FROM distributors WHERE did = $1;
$$ LANGUAGE SQL;
SELECT * FROM distributors_2(111) AS (f1 int, f2 text);
f1 | f2
—–+————-
111 | Walt Disney
Compatibility
Of course, the SELECT statement is compatible with the SQL standard. But there are some extensions and some missing features.
Omitted FROM Clauses
PostgreSQL allows one to omit the FROM clause. It has a straightforward use to compute the results of simple expressions:
SELECT 2+2;
?column?
———-
4
Some other SQL databases cannot do this except by introducing a dummy one-row table from which to do the SELECT.
Note that if a FROM clause is not specified, the query cannot reference any database tables. For example, the following query is invalid:
SELECT distributors.* WHERE distributors.name = ‘Westward’;
PostgreSQL releases prior to 8.1 would accept queries of this form, and add an implicit entry to the query’s FROM clause for each table referenced by the query. This is no longer the default behavior, because it does not comply with the SQL standard, and is considered by many to be error-prone. For compatibility with applications that rely on this behavior the add_missing_from configuration variable can be enabled.
The AS Key Word
In the SQL standard, the optional key word AS is just noise and can be omitted without affecting the meaning. The PostgreSQL parser requires this key word when renaming output columns because the type extensibility features lead to parsing ambiguities without it. AS is optional in FROM items, however.
Namespace Available to GROUP BY and ORDER BY
In the SQL-92 standard, an ORDER BY clause may only use result column names or numbers, while a GROUP BY clause may only use expressions based on input column names. PostgreSQL extends each of these clauses to allow the other choice as well (but it uses the standard’s interpretation if there is ambiguity). PostgreSQL also allows both clauses to specify arbitrary expressions. Note that names appearing in an expression will always be taken as input-column names, not as result-column names.
SQL:1999 and later use a slightly different definition which is not entirely upward compatible with SQL-92. In most cases, however, PostgreSQL will interpret an ORDER BY or GROUP BY expression the same way SQL:1999 does
=====================================================================================
select * from produk where nama like ‘%k%’;
========================================================================
Privilege short name Description
SELECT r Can read data from the object.
INSERT a Can insert data into the object.
UPDATE w Can change data in the object.
DELETE d Can delete data from the object.
RULE R Can create a rule on the table
REFERENCES x Can create a foreign key to a table. Need this on both sides of the key.
TRIGGER t Can create a trigger on the table.
TEMPORARY T Can create a temporary table.
EXECUTE X Can run the function.
USAGE U Can use the procedural language.
ALL All appropriate privileges. For tables, this equates to arwdRxt
You can apply these privileges to users, groups or a special target called PUBLIC, which is any user on the system.
===========================================================================
Setting cara autentifikasi
Ketik baris di bawah ini untuk mengganti setting autentikasi pada postgresql
# vi /var/lib/pgsql/data/pg_hba.conf
Cari baris di bawah ini
# TYPE DATABASE USER CIDR-ADDRESS METHOD
# “local” is for Unix domain socket connections only
local all all ident sameuser
# IPv4 local connections:
host all all 127.0.0.1/32 ident sameuser
# IPv6 local connections:
host all all ::1/128 ident sameuser
dan rubah menjadi :
# TYPE DATABASE USER CIDR-ADDRESS METHOD
# “local” is for Unix domain socket connections only
local all all password sameuser
# IPv4 local connections:
host all all 127.0.0.1/32 password sameuser
# IPv6 local connections:
host all all ::1/128 password sameuser
Kenapa musti diganti jadi password? Soalnya kalo anda menggunakan ident, anda harus login yang sama persis dengan shell account, contoh nya, anda harus login sebagai default name POSTGRES untuk bisa login ke database. Biasanya kalo mao akses dari PHP ini bukan yang anda inginkan
Untuk bisa setting nya berlaku, anda harus restart
# /etc/init.d/postgresql restart
===========================================================================
CREATE TABLE dan INSERT DATA
To create a new row, use the INSERT command. The command requires the table name and a value for each of the columns of the table. For example, consider the products table from section 3 Data Definition:
CREATE TABLE products (
product_no integer,
name text,
price numeric
);
An example command to insert a row would be:
INSERT INTO products VALUES (1, ‘Cheese’, 9.99);
The data values are listed in the order in which the columns appear in the table, separated by commas. Usually, the data values will be literals (constants), but scalar expressions are also allowed.
The above syntax has the drawback that you need to know the order of the columns in the table. To avoid that you can also list the columns explicitly. For example, both of the following commands have the same effect as the one above:
INSERT INTO products (product_no, name, price) VALUES (1,
‘Cheese’, 9.99);
INSERT INTO products (name, price, product_no) VALUES
(‘Cheese’, 9.99, 1);
Many users consider it good practice to always list the column names.
If you don’t have values for all the columns, you can omit some of them. In that case, the columns will be filled with their default values. For example,
INSERT INTO products (product_no, name) VALUES (1, ‘Cheese’);
INSERT INTO products VALUES (1, ‘Cheese’);
The second form is a PostgreSQL extension. It fills the columns from the left with as many values as are given, and the rest will be defaulted.
For clarity, you can also request default values explicitly, for individual columns or for the entire row:
INSERT INTO products (product_no, name, price) VALUES (1,
‘Cheese’, DEFAULT);
INSERT INTO products DEFAULT VALUES;
You can insert multiple rows in a single command:
INSERT INTO products (product_no, name, price) VALUES
(1, ‘Cheese’, 9.99),
(2, ‘Bread’, 1.99),
(3, ‘Milk’, 2.99);
==———————————-
To perform an update, you need three pieces of information:
1. The name of the table and column to update,
2. The new value of the column,
3. Which row(s) to update.
Recall from section 3 Data Definition that SQL does not, in general, provide a unique identifier for rows. Therefore it is not necessarily possible to directly specify which row to update. Instead, you specify which conditions a row must meet in order to be updated. Only if you have a primary key in the table (no matter whether you declared it or not) can you reliably address individual rows, by choosing a condition that matches the primary key. Graphical database access tools rely on this fact to allow you to update rows individually.
For example, this command updates all products that have a price of 5 to have a price of 10:
UPDATE products SET price = 10 WHERE price = 5;
This may cause zero, one, or many rows to be updated. It is not an error to attempt an update that does not match any rows.
Let’s look at that command in detail. First is the key word UPDATE followed by the table name. As usual, the table name may be schema-qualified, otherwise it is looked up in the path. Next is the key word SET followed by the column name, an equals sign and the new column value. The new column value can be any scalar expression, not just a constant. For example, if you want to raise the price of all products by 10% you could use:
UPDATE products SET price = price * 1.10;
As you see, the expression for the new value can refer to the existing value(s) in the row. We also left out the WHERE clause. If it is omitted, it means that all rows in the table are updated. If it is present, only those rows that match the WHERE condition are updated. Note that the equals sign in the SET clause is an assignment while the one in the WHERE clause is a comparison, but this does not create any ambiguity. Of course, the WHERE condition does not have to be an equality test. Many other operators are available (see section 7 Functions and Operators). But the expression needs to evaluate to a Boolean result.
You can update more than one column in an UPDATE command by listing more than one assignment in the SET clause. For example:
UPDATE mytable SET a = 5, b = 3, c = 1 WHERE a > 0;