How to show data in a table by using psql command line interface? - psql

Is there a way to show all the content inside a table by using psql command line interface?
I can use \list to show all the databases, \d to show all the tables, but how can I show all the data in a table?

Newer versions: (from 8.4 - mentioned in release notes)
TABLE mytablename;
Longer but works on all versions:
SELECT * FROM mytablename;
You may wish to use \x first if it's a wide table, for readability.
For long data:
SELECT * FROM mytable LIMIT 10;
or similar.
For wide data (big rows), in the psql command line client, it's useful to use \x to show the rows in key/value form instead of tabulated, e.g.
\x
SELECT * FROM mytable LIMIT 10;
Note that in all cases the semicolon at the end is important.

Step 1. Check the display mode is "on" by using
\x
Step 2. Don't forget the ;
I tried for fifteen minutes just because I forgot the semicolon.
AND USE UPPERCASE ENGLISH.
TABLE users;
And you will get something like

On Windows use the name of the table in quotes:
TABLE "user"; or SELECT * FROM "user";

you should use quotes
example =>
1) \c mytablename
2) SELECT * FROM "mytablename"; OR TABLE "mytablename";

postgres commande line
to show databases : \l
to show tables : \dt
to show data in table x : SELECT * FROM "x";
to exit : \q

If you use schemas, the following will be correct:
SELECT * FROM "schema-name"."table-name";

Related

is there are any alpha logic define in informix DB

i am using informix DB , i need to get records that contain alpha [A-Za-z] character on last character
what i try is :
select * from table_name
where (SUBSTR(trim(customer),-1,1)!='0' and SUBSTR(trim(customer),-1,1)!='1' and SUBSTR(trim(customer),-1,1)!='2' and SUBSTR(trim(customer),-1,1)!='3' and SUBSTR(trim(customer),-1,1)!='4' and SUBSTR(trim(customer),-1,1)!='5' and SUBSTR(trim(customer),-1,1)!='6' and SUBSTR(trim(customer),-1,1)!='7' and SUBSTR(trim(customer),-1,1)!='8' and SUBSTR(trim(customer),-1,1)!='9') or (SUBSTR(trim(customer),-1,1)=' ') or (SUBSTR(trim(customer),-1,1)='') or (customer IS NULL)
is there are any way to write where SUBSTR(trim(customer),-1,1)=alpha rather than write
SUBSTR(trim(customer),-1,1)!='0' and SUBSTR(trim(customer),-1,1)!='1' and SUBSTR(trim(customer),-1,1)!='2' and SUBSTR(trim(customer),-1,1)!='3' and SUBSTR(trim(customer),-1,1)!='4' and SUBSTR(trim(customer),-1,1)!='5' and SUBSTR(trim(customer),-1,1)!='6' and SUBSTR(trim(customer),-1,1)!='7' and SUBSTR(trim(customer),-1,1)!='8' and SUBSTR(trim(customer),-1,1)!='9'
If you have a 'recent' version of Informix (anything over 12.10 should do) you can use regex_match():
https://www.ibm.com/support/knowledgecenter/SSGU8G_14.1.0/com.ibm.dbext.doc/ids_dbxt_544.htm
Something like :
> select * from table(set{'test','test1','tesT'})
where regex_match(unnamed_col_1, '[a-zA-Z]$');
unnamed_col_1
test
tesT
2 row(s) retrieved.
>
You can use the Informix MATCHES operator, that is supported in any version.
The query would be like this:
select * from table_name
where customer matches "*[A-Za-z]"

How to get row Count of the sqlite3_stmt *statement? [duplicate]

