Select all values in a column into a string in SQLite? - sql

In SQL Server, I can do this with the help of Cursor (to loop through each row in the result set and build my string). But I don't know how to do the same in SQLite, this task is not like the so-called Pivoting which as far as I know, we have to know the exact rows we want to turn to columns. My case is different, I want to select all the values of a specified column into a string (and then can select as a column of 1 row), this column can have various values depend on the SELECT query. Here is a sample of how it looks:
A | B
------------
1 | 0
8 | 1
3 | 2
... ....
I want to select all the values of the column A into a string like this "183..." (or "1,8,3,..." would be fine).
This can be used as a column in another SELECT, I have to implement this because I need to display all the sub-infos (on each row of column A) as a comma-separated list in another row.
I don't have any idea on this, it seems to need some procedural statements (such as placed in a procedure) but SQLite limits much on how I can do with loop, variable declaration,...I'm really stuck. This kind of task is very common when programming database and there is no reason for me to refuse doing it.
Please help, your help would be highly appreciated! Thanks!

If you're just trying to get all the values from Column A into a single record, then use GROUP_CONCAT:
select group_concat(a, ',')
from yourtable
SQL Fiddle Demo

The main problem is that you are think like an application programmer. SQL does a lot of things for you.
SELECT *
FROM tableA
WHERE A IN (SELECT A
FROM tableB)
No need to resort to cursors, stored procedures and multiple queries.

Related

Access 2013 query - select 1st row

It seems a basic questions but after several hours and days, i'm still blocked.
As part of a query I would like to select some specific rows in a table (actually this table is already a query). As an example, rows are highlighted in the picture attached. For each "batch", this corresponds to the row containing the lower "CountofVials" and is not a "Stability rack".
How would you create the query? I usually use the Design view to create query but i can understand SQL too.
table with rows to select in yellow
SELECT *
FROM YourQuery a
WHERE EXISTS (SELECT 1
From YourQuery b
WHERE b.[Stability Rack] = False AND b.Batch=a.Batch
GROUP BY Batch
HAVING Min(CountOfVial)=a.CountOfVial )
You cannot 'select' non-contiguous in Access. You can use a form and 'highlight' entire rows or individual values using conditional formatting. There has been much posted on conditional formatting, so it would be best to just look it up.

oracle sql query requirements

I have some data in oracle table abot 10,000 rows i want to genrate column which return 1 for ist row and 2 for second and so on 1 for 3rd and 2 for 4th and 1 for 5th and 2 for 6th and so on..Is there any way that i can do it using sql query or any script which can update my column like this.that it will generate 1,2 as i mentioned above i have thought much but i didn't got to do this using sql or any other scencrio for my requirements.plz help if any possibility for doing this with my table data
You can use the combination of the ROWNUM and MOD functions.
Your query would look something like this:
SELECT ROWNUM, 2 - MOD(ROWNUM, 2) FROM ...
The MOD function will return 0 for even rows and 1 for odd rows.
select mod(rownum,5)+1,fld1, fld2, fld3 from mytable;
Edit:
I did not misunderstand requirements, I worked around them. Adding a column and then updating a table that way is a bad design idea. Tables are seldom completely static, even rule and validation tables. The only time this might make any sense is if the table is locked against delete, insert, and update. Any change to any existing row can alter the logical order. Which was never specified. Delete means the entire sequence has to be rewritten. Update and insert can have the same effect.
And if you wanted to do this you can use a sequence to insert a bogus counter. A sequence that cycles over and over, assuming you know the order and can control inserts and updates in terms of that order.

Select * with specific alias [syntax]

I want to use select * to select all the fields from a table but I also want to use an alias on just one field. Is it possible? If so what would the syntax be.
Example
select *,
item1 as hats
from factory
I have not been able to make anything like this work, Thanks!
I just tried
select *, item1 as hats from factory
on mysql and postgres and on both DBMS it runs fine. Only take into consideration that you get two columns with item1. One column named item1 and one named hats.
That should work, but keep in mind that your item1 column will be duplicated!
Suppose your table has the columns (id, item1, item2) then your proposed select will return (id,item1,item2,hats).
It's valid in MS Sql Server as well but the column you are alias'ng will be duplicated.
Tried the query in Sql server 2005 and it did worked.
select *,col2 as 'customcol' from table1
Yes, it is possible to use that format however, use of Select * is not recommend. It is better to enumerate the columns you want. Some database products may balk if the list of columns in combination with your aliased column produces a duplicate column name. However, again, you can solve this by enumerating the columns.

