Archive for the ‘SQL’ Category

If you have a HyperSQL (HSQL) database stored in a file, it is often useful to be able to query that database from the command line. This can be done using the following command: hsqldb-sqltool –inlineRc url=jdbc:hsqldb:file:<db_name>,user=<username>,password=[<password>] By default, user SA with no password will exist for each database file. If the database does not […]

PHP is able to communicate with PostgreSQL databases using some relatively simple calls. In a similar manner to other database systems, the script needs to do the following: connect to the database using pg_connect execute queries using pg_query and pg_free_result close the database connection using pg_close For example, consider the following script: <?PHP // database […]

Consider the following query (tested on PostgreSQL – some other systems may require a table to be specified): SELECT ‘Yes’ AS Value_Returned WHERE 1 != 2; This query returns 1 row: ( Value_Returned = ‘Yes’ ), as one would expect. But what if we compare against NULL? SELECT ‘Yes’ AS Value_Returned WHERE 1 != NULL; […]

Conditional INSERT in SQL

Posted: 23rd October 2013 by Tim in SQL
Tags: , , , , , ,

Sometimes you want to run an INSERT statement in SQL only if some condition is met. There are a few methods available to do this, but not all of them are supported by all database systems. One method which is supported on all systems the use of a SELECT statement to return the row values, […]

If you’re writing functions in postgres then you’ll probably be using a language such as plpgsql. Let’s say you’re writing a script to to add all of these functions to a new database, but you don’t know whether that language has been created yet. You’ll probably want to do something like CREATE LANGUAGE IF NOT […]

Conditional COUNT in SQL

Posted: 10th October 2010 by Tim in SQL
Tags: , , , , , , , , , , ,

Sometimes you want to count the number of results which meet a certain condition. Excel has a COUNTIF(…) function but there is nothing like that in the (current) SQL standard. The solution is to mix the SUM function with a CASE statement. Confused? Let’s see an example. Imagine you have two tables – student (student_id, […]

It’s often useful to concatenate two fields together in an SQL query. In PostgreSQL, fields may be concatenated using the || operator. The syntax is really simple. Just place the double bar between the fields you want to join, and (optionally) give a label to that new field. Strings can also be concatenated with the […]

PostgreSQL, unfortunately, does not provide an inline IF statement like some other SQL servers. CASE statements, however, can be run inline which can be quite handy. Let’s say you have a user table with a num_heads field. You want to know if the user is a zombie, human or alien with one query. This could […]

Let’s say you have a file type whose contents are in XML format but have a different file extension such as .tim . If you want to edit these files with Vim with syntax highlighting, simply add the following to ~/.vimrc (affects only your Vim environment) or /etc/vim/vimrc (affects everyone’s Vim environment): au BufNewFile,BufRead *.tim […]

If you’re getting a FATAL: Ident authentication failed for user [username] Error when attempting to connect to postgres as a specific user, chances are you need to change some security settings. Postgresql, by default, only allows you to connect to postgres if the postgres username is the same as your username on the operating system. […]


Posted: 18th February 2010 by Tim in PostgreSQL
Tags: , , , , , ,

If you’re looking for a command to give you a list of schemas in PostgreSQL, much like MySQL’s SHOW SCHEMAS command, then \dn is what you’re looking for. ie: \dn List of schemas Name               | Owner ——————-+——— information_schema | postgres pg_catalog         | postgres person             | tim …

Quite often you need to insert a row into a table and then extract the auto-generated ID. Often people do the insert and then query the table again for the highest ID. This method may have concurrency issues (ie: if someone else inserts a record between the two queries), so they wrap it all up […]

Substitution variables in PostgreSQL

Posted: 3rd February 2010 by Tim in PostgreSQL

If you’re writing a script which references a hard-coded value, it’s always cleaner to create a variable or constant to reference that value. PostgreSQL allows you to do that. These substitution variables are defined using the \set var_name ‘value’ command. The value of the variable must be enclosed in single quotes. If the value is […]

DESCRIBE table in PostgreSQL

Posted: 20th January 2010 by Tim in PostgreSQL
Tags: , , , , ,

MySQL has a nice way to get the details of a table structure through the DESCRIBE command. PostgreSQL can also do this for you with \d table_name. For example (sorry about the poor layout): tim=# \d test_table Table “public.test_table” Column | Type | Modifiers ———+—————————–+——————- test_id | integer | not null default nextval(‘test_table_test_id_seq’::regclass) name | […]

The unix epoch timestamp is a number representing the number of seconds since the first of January, 1970. This may seem like a strange representation, but it allows dates to be compared very easily. To get the epoch timestamp of a date in PostgreSQL, we can use the EXTRACT function like so: tim=# SELECT EXTRACT(EPOCH […]


Posted: 11th January 2010 by Tim in PostgreSQL

MySQL allows you to extract a list of tables in schema using the SHOW TABLES command. This can be done in PostgreSQL by using the dt command. ie: tim=#dt List of relations Schema | Name | Type | Owner ——-+——+——+——- public | person | table | tim public | business | table | tim (2 […]

Database systems such as MySQL allow you to specify a column as being auto incrementing. PostgreSQL, on the other hand, does things differently. Fields are incremented using sequences; external counters which are incremented manually. To use this requires setting up the sequence with a unique name and telling PostgreSQL to grab and increment the sequence […]

Like MySQL, there is a way to see all processes in PostgreSQL. It’s one simple command: SELECT * FROM pg_stat_activity; Note that if the current_query field keeps coming up empty, you might need to enable stats_command_string in your postgresql.conf. Enjoy.

The PostgreSQL documentation states that PQexecParams can be called like so: PGresult *PQexecParams(PGconn *conn, const char *command, int nParams, const Oid *paramTypes, const char * const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat); There are two parts of this call which can be tricky to novice C and/or PostgreSQL users and aren’t explained […]

There are times when you want to explicitly set or reset the counter value on a SERIAL (auto incrementing) field or on a SEQUENCE. This may be done using a SELECT SETVAL(…) command. If you’re using a SERIAL field, PostgreSQL will actually create a SEQUENCE for you, which increments every time you insert a row. […]

USE [schema_name] in PostgreSQL

Posted: 17th November 2009 by Tim in PostgreSQL
Tags: , , , , ,

For those moving from MySQL to PostgreSQL, there are a few differences which you will need to get used to. One of these differences is the USE command, used to select the schema to select tables, views, etc from. PostgreSQL does not have the USE command. Instead, you can use: SET search_path TO [schema_name] For […]

MySQL comes with a library to make talking to MySQL with C easyish. There are a few things you have to install first, though. I’m using Ubuntu 8.04 for this walkthrough, but things should be similar for other flavours of Linux. Before we start, we have to download the development files required: sudo apt-get install […]

Inline IF and CASE statements in MySQL

Posted: 13th August 2009 by Tim in MySQL
Tags: , , , , , ,

There are times where running IF statements inside a query can be useful. MySQL provides a simple way to do this through the use of IF and CASE statements. The IF statement takes three arguments; the conditional, the true value and the false value. False and true values may be static values or column values. […]

MySQL Foreign Keys

Posted: 23rd July 2009 by Tim in MySQL
Tags: , , , ,

Foreign keys are a good way to ensure consistency between tables, by ensuring that the value in one table column exists in another table. For example, you might have a person table which contains person_id, first_name and surname. You may then have another table, person_ages, which contains person_id and date_of_birth. You would add a foreign […]