I want to get the number of selected rows as well as the selected data. At the present I have to use two sql statements:
one is
select * from XXX where XXX;
the other is
select count(*) from XXX where XXX;
Can it be realised with a single sql string?
I've checked the source code of sqlite3, and I found the function of sqlite3_changes(). But the function is only useful when the database is changed (after insert, delete or update).
Can anyone help me with this problem? Thank you very much!
SQL can't mix single-row (counting) and multi-row results (selecting data from your tables). This is a common problem with returning huge amounts of data. Here are some tips how to handle this:
Read the first N rows and tell the user "more than N rows available". Not very precise but often good enough. If you keep the cursor open, you can fetch more data when the user hits the bottom of the view (Google Reader does this)
Instead of selecting the data directly, first copy it into a temporary table. The INSERT statement will return the number of rows copied. Later, you can use the data in the temporary table to display the data. You can add a "row number" to this temporary table to make paging more simple.
Fetch the data in a background thread. This allows the user to use your application while the data grid or table fills with more data.
try this way
select (select count() from XXX) as count, *
from XXX;
select (select COUNT(0)
from xxx t1
where t1.b <= t2.b
) as 'Row Number', b from xxx t2 ORDER BY b;
just try this.
You could combine them into a single statement:
select count(*), * from XXX where XXX
or
select count(*) as MYCOUNT, * from XXX where XXX
To get the number of unique titles, you need to pass the DISTINCT clause to the COUNT function as the following statement:
SELECT
COUNT(DISTINCT column_name)
FROM
'table_name';
Source: http://www.sqlitetutorial.net/sqlite-count-function/
For those who are still looking for another method, the more elegant one I found to get the total of row was to use a CTE.
this ensure that the count is only calculated once :
WITH cnt(total) as (SELECT COUNT(*) from xxx) select * from xxx,cnt
the only drawback is if a WHERE clause is needed, it should be applied in both main query and CTE query.
In the first comment, Alttag said that there is no issue to run 2 queries. I don't agree with that unless both are part of a unique transaction. If not, the source table can be altered between the 2 queries by any INSERT or DELETE from another thread/process. In such case, the count value might be wrong.
Once you already have the select * from XXX results, you can just find the array length in your program right?
If you use sqlite3_get_table instead of prepare/step/finalize you will get all the results at once in an array ("result table"), including the numbers and names of columns, and the number of rows. Then you should free the result with sqlite3_free_table
int rows_count = 0;
while (sqlite3_step(stmt) == SQLITE_ROW)
{
rows_count++;
}
// The rows_count is available for use
sqlite3_reset(stmt); // reset the stmt for use it again
while (sqlite3_step(stmt) == SQLITE_ROW)
{
// your code in the query result
}

Firebird: simulating create table as?

I'm searching a way to simulate "create table as select" in Firebird from SP.
We are using this statement frequently in another product, because it is very easy for make lesser, indexable sets, and provide very fast results in server side.
create temp table a select * from xxx where ...
create indexes on a ...
create temp table b select * from xxx where ...
create indexes on b ...
select * from a
union
select * from b
Or to avoid the three or more levels in subqueries.
select *
from a where id in (select id
from b
where ... and id in (select id from c where))
The "create table as select" is very good cos it's provide correct field types and names so I don't need to predefine them.
I can simulate "create table as" in Firebird with Delphi as:
Make select with no rows, get the table field types, convert them to create table SQL, run it, and make "insert into temp table " + selectsql with rows (without order by).
It's ok.
But can I create same thing in a common stored procedure which gets a select sql, and creates a new temp table with the result?
So: can I get query result's field types to I can create field creator SQL from them?
I'm just asking if is there a way or not (then I MUST specify the columns).
Executing DDL inside stored procedure is not supported by Firebird. You could do it using EXECUTE STATEMENT but it is not recommended (see the warning in the end of "No data returned" topic).
One way to do have your "temporary sets" would be to use (transaction-level) Global Temporary Table. Create the GTT as part of the database, with correct datatypes but without constraints (those would probably get into way when you fill only some columns, not all) - then each transaction only sees it's own version of the table and data...

union between requests with remplacement variables in sqlplus

I have 14 fields which are similar and I search the string 'A' on each of them. I would like after that order by "position" field
-- some set in order to remove a lot of useless text
def col='col01'
select '&col' "Fieldname",
&col "value",
position
from oneTable
where &col like '%A%'
/
-- then for the second field, I only have to type two lines
def col='col02'
/
...
def col='col14'
/
Write all the fields which contains 'A'. The problem is that those field are not ordered by position.
If I use UNION between table, I cannot take advantage of the substitution variables (&col), and I have to write a bash in unix in order to make the replacement back into ksh. The problem is of course that database code have to be hard-coded in this script (connection is not easy stuff).
If I use a REFCURSOR with OPEN, I cannot group the results sets together. I have only one request and cannot make an UNION of then. (print refcursor1 union refcursor2; print refcursor1+refcursor2 raise an exception, select * from refcursor1 union select * from refcursor2, does not work also).
How can concatenate results into one big "REFCURSOR"? Or use a union between two distinct run ('/') of my request, something like holding the request while typing new definition of variables?
Thank you for any advice.
Does this answer your question ?
CREATE TABLE #containingAValueTable
(
FieldName VARCHAR(10),
FieldValue VARCHAR(1000),
position int
)
def col='col01'
INSERT INTO #containingAValueTable
(
FieldName , FieldValue, position
)
SELECT '&col' "Fieldname",
&col "value",
position
FROM yourTable
WHERE &col LIKE '%A%'
/
-- then for the second field, I only have to type two lines
def col='col02'
INSERT INTO...
/
def col='col14'
/
select * from #containingAValueTable order by postion
DROP #containingAValueTable
But I'm not totally sure about your use of the 'substitution variable' called "col" (and i only have SQL Server to test my request so I used explicit field names)
edit : Sorry for the '#' charcater, we use it so often in SQL Server for temporaries, I didn't even know it was SQL Server specific (moreover I think it's mandatory in sql server for creating temporary table). Whatever, I'm happy I could be useful to you.