SQL copy sum of 2 varchars to to new table

tis my first question so sorry if its not well structured, I have looked for the answer for a while but no joy so here goes..
basically I have 20 columns and want to take the result of adding columns (a+b) (b+c) etc and make this the value of my new columns,
when i do a simple select statement the values appear as expected but i cant seem to get them to appear into a new table
the columns are varchars
this is one of the 20 select queries
((accidentlogs.before_T18/16-accidentlogs.before_T19/16)/21.954),
It seems like such an easy function and it probably is but stick a fork in me on this one
You can use the result of a SELECT Statement as a value for an INSERT Statement. The exact syntax may vary for the SQL Dialect you use (Oracle, Postgres, MySql...)
This is the code for postgres:
INSERT INTO table (field1, field2...) SELECT 'value1', 'value2'...

Is there efficient SQL to query a portion of a large table

The typical way of selecting data is:
select * from my_table
But what if the table contains 10 million records and you only want records 300,010 to 300,020
Is there a way to create a SQL statement on Microsoft SQL that only gets 10 records at once?
E.g.
select * from my_table from records 300,010 to 300,020
This would be way more efficient than retrieving 10 million records across the network, storing them in the IIS server and then counting to the records you want.
SELECT * FROM my_table is just the tip of the iceberg. Assuming you're talking a table with an identity field for the primary key, you can just say:
SELECT * FROM my_table WHERE ID >= 300010 AND ID <= 300020
You should also know that selecting * is considered poor practice in many circles. They want you specify the exact column list.
Try looking at info about pagination. Here's a short summary of it for SQL Server.
Absolutely. On MySQL and PostgreSQL (the two databases I've used), the syntax would be
SELECT [columns] FROM table LIMIT 10 OFFSET 300010;
On MS SQL, it's something like SELECT TOP 10 ...; I don't know the syntax for offsetting the record list.
Note that you never want to use SELECT *; it's a maintenance nightmare if anything ever changes. This query, though, is going to be incredibly slow since your database will have to scan through and throw away the first 300,010 records to get to the 10 you want. It'll also be unpredictable, since you haven't told the database which order you want the records in.
This is the core of SQL: tell it which 10 records you want, identified by a key in a specific range, and the database will do its best to grab and return those records with minimal work. Look up any tutorial on SQL for more information on how it works.
When working with large tables, it is often a good idea to make use of Partitioning techniques available in SQL Server.
The rules of your partitition function typically dictate that only a range of data can reside within a given partition. You could split your partitions by date range or ID for example.
In order to select from a particular partition you would use a query similar to the following.
SELECT <Column Name1>…/*
FROM <Table Name>
WHERE $PARTITION.<Partition Function Name>(<Column Name>) = <Partition Number>
Take a look at the following white paper for more detailed infromation on partitioning in SQL Server 2005.
http://msdn.microsoft.com/en-us/library/ms345146.aspx
I hope this helps however please feel free to pose further questions.
Cheers, John
I use wrapper queries to select the core query and then just isolate the ROW numbers that i wish to take from the query - this allows the SQL server to do all the heavy lifting inside the CORE query and just pass out the small amount of the table that i have requested. All you need to do is pass the [start_row_variable] and the [end_row_variable] into the SQL query.
NOTE: The order clause is specified OUTSIDE the core query [sql_order_clause]
w1 and w2 are TEMPORARY table created by the SQL server as the wrapper tables.
SELECT
w1.*
FROM(
SELECT w2.*,
ROW_NUMBER() OVER ([sql_order_clause]) AS ROW
FROM (
<!--- CORE QUERY START --->
SELECT [columns]
FROM [table_name]
WHERE [sql_string]
<!--- CORE QUERY END --->
) AS w2
) AS w1
WHERE ROW BETWEEN [start_row_variable] AND [end_row_variable]
This method has hugely optimized my database systems. It works very well.
IMPORTANT: Be sure to always explicitly specify only the exact columns you wish to retrieve in the core query as fetching unnecessary data in these CORE queries can cost you serious overhead
Use TOP to select only a limited amont of rows like:
SELECT TOP 10 * FROM my_table WHERE ID >= 300010
Add an ORDER BY if you want the results in a particular order.
To be efficient there has to be an index on the ID column.