delphi "Invalid use of keyword" in TQuery

I'm trying to populate a TDBGrid with the results of the following TQuery against the file Journal.db:
select * from Journal
where Journal.where = "RainPump"
I've tried both Journal."Where" and Journal.[Where] to no avail.
I've also tried: select Journal.[Where] as "Location" with the same result.
Journal.db is a file created by a third party and I am unable to change the field names.
The problem is that the field I'm interested in is called 'where' and understandably causes the above error. How do I reference this field without causing the BDE (presumably) to explode?
Aah, I'm loving delphi again... I found a workaround. The TQuery component has the Filter property :-)
I omitted the "Where=" where clause from the query whilst still keeping all the other 'and' conditions.
I set the Filter property to "Where = 'RainPump'".
I set the Filtered property to True and life is good again.
I'm still wondering if there's a smarter way to do this using this old technology but if it's stupid and it works, then it's not stupid.
I'm afraid that someone reading this thread will get the impression that the BDE SQL engine cannot handle the query:
select * from Journal where Journal."Where" = "RainPump"
and will waste their time unnecessarily circumlocuting around it.
In fact this construction works fine. The quotes around "Where" keeps the BDE from interpreting it as a keyword, just as you would expect.
I don't know what is wrong in Baldric's particular situation, or what he tried in what order. He describes the problem as querying a *.db table, but his SQL error looks more like something you'd get in passthrough mode. Or, possibly he simplified his code for submission, thus eliminating the true cause of the error.
My tests performed with:
BDE v.5.2 (5.2.0.2)
Paradox for Windows v. 7 (32b)
Delphi 5.0 (5.62)
Various versions of the statement that succeed:
select * from Journal D0 where D0."Where" = "RainPump"
select * from Journal where Journal."Where" = "RainPump"
select * from ":common:Journal" D0 where D0."Where" = "RainPump"
select * from ":common:Journal" where ":common:Journal"."Where" = "RainPump"
select * from :common:Journal where Journal."Where" = "RainPump"
select * from ":common:Journal" D0 where D0."GUMPIK" = 3
select * from ":common:Journal" where ":common:Journal"."GUMPIK" = 3
select * from :common:Journal where Journal."GUMPIK" = 3
Versions of the statement that look correct but fail with "Invalid use of keyword":
select * from ":common:Journal" where :common:Journal."Where" = "RainPump"
select * from :common:Journal where :common:Journal."Where" = "RainPump"
select * from ":common:Journal" where :common:Journal."GUMPIK" = 3
select * from :common:Journal where :common:Journal."GUMPIK" = 3
-Al.
You can insert the resultset into a new table with "values" (specifying no column names) where you have given your own column names in the new table and then do a select from that table, Using a TQuery, something like:
Query1.sql.clear;
query1,sql.add('Insert into newtable values (select * from Journal);');
query1.sql.add('Select * from newtable where newcolumn = "Rainpump";');
query1.open;
Rewrite it like this, should work:
select * from Journal where Journal.[where] = "RainPump"
Me, I'd rename the awkward column.
In MySQL, table/column names can be enclosed in `` (the angled single quotes). I'm not sure what the BDE allows, but you could try replacing [where] with `where`
select * from Journal where Journal."where" = "RainPump"
Ok, so naming columns after keyboards is bad in ANY SQL system. Would you name a column "select" or "count" or "alter" or "table" or perhaps just for the fun of it "truncate" or "drop"? I would hope not.
Even if you build in the work around for this instance you are creating a mine field for whomever comes after you. Do what mj2008 said and rename the bloody column.
Allowing this column name to persist is the worst example of someone who is building a system and would get you on the poop list for any project manager.

Resources