Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
So, I'm practicing for an exam *(high school level)*, and although we have never been thought SQL it is necessarry know a little when handling **MS Access**. The task is to select the IDs of areas which names does not correspond with the town's they belong to. In the solution was the following example: ``` SELECT na...
One thing that would create a difference is to consider this example ``` areaid areaname townname 1 AA AA 1 AA BB ``` So your first query would exclude both records from the outcome. Because the inner query would identify `areaid =1` to be among those to be excluded. Therefore, both records ...
The reason is because there can be more than one town in an area, right? So if there is a town in an area that has a similar name, then that area will be found in the LIKE subquery. If there is another town in the SAME AREA that does not have a similar name, then that area will ALSO be found in the NOT LIKE subquery....
SQL: Not Like produces different results than what would be Like's opposite
[ "", "sql", "database", "ms-access", "" ]
I'm collecting data between two date 01/12/2014 and 31/12/2014 but my sql data type in nvarchar is my query right? ``` SELECT * from customer where date >= convert(datetime, '01/12/2014', 105) AND date <= convert(datetime, '31/12/2014', 105) ``` Result ``` Msg 242, Level 16, State 3, Line 1 The conversion of a nv...
as I know you must separate different parts of a DATE with "-" not with "/" in format 105. here is an example: ``` SELECT convert(datetime, '23-10-2016', 105) -- dd-mm-yyyy ``` so you must rewrite your code as: ``` SELECT * from customer where date >= convert(datetime, '01-12-2014', 105) AND date <= convert(dateti...
The format your string are in, `'dd/mm/yyyy'` is 103, not 105 (which is `'dd-mm-yyyy'`). So, simply use the correct format: ``` SELECT * FROM customer WHERE [date] >= CONVERT(datetime, '01/12/2014', 103) AND [date] <= CONVERT(datetime, '31/12/2014', 103) ```
Convert nvarchar to date and Get data between two date
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have a 2 tables: ``` DECLARE @MASTER TABLE (MAST_ID INT, MAST_NAME NVARCHAR(10), IS_ACTIVE CHAR(1) ) INSERT INTO @MASTER VALUES (1, 'MAST1', 'A'), (2, 'MAST2', 'I'), (3, 'MAST3', 'A'), (4, 'MAST4', 'A') SELECT * FROM @MASTER DECLARE @C...
``` select * from @MASTER A where is_active = 'A' and exists (select 1 from @child where is_active = 'A' and mast_id = A.mast_id); ``` and ``` select * from @child A where is_active = 'A' and exists (select 1 from @master where mast_id = A.mast_id and is_active = 'A'); ``` Fiddle - <http://sqlfiddle.com/#!6/7a59c/4...
You need to build a subquery to obtain the `MAST_ID` from the `@CHILD` table where the `IS_ACTIVE = 'A'` and then subquery against the `@MASTER` to get `IS_ACTIVE = 'A'` for those `MAST_ID` ``` SELECT M.* FROM @MASTER M WHERE IS_ACTIVE = 'A' AND MAST_ID IN (SELECT MAST_ID FROM @CHILD C WHERE IS_ACTIVE = 'A') ```
Looking for master/child table database on condition?
[ "", "sql", "sql-server", "" ]
I am trying to generate Fibonacci series using below query (recursive WITH clause). ``` WITH X(Pnbr,Cnbr) AS (SELECT 0, 1 FROM dual UNION ALL SELECT X.Cnbr, X.Pnbr+X.Cnbr FROM X WHERE X.Cnbr<50 ) SELECT * FROM X ``` But I am getting this error ``` ORA-32044: cycle detected while executing recursive WITH query ``...
Your data at first iteration would be ``` PNBR CNBR 0 , 1 1 , 1 + 0 ``` So, CNBR is 1 is first two rows.. A Cycle is detected! The `CONNECTING` condition has to be **unique**! > So probably you would need to maintain an iterator. `ROWNUM` is what I used here for it. ``` WITH X(iter,Pnbr,Cnbr) AS (SELECT 1,0,...
I agree with the diagnosis in M. Ravisankar's Answer (from 2015), but not with the remedy. To handle precisely the situation presented in the original post, recursive CTE offers the `CYCLE` clause. In this problem, while there will be repeated values in the `Pnbr` column as well as in the `Cnbr` column, when considere...
Trying to generate Fibonacci series using recursive WITH clause, getting error: 'cycle detected while executing'
[ "", "sql", "oracle", "recursion", "" ]
Let's say I have two tables: ``` user (user_name varchar(50), project_name varchar(50)) project (project_name varchar(50), project_cost(integer)) ``` I have a query that's returns me results which are "de-facto desired" : ``` select u.user_name, p.project_name from user u, project p where u.project_name = p.projec...
If no `order by` clause is given, postgres (and any other reasonable database, for that sake), should return the rows in the order it was able to produce them (be it from an internal cache, an index, or directly from the table). Since the same algorithm is used on the same data, it isn't surprising you're getting the ...
To know what really DBMS does one should look at the PLAN. The output order will depend upon it too. However there are two things to remember: first, if the plan includes 'full (heap) table scan' then the order is undefined (as DBMS may freely reorder heap data); second, the plan may change significantly if you change ...
How does postgres order the results when ORDER BY is not provided
[ "", "sql", "postgresql", "select", "sql-order-by", "" ]
I have a table with Column - D and E. I want to get D, Distinct E in each D, Count of total number of entry for each D. How to write SQL for this ? Data: ``` D | E ----- 1 | K 1 | K 1 | A 2 | S 2 | S 2 | S 2 | S ``` Desired o/p: ``` D | E | Total_E_in_D ---------------------- 1 | K | 3 1 | A | 3 ...
The specific answer to the question is: ``` select dept, count(*) as numemployees, count(distinct emp) as numDistinctEmployees from d1 group by dept; ``` This just seems quite unusual, because the it assumes that employees would be in the same department more than once. EDIT: Strange data format, but just use aggre...
You can group on the department and the employee, and join in a query where you group on the department to count the employees: ``` select e.Dept, e.Emp d.EmpCount from table e inner join ( select Dept, count(distinct Emp) as EmpCount from table group by Dept ) d on d.De...
SQL - GROUP BY and COUNT
[ "", "sql", "oracle", "group-by", "" ]
I have a query which I use InnoDB storage engine. I want to optimize it. It takes too much time to execute. I have 5 million data in my database. Now it takes 250 seconds to execute. ``` INSERT INTO dynamicgroups (adressid) SELECT SQL_NO_CACHE DISTINCT(addressid) FROM ( SELECT cluster_0.addressid FROM (...
Your queries all seem to be variations of this query: ``` SELECT g.addressid FROM table2.635_emadresmgroups g INNER JOIN table2.emaildata f_0 ON f_0.addressid = g.addressid WHERE (f_0.birthday > date(DATE_SUB(NOW(),INTERVAL 18 MONTH)) AND f_0.birthday < CURDATE() ) ``` I would suggest approaching this usin...
Even though the EXPLAIN operator isn't implemented as well as others.. I'd suggest you use it for your query. After that you can analyse what the result that EXPLAIN give and decide which columns should be indexed. For more information I'd suggest viewing these sources: [MySQL syntax: EXPLAIN](http://dev.mysql.com/d...
How to optimize Mysql Query that has 2 Inner Joins with Distinct? ( InnoDB )
[ "", "mysql", "sql", "performance", "" ]
I have a table with `Subscription' , when I sort recordes with order by I getting wrong result . My Result Does not sort , by MyColumn my query is : ``` Select Subscriptioncode from Subscription order by Subscriptioncode desc ``` my Result like as : ``` 90 80 8 700 73 634 100 ``` Why getting this Result ? > In Su...
Your column `SubscriptionCode` is currently not a numeric type, and it is likely a text type instead. However, you can `CAST` this column to an `INT` type and then the ordering should work with no problem: ``` Select Subscriptioncode from Subscription order by CAST(Subscriptioncode AS INT) desc ```
You should declare **Subscriptioncode** column **Datatype As INT** Example ``` create table Subscription( Subscriptioncode int) insert into Subscription values('90') insert into Subscription values('80') insert into Subscription values('8') insert into Subscription values('700') insert into Subscription values...
order by sort wrong records
[ "", "sql", "sql-server", "t-sql", "" ]
I'm new in SQL and I need to create table with specified field format. How to add CHECK condition that will assure that input will be formatted e.g. [LLLDD] where L is a letter and D is a digit?
Try this: <http://sqlfiddle.com/#!6/3974b> ``` create table test ( field1 char(5), check (field1 like '[a-z][a-z][a-z][0-9][0-9]') ); insert into test values ('ttt09'); --this will succeed ``` If you were to change the insert to: ``` insert into test values ('testi'); -- this will fail insert into test values (...
Try this if you are adding the constraint on a new table ``` CONSTRAINT ck_data_checker CHECK ([columnName] LIKE ('[A-Z][A-Z][A-Z][0-9][0-9]')) ``` Try this if you are adding the constraint on existing table ``` ALTER TABLE tableName ADD CONSTRAINT ck_data_checker CHECK ([columnName] LIKE ('[A-Z][A-Z][A-Z][0-9][...
How to specify input format in SQL create table?
[ "", "sql", "sql-server", "create-table", "" ]
Here is the table- ``` time ______ 2:00 am 1:05 PM 12:00 Pm 11:10pM ``` Here is what the result should look like- ``` time ______ 2:00 am 1:05 PM 12:00 Pm 11:10 pM ``` How can I do it? If you would like to try- ``` create table tmp ( time varchar2(50) ); insert into tmp values (' 2:00 am'); ...
You could use **REGEXP\_REPLACE** to modify the data to your desired pattern. For example, ``` SQL> SELECT TIME, 2 regexp_replace(trim(' ' FROM TIME), 3 '^([[:digit:]]{1,2})(:)([[:digit:]]{1,2})[[:space:]]*([[:alpha:]]{2})$', 4 '\1\2\3 \4') str 5 FROM tmp; TIME STR ----------...
You can use `regexp_replace` for formatting complex expressions: ``` select regexp_replace(time, '^[[:space:]]*([[:digit:]]{1,2}:[[:digit:]]{1,2})[[:space:]]*([aApP][mM]).*$', '\1 \2') from tmp; ``` SQL fiddle: <http://sqlfiddle.com/#!4/ba037f/2>.
How can I format result of the SQL in my case?
[ "", "sql", "oracle", "" ]
I have been forced into using **PostgreSQL**. I have read something about it but still it's new and I have no idea why I'm getting this error: `SQLSTATE[42703]: Undefined column: 7 ERROR: column t0.id does not exist LINE 1: SELECT t0.id AS id1, t0.user AS user2, t0.email AS ma...` I checked that id column exists for ...
`user` [is a reserved word](http://www.postgresql.org/docs/current/static/sql-keywords-appendix.html). It's an alias for `current_user`. ``` regress=> SELECT * FROM user; current_user -------------- myusername (1 row) ``` If you want to use `user` as a table name, since it's a reserved word you must *quote the ide...
define table name with special chars because some tables like user, postgresql is looking as system table. instead "user" write "`user`". * @ORM\Table(name="user") add * @ORM\Table(name="`user`")
Doctrine column id does not exist on PostgreSQL
[ "", "sql", "database", "postgresql", "doctrine", "" ]
I have a table `invoices` with a field `invoice_number`. This is what happens when i execute `select invoice_number from invoice`: ``` invoice_number -------------- 1 2 3 5 6 10 11 ``` I want a SQL that gives me the following result: ``` gap_start | gap_end 4 | 4 7 | 9 ``` How can i write a SQL to p...
The name of this problem is the "Gaps and Islands problem" which can be done with any [modern SQL](http://use-the-index-luke.com/blog/2015-02/modern-sql), using [window functions](http://www.postgresql.org/docs/current/static/tutorial-window.html): ``` select invoice_number + 1 as gap_start, next_nr - 1 as gap...
We can use a simpler technique to get all missing values first, by joining on a generated sequence column like so: ``` select series from generate_series(1, 11, 1) series left join invoices on series = invoices.invoice_number where invoice_number is null; ``` This gets us the series of missing numbers, which can be u...
Find gaps of a sequence in SQL without creating additional tables
[ "", "sql", "postgresql", "gaps-and-islands", "" ]
I am trying to do a JOIN on two Tables. Each table contains a UPC varchar2(20) from different data sources. What makes this JOIN a bit difficult is that the values of UPC can vary in size, can sometimes be padded with leading zeros, and sometimes not. All contain a trailing check digit. For example: ``` Tabl...
You can try this: ``` select * from table1 inner join table2 on (CAST(CAST(table1.UPC AS BIGINT) AS VARCHAR)) =(CAST(CAST(table2.UPC AS BIGINT) AS VARCHAR)) ``` **[SQL FIDDLE DEMO](http://sqlfiddle.com/#!6/addd1/5)** or ``` select * from table1 inner join table2 on (RIGHT(table1.UPC,(LEN(table1.UPC)...
This is not the highest-performance option, but it is the simplest: ``` SELECT T1.UPC, T2.Column1 FROM myTable T1 INNER JOIN myTable T2 ON RIGHT(REPLICATE('0', 20) + T2.UPC, 20) = RIGHT(REPLICATE('0', 20) + T1.UPC, 20) ``` Alternatively, you can create computed columns for these padded UPCs, and place ind...
Best Way to do a JOIN on Product UPC varchar(20)?
[ "", "sql", "sql-server", "" ]
I have this table ``` create table customers(id int, cust text, email id, cust_grp int); ``` and I use the following select query to get 3 results in 3 different conditions ``` select count(*) as cust_with_email from customers where email<>'' and cust_grp=101; result -------- 199 select count(*) as cust_without_...
You can use [`case when`](http://www.postgresql.org/docs/9.4/static/plpgsql-control-structures.html#PLPGSQL-CONDITIONALS) to filter `email` *column* and concatenate the result using `|` symbol ``` SELECT count(*) || '|' || count(CASE WHEN email <> '' THEN email END) || '|' || c...
Try this: ``` SELECT count(*), count(email = '' OR NULL), count(email <> '' OR NULL) FROM customers WHERE cust_grp = 101; ``` Or, In PG 9.4+: ``` SELECT count(*), count(*) FILTER (WHERE email = ''), count(*) FILTER (WHERE email <> '') FROM customers WHERE cust_grp = 101; ```
Complex select on a single column
[ "", "sql", "postgresql", "" ]
Welcome! I am currently working on some C# and I encountered a rather silly issue. I need to fill ListBox with some data from database obviously. Problem is varchar filtering. I need to filter codes and display only the right ones. Example of codes are: `RRTT, RRTR, RT12, RQ00, R100, R200, R355, TY44, GG77 etc. Four ...
In SQL Server, you can make use of wildcards. Here is one approach: ``` where rcode like 'R___' and -- make sure code has four characters rcode not like 'R%[^0-9]%' -- and nothing after the first one is not a number ``` Or: ``` where rcode like 'R[0-9][0-9][0-9]' ``` In other databases, you would norma...
here solution using like ``` SELECT * FROM ( VALUES ( 'R123'), ( 'R12T' ), ( 'RT12' ) ) AS t(test) where test like 'R[0-9][0-9][0-9]' ```
SQL Like filtering
[ "", "sql", "sql-server", "t-sql", "sql-like", "varchar", "" ]
i am having table in ms access named as stockitems, table structure is.. ``` stdate stitems 01-04-2015 Red 02-04-2015 Blue 08-04-2015 Green 01-05-2015 Grey 02-05-2015 Violet 09-05-2015 Purple 04-06-2015 Sky Blue ``` i am using the below code to select records from that table... ``` Dim report As Ne...
MS/Access interprets dates as mm/dd/yy and so you are selecting data from January 4th -> March 5th. Reformat your dates in the SQL as mm-dd-yyyy. Generally Ms/Access actually requires the date literals in the format #mm/dd/yyyy# (i.e. with the #'s). ``` Dim dtDate1 as DateTime = DateTime.Parse(date1.text) Dim dtDate2 ...
You need properly formatted date expressions in your SQL: ``` Dim xs1 As string Dim xs2 As string Dim sql as string xs1 = Date.Parse(date1.Text).ToString("yyyy'/'MM'/'dd") xs2 = Date.Parse(date2.Text).ToString("yyyy'/'MM'/'dd") sql = "select * from stockitems where stdate between #" & xs1 & "# and #" & xs2 & "#" Dim ...
Query records between two dates using VB.net/MS Access
[ "", "sql", "vb.net", "ms-access", "" ]
I'm using PostgreSQL. I need to select the **max of each group**, the situation is that the table represents the products sell on each day, and I want to know the top sold product of each day. ``` SELECT sum(detalle_orden.cantidad) as suma,detalle_orden.producto_id as producto ,to_char(date_trunc('day',orden.fec...
You can still use `DISTINCT ON` to get this done in a single query level without subquery, because `DISTINCT` is applied after `GROUP BY` and aggregate functions (and after window functions): ``` SELECT DISTINCT ON (3) sum(d.cantidad) AS suma , d.producto_id AS producto , to_char(o.fecha AT TIME ZONE ...
You can (ab)use `SELECT DISTINCT ON` with the appropriate ordering clause. Assuming you made your previous query into a view: ``` SELECT DISTINCT ON (dia, producto) * FROM some_view ORDER BY dia, producto, suma DESC; ``` the `DISTINCT` ensures you will retain only one row for every day and product, and the `ORDER BY`...
Select max record of each group on a group by
[ "", "sql", "postgresql", "aggregate-functions", "greatest-n-per-group", "" ]
i have table like ``` CREATE TABLE meta.fk_payment1 ( id serial NOT NULL, settlement_ref_no character varying, order_type character varying, fulfilment_type character varying, seller_sku character varying, wsn character varying, order_id character varying, order_item_id bigint, .... ); ``` i am i...
Copy distinct data to work table `fk_payment1_copy`. The simplest way to do that is to use `into` ``` SELECT max(id),settlement_ref_no ... INTO fk_payment1_copy from fk_payment1 GROUP BY settlement_ref_no ... ``` delete all rows from `fk_payment1` ``` delete from fk_payment1 ``` and copy data from `fk_payment1_cop...
You can do like this **e.g.** ``` DELETE FROM table_name WHERE ctid NOT IN (SELECT MAX(dt.ctid) FROM table_name As dt GROUP BY dt.*); ``` run this query ``` DELETE FROM meta.fk_payment1 WHERE ctid NOT IN (SELECT MAX(dt.ctid) FROM meta.fk_payment1 A...
Delete duplicate records from a Postgresql table without a primary key?
[ "", "sql", "postgresql", "" ]
I have a simple query ``` SELECT Group, Value, NULL AS MONTH from tbl_A ``` which returns ``` Group Value Month A 100 NULL B 110 NULL ``` I'm seeking results that return ``` Group Value Month A 100 1 A 100 2 A 100 3 ... B 110 1 B 110 2 B ...
You can use `VALUES` clause to define a [Table Value Constructor (TVC)](https://www.simple-talk.com/sql/sql-training/table-value-constructors-in-sql-server-2008/) . Then `CROSS APPLY` in order to get required result set: ``` SELECT [Group], Value, x.y AS MONTH from tbl_A CROSS APPLY (VALUES (1), (2), (3)) x(y) ``` ...
Try `CROSS join` as below ``` select Group, Value, MONTH from tbl_A cross join (select 1 as MONTH union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 ...
Force repeated rows with different derived value
[ "", "sql", "t-sql", "" ]
I recently responded [to this question](https://stackoverflow.com/questions/30163920/formatting-datetime-in-ssrs-expression) in the SSRS-2008 tag that required changing the day number in a date to the ordinal number (i.e. "1st", "2nd" instead of "1", "2"). The solution involved a VB.Net function. I'm curious how one wo...
Here's a scalable solution that should work for any number. I thought other's used % 100 for 11,12,13 but I was mistaken. ``` WITH CTE_Numbers AS ( SELECT 1 num UNION ALL SELECT num + 1 FROM CTE_Numbers WHERE num < 1000 ) SELECT CAST(num AS VARCHAR(10)) + CASE WHEN num...
You can do that just as easily in SQL as in the app layer: ``` DECLARE @myDate DATETIME = '2015-05-21'; DECLARE @day INT; SELECT @day = DAY(@myDate); SELECT CASE WHEN @day IN ( 11, 12, 13 ) THEN CAST(@day AS VARCHAR(10)) + 'th' WHEN @day % 10 = 1 THEN CAST(@day AS VARCHAR(10)) + 'st' WHEN @...
How to create ordinal numbers (i.e. "1st" "2nd", etc.) in SQL Server
[ "", "sql", "sql-server", "t-sql", "" ]
I have a week number and year and i need to display "total for mm/dd/yy to mm/dd/yy in a row of my ssrs report. My week starts with Monday. For example if my week number is '2' and year is '2010' then I have to display "total for 01/04/2010 to 01/10/2010 in my ssrs column. how to do this?
Try this ``` declare @year char(4) = '2010' declare @week int = 2 declare @fromdate datetime declare @todate datetime set @fromdate = DATEADD(wk, DATEDIFF(wk, 6, '1/1/' + @year) + (@week-1), 7); set @todate = DATEADD(wk, DATEDIFF(wk, 5, '1/1/' + @year) + (@week-1), 6) ; ;WITH dates AS ( SELECT CONVERT(datetime,@f...
SQL Server has a [DATEPART](https://msdn.microsoft.com/en-us/library/ms174420.aspx) function which calculates the ordinal week number of a year. However, you have to call [DATEFIRST](https://msdn.microsoft.com/en-AU/library/ms181598.aspx) before this to define which day of the week represents the start of the week. In ...
Finding week start and week end date
[ "", "sql", "sql-server", "sql-server-2008", "reporting-services", "ssrs-2008-r2", "" ]
I've a product table with three columns: 1. product\_id 2. product\_name 3. product\_keywords And it contains values something like that: > product\_id | product\_name | product\_keywords > 1                |Computer         |pc, computer, laptop, personal computer, desktop computer > ---------------------------...
Although my first instinct would be to re-design the schema to have a `keywords` table with unique values and a mapping table between the products and the keywords, MySQL actually offers an elegant way to query comma-delimited strings with the [`find_in_set`](https://dev.mysql.com/doc/refman/5.6/en/string-functions.htm...
You can use [find\_in\_set](https://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_find-in-set). ``` select * from `table` where find_in_set(' Computer',product_name) ``` But storing values as csv is very bad database design.
mysql select rows on comma seperated value in column
[ "", "mysql", "sql", "select", "" ]
I have a large equation in a select statement that I need to reference in a where statement I think it is eating up my efficiency, I do not want to reference it more than I need to. ``` SELECT 'HeaderDetail' AS rowType, ... , [large CASE/WHEN statement] AS Tracking ... WHERE NOT(@DNC IN([large CASE/WHEN statement])) A...
What happens when you filter the rows in `outer query` or `CTE`. ``` With CTE as ( SELECT 'HeaderDetail' AS rowType, ... , [large CASE/WHEN statement] AS Tracking ... ) select * from CTE WHERE NOT(@DNC IN(Tracking)) AND Tracking IS NOT NULL ``` or use `Sub-Select` ``` select * from ( SELECT 'HeaderDetail' AS rowTy...
use a subquery ``` select * from ( your query with the large case statement goes here ) temp where theAliasForThatCaseStatment is not null ```
SQL Reference Large Equation in Select Statement
[ "", "mysql", "sql", "sql-server", "performance", "subquery", "" ]
I know it is possible to filter a query from a list as in `Select * from table where ID in (1,2,3,4)`, but is it possible to select from a list? For example, I'd like to select date and offset date from a list of offset hours: ``` select sysdate, sysdate - offset / 24 as offsetSysdate from dual, (1,2,3,4) as offset `...
You can use a database "table of number" type - either create one or use one that handily exists like SYS.KU$\_OBJNUMSET: ``` select sysdate, sysdate - offset.column_value / 24 as offsetSysdate from TABLE (KU$_OBJNUMSET(1,2,3,4)) offset ``` Note that above `offset` is now an alias for the TABLE, and there is a pseudo...
Sure, use a subselect for that ``` select sysdate, sysdate - offset / 24 as offsetSysdate from ( select 1 as offset from dual union select 2 from dual union select 3 from dual union select 4 from dual ) ``` For a more sophisticated way to generate the number sequence, see e.g. [here](https...
Oracle: Can I select from a list of values?
[ "", "sql", "oracle", "" ]
I'm sitting at the following problem: I'm writing a view where I join several tables to a person table. And I now trying to join the partners table but I only need the historical last valid partner row: partners table: ``` id, name, married_at, divorced_at, died_at, someone_id ``` As you can see it's about partners ...
This ought to do what you want: ``` with partners (id, name, married_at, divorced_at, died_at, someone_id) as (select 1, 'partner', to_date('01/01/2000', 'dd/mm/yyyy'), null, null, 12 from dual union all select 2, 'honey1', to_date('15/01/2000'...
If I understand your question (and I believe I do), you should try something like this: ``` SELECT * FROM someone_table s left join ( SELECT * FROM ( SELECT * FROM partners p WHERE p.someone_id = s.id ORDER BY GREATEST(died_at, divorced_at, married_at) ) x WHERE ROWNUM =...
SQL Join only the last historical row
[ "", "sql", "oracle", "greatest-n-per-group", "" ]
I have 2 similar tables, one with all the data and the other contains a subset of the first. Every 2-3 days I need to insert in the second table the missing values, and I use this code ``` INSERT INTO [SRVDB2].[dbt].[curve].[curve_value] SELECT * FROM [SRVDB1].[dbt].[curve].[curve_value] as DB01 WHERE TargetDate >= '2...
Add explicit check for `NULL` for both of these columns: ``` INSERT INTO [SRVDB2].[dbt].[curve].[curve_value] SELECT * FROM [SRVDB1].[dbt].[curve].[curve_value] as DB01 WHERE TargetDate >= '20150505' and NOT EXISTS (SELECT * FROM [SRVDB2].[dbt].[curve].[curve_value] as DB02 WHERE DB02.TargetDate = ...
@dotnetom's answer (+1) should work for your problem. However, making some assumptions on the problem you describe, I suspect the following would work just as well: ``` INSERT INTO [SRVDB2].[dbt].[curve].[curve_value] SELECT * FROM [SRVDB1].[dbt].[curve].[curve_value] WHERE TargetDate >= '20150505' EXCEPT SELECT * FRO...
SQL server update table with missing values
[ "", "sql", "sql-server", "difference", "" ]
I have a database table in which multiple customers can be assigned to multiple types. I am having trouble formulating a query that will exclude all customer records that match a certain type. For example: ``` ID CustomerName Type ========================= 111 John Smith TFS-A 111 John Smith PRO 111 Jo...
You can get all `'PRO'` customers and use `NOT EXISTS` clause to exclude the ones that are also `'TFS'`: ``` SELECT DISTINCT ID, CustomerName FROM mytable AS t1 WHERE [Type] = 'PRO' AND NOT EXISTS (SELECT 1 FROM mytable AS t2 WHERE t1.ID = t2.I...
``` Select DISTINCT(Customername),ID FROM tablename WHERE NOT (ID IN (SELECT ID FROM tablename WHERE type='PRO') AND ID IN (SELECT ID FROM tablename WHERE type='TFS')) ``` EDIT: now added working TFS clause Get all customers that do not have TYPE PRO AND TFS for example SQLFIDDLE:<http://sqlfiddle.com/#!9/...
Query to exclude two or more records if they match a single value
[ "", "sql", "sql-server", "" ]
I have column with all kinds of numbers, I am specifically trying to extract numbers that have either ``` 555 ``` or ``` 555.xx ``` or ``` 555.x ``` The output should look like this ``` 555 555.1 555.5 555.9 555.58 555.22 . . ``` IE I need an sql query that will return the rows that have just the number 555 wit...
You can try `LIKE` statement ``` WHERE Col LIKE '555.%' OR Col = '555' ```
As a fast approach I would do ``` CAST((ValueOfTable * 100.00) AS DECIMAL(18, 2)) ``` > my table name is Diagnosis and the column name is code, where should I > add the table name and column name in this code ? In your situation: ``` SELECT CAST((code * 100.00) AS DECIMAL(18, 2)) FROM Diagnosis ; ``` I'm expectin...
SQL query to extract a number and its decimal variations
[ "", "sql", "netezza", "" ]
I have this below query. I like to insert only if the row is not present in TABLE1. How can I do that? ``` INSERT INTO TABLE1 (VEH_YEAR, VEH_MAKE, ACV_VOLUME) SELECT VEH_YEAR, VEH_MAKE, (SELECT COUNT(*) FROM ACV_VEHICLE_DETAILS WHERE YEAR = table2 .veh_year AND MAKE = table2 .veh_make ) AS ACV_VOLUME FROM TA...
Use `not exists`: ``` INSERT INTO TABLE1 (VEH_YEAR, VEH_MAKE, ACV_VOLUME) SELECT VEH_YEAR, VEH_MAKE, (SELECT COUNT(*) FROM ACV_VEHICLE_DETAILS vd WHERE vd.YEAR = t2.veh_year AND vd.MAKE = t2.veh_make ) AS ACV_VOLUME FROM TABLE2 t2 WHERE VEH_YEAR IS NOT NULL A...
You can use `MERGE` with `WHEN NOT MATCHED THEN INSERT`: ``` merge into Table1 t using ( SELECT VEH_YEAR, VEH_MAKE, (SELECT COUNT(*) FROM ACV_VEHICLE_DETAILS WHERE YEAR = table2 .veh_year AND MAKE = table2 .veh_make ) AS ACV_VOLUME FROM TABLE2 table2 WHERE VEH_YEAR IS NOT NULL AND VEH...
INSERT INTO SELECT if NOT EXISTS in oracle
[ "", "sql", "oracle", "not-exists", "" ]
I want to condense the following three queries into one query and out put the totals into 3 columns. Oh and how do I make it so I don't have to declare the date. I want it to "know" the current date, month, and year. ``` DECLARE @myDate as datetime SET @myDate = '2015-01-1' select SUM(Amount) as 'Day Total' from [Acc...
If I'm understanding the problem correctly, then something like this ought to work: ``` declare @today date = convert(date, getdate()); select [Day Total] = sum(case when [AccountingDate] >= @today and [AccountingDate] < dateadd(day, 1, @today) then [Amount] else 0 end), [Month Total] = sum(case when [Acco...
Make them all part of a 'super' select: ``` DECLARE @myDate as datetime SET @myDate = '2015-01-1' SELECT (select SUM(Amount) from [Accounting].[dbo].[HandPay] where AccountingDate>=@myDate and AccountingDate<dateadd(day,1,@myDate) ) as 'Day Total', (select SUM(Amount) from [Accounting].[dbo].[HandPay] where A...
SQL Server How to combine 3 queries into one?
[ "", "sql", "sql-server", "" ]
In Microsoft SQL Server, to test something like this in the query window: ``` select * from Users where LastName = @lastname ``` I can add this before the command: ``` declare @lastname varchar(16) set @lastname = 'Troy' ``` But in PostgreSQL, I cannot find a similar way to do so. It seems the only thing I can do i...
I config postgres to log all the commands, and copy the command from the log file, so all the parameters are already replaced with the value, and test the command in the query window. May not be the best approach, but it is easy and works for me
Various options. Provide parameters in a [CTE](https://www.postgresql.org/docs/current/queries-with.html) to have "variables" in **pure SQL**: ``` WITH var(lastname) AS (SELECT 'Troy'::varchar(16)) SELECT * FROM users, var v WHERE lastname = v.lastname; ``` This works for *any* query. Since the CTE `var` holds ...
How to test my ad-hoc SQL with parameters in Postgres query window
[ "", "sql", "postgresql", "parameterized-query", "" ]
I have a SQL table that have ID , start and End Dates. Example, ``` ID StartDt EndDt 123 1/1/2010 12/31/2014 456 7/16/2013 11/20/2014 ``` Based on Oct-Sept FY calendar I can get the FY from the dates (e.g., 2010 and 2015 for ID 123). However, I would like to duplicate the row with the initial and last FY; ...
The query below uses a recursive CTE to count years from the start date fiscal year to the end date fiscal year. ``` ;WITH CTE AS ( SELECT ID, YEAR(StartDt) AS FY, YEAR(EndDt) AS EY FROM [Source] UNION ALL SELECT ID, FY + 1, EY FROM CTE WHERE FY ...
You can use a recursive `cte` to get a list of all possible years, then `JOIN` to that: ``` ;with cte AS (SELECT 2010 AS Yr UNION ALL SELECT Yr + 1 FROM cte WHERE Yr < 2015) SELECT a.ID, b.Yr FROM YourTable a JOIN cte b ON b.Yr BETWEEN YEAR(a.StartDt) AND YEAR(...
How to duplicate Rows with new entries
[ "", "sql", "t-sql", "" ]
I'm running a series of SQL queries to find data that needs cleaning up. One of them I want to do is look for: * 2 or more uppercase letters in a row * starting with a lowercase letter * space then a lowercase letter For example my name should be "John Doe". I would want it to find "JOhn Doe" or "JOHN DOE" or "John d...
The key is to use a case-sensitive collation, i.e. `Latin1_General_BIN`*\**. You can then use a query with a [`LIKE` expression](https://msdn.microsoft.com/en-us/library/ms179859.aspx) like the following ([SQL Fiddle demo](http://sqlfiddle.com/#!6/2b7ce/7)): ``` select * from foo where name like '%[A-Z][A-Z]%' collate...
You can use a regular expression. I'm not a SQL Server whiz, but you want to use [RegexMatch](https://msdn.microsoft.com/en-us/magazine/cc163473.aspx). Something like this: ``` select columnName from tableName where dbo.RegexMatch( columnName, N'[A-Z]\W[A-Z]' ) = 1 ```
How to find more than 1 uppercase character
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "case-sensitive", "" ]
I would like to store people's information in the database (table). Every person can have a different set of properties. I would like to store all these properties. But creating fixed number of columns does not make my application scalable. So, another approach is to store these values inside key-value tables which le...
What Database are you using. One solution (if your DB supports) could be storing the person's information in an XML Format.
If you are stuck using SQL Server for this task, you can leverage its XML Support. Notably, you can use XPath. [Using XPath Queries in SQLXML 4.0](https://msdn.microsoft.com/en-us/library/ms171802(v=sql.105).aspx)
Storing entities with dynamic set of properties in a table (and using fixed columns or key-value tables)
[ "", "sql", "sql-server", "database", "database-design", "key-value", "" ]
I have a column in our database that holds 4 fields as a "\" delimited string. I have split the fields as I need them seperatly in my report. I also need to use these fields individually as where criteria against another table. **Things I've tried:** Temporary table: ``` CREATE GLOBAL TEMPORARY TABLE pfcc ON COM...
I think this is the query you want: ``` select gch.Line, gch.productB, gch.productC, REGEXP_SUBSTR(p.delimited, '[^\]+', 1, 4) from products p inner join lineitems gch on gch.Line = REGEXP_SUBSTR(p.delimited, '[^\]+', 1, 1) and gch.productB = REGEXP_SUBSTR(p.delimited, '[^\]+', 1, 2) and ...
You can use CTE as follows. ``` with pfcc as (select REGEXP_SUBSTR(delimited , '[^\]+', 1, 1) colA, REGEXP_SUBSTR(delimited , '[^\]+', 1, 2) colB, REGEXP_SUBSTR(delimited , '[^\]+', 1, 3) colC, REGEXP_SUBSTR(delimited , '[^\]+', 1, 4) colD from products where productid = 1) select * from pfcc ...
Join to splitted string columns in Oracle
[ "", "sql", "oracle", "join", "plsql", "" ]
I need to get some values from a database and count all rows. I wrote this code: ``` SELECT author, alias, (select COUNT(*) from registry WHERE status='OK' AND type='H1') AS count FROM registry WHERE status='OK' AND type='H1' ``` It works, but, how can I simplify this code? Both `WERE` condition thereof.
If the query is returning the resultset you need, with the "total" count of rows (independent of author and alias), with the same exact value for "count" repeated on each row, we could rewrite the query like this: ``` SELECT t.author , t.alias , s.count FROM registry t CROSS JOIN ( SELECT COUNT(*) AS `c...
try this: ``` SELECT author, alias, count(1) AS caunt FROM registry WHERE status='OK' AND type='H1' group by author, alias ```
Simplify select with count
[ "", "mysql", "sql", "select", "count", "" ]
The [problem statement](http://sqlzoo.net/wiki/SELECT_from_WORLD_Tutorial) is: > Put the continents right... > > * Oceania becomes Australasia > * Countries in Eurasia and Turkey go to Europe/Asia > * Caribbean islands starting with 'B' go to North America, other Caribbean islands go to South America > > Show the name...
This works for me. Don't ask me why I have to use the ORDER BY (didn't work without it). ``` SELECT name, continent, CASE WHEN continent='Oceania' THEN 'Australasia' WHEN continent = 'Eurasia' THEN 'Europe/Asia' WHEN name='Turkey' THEN 'Europe/Asia' WHEN continent='Caribbean' AND name LIKE ...
Looks to be a bug in their system unless I'm reading the question wrong: ``` SELECT name, continent, CASE WHEN continent='Oceania' THEN 'Australasia' WHEN continent IN ('Eurasia') THEN 'Europe/Asia' WHEN name='Turkey' THEN 'Europe/Asia' WHEN continent='Caribbean' AND name LIKE 'B%' THEN 'North ...
What is the solution to 13th part of 'select from world' tutorial on sqlzoo?
[ "", "sql", "case", "sql-like", "case-when", "" ]
Four simple SELECT statements: ``` SELECT 33883.50 * -1; SELECT 33883.50 / -1.05; SELECT 33883.50 * -1 / 1.05; SELECT (33883.50 * -1) / 1.05; ``` But the results are not as I would expect: ``` -33883.50 -32270.000000 -32269.96773000 -32270.000000 ``` That third result is the one that seems questionable. I can see w...
In your example ``` 33883.50 * -1 / 1.05 ``` is evaluated as ``` 33883.50 * (-1 / 1.05) ``` instead of ``` (33883.50 * -1) / 1.05 ``` which results in a loss in precision. I played a bit with it. I used SQL Sentry Plan Explorer to see the details of how SQL Server evaluates expressions. For example, ``` 2 * 3 *...
Do you know **[*BODMAS*](http://www.math-only-math.com/bodmas-rule.html)** rule. The answer is correct its not because of Sql Server, Its a basic mathematics. First comes `Division` then comes the `Subtraction`, So always Division will happen before Subtraction If you want to get correct answer then use proper parent...
Why is SQL Server changing operation order and boxing the way it does?
[ "", "sql", "sql-server", "sql-server-2014", "" ]
There is a table named PRODUCT\_PRICE: ``` CREATE TABLE [TEST].[PRODUCT_PRICE] ( [PRICE_ID] [bigint] NOT NULL, [PRODUCT_ID] [bigint] NOT NULL, [PRICE_DATE] [date] NOT NULL, [IS_SALE_PRICE] [bit] NOT NULL, [UNIT_PRICE] [decimal](18, 2) NOT NULL ) ``` It has the following records: ``` PRICE_ID PROD...
If you're sure that there will only be a maximum of 2 rows for each `PRODUCT_ID` - `PRICE_DATE` combination, you can use conditional aggregation instead of `JOIN`: [**SQL Fiddle**](http://sqlfiddle.com/#!6/5d84d/1/0) ``` SELECT PRICE_ID = MAX(CASE WHEN RN = 1 THEN PRICE_ID END), PRODUCT_ID, PR...
You are getting `PRICE_ID=1` vs `PRICE_ID =2` and `PRICE_ID=2` vs `PRICE_ID=1` So you have a repeated row. In the `ON CLAUSE`, you should force to only `join` when `PRICE_ID1 < PRICE_ID2` Add this to the ON CLAUSE: ``` AND PR1.PRICE_ID < PR2.PRICE_ID ``` And use LEFT JOIN With that changes u will get 4 rows, u nee...
How to JOIN a table with itself and display it as a single row
[ "", "sql", "sql-server", "" ]
I have a hardware group and many devices into this group. Example: ``` + Room 1 |-- Computer |-- Camera + Room 2 |-- Computer |-- Switch ``` All devices are monitored using ping. When some device is not working the program add a row into a table saying the start of break. When the device back on then the program upda...
You are looking to combine the different groups into "islands" and to count the extend of the islands. That is why this type of problem is sometimes called gaps and islands. Let me assume that you are using SQL Server 2012+. That slightly simplifies the calculations. The idea is to determine the starts and ends for ov...
A bit convoluted, but I have a working solution. The trick was to alter the data presentation. EDIT : This solution works as long as there are never two events that take place on the same device at the same time. I left a SQL Fiddle here : <http://sqlfiddle.com/#!6/59e80/8/0> ``` declare @tblGroup table (id int, nam...
Unioning overlapping time ranges, then summing the total time
[ "", "sql", "sql-server", "" ]
I have a table with 32 Million rows and 31 columns in PostgreSQL 9.2.10. I am altering the table by adding columns with updated values. For example, if the initial table is: ``` id initial_color -- ------------- 1 blue 2 red 3 yellow ``` I am modifying the table so that the result is: ``` id ...
> The columns types are either character varying or character. Don't use `character`, that's a misunderstanding. `varchar` is ok, but I would suggest just `text` for arbitrary character data. * [Any downsides of using data type "text" for storing strings?](https://stackoverflow.com/questions/20326892/any-downsides-of...
Maybe I'm misreading the question, but as far as I know, you have 2 possibilities for creating a table with the extra columns: 1. `CREATE TABLE` This would create a new table and filling could be done using * `CREATE TABLE .. AS SELECT..` for filling with creation or * using a separate `INSERT...SELECT...`...
Column Copy and Update vs. Column Create and Insert
[ "", "sql", "postgresql", "database-administration", "postgresql-performance", "bulkupdate", "" ]
In SQL Server, if my `SELECT` statement in a subquery returns no row, is then the result of the subquery equal to `NULL`? I made some research, but I am not sure about it. Example: ``` IF (SELECT TOP 1 CLMN1 FROM SOMETABLE) IS NOT NULL THEN .... ``` I am asking to understand the behaviour of the if-statement abov...
NULL means no value, for example that the "box" for a certain column in a certain row is empty. NO ROW means that there are no rows.
Looks like the answer is yes: ``` DECLARE @Test TABLE (Id INT) INSERT INTO @Test VALUES (1) SELECT * FROM @Test WHERE Id = 2 SELECT CASE WHEN (SELECT * FROM @Test WHERE Id = 2) IS NULL THEN 1 ELSE 0 END ``` EDIT: after you updated your question I think I should add that instead of checking if there are rows with...
Is a subquery, which is returning no row, equal to NULL?
[ "", "sql", "sql-server", "select", "" ]
I have the following database table: ``` LNr OrderNr Ident Amount 1 128 3 123.00 2 128 14 200.00 3 1290 3 300.00 4 13400 3 637.00 ``` I want to calculate the sum of the `Amount`-fields where `Ident` equals 3, but not 14 at the same time. So I want the database server to return only...
You can add another `not exists` condition: ``` SELECT SUM(Amount) FROM mytable x WHERE Ident = 3 AND NOT EXISTS (SELECT * FROM mytable y WHERE x.OrderNr = y.OrderNr AND y.Ident = 14) ```
The only way to do that is to further qualify your WHERE clause, by either excluding row 1, or including just row 3 and 4. You need additional filtering. There must other tables joined to that table that should allow you to filter gracefully based on whatever business rules you have defined.
How to return only one result from sql table?
[ "", "sql", "sql-server", "select", "" ]
I have a table in sql server 2012, where one column is nvarchar. It contains Romanian characters. We've noticed that only some of the letters 'Ș' do not show in reports at all, so I found that it depends of the keyboard settings. There are two different keyboard settings for Romanian - Standard and Legacy. Letter 'Ș' ...
So firstly from my comments, `CHAR(63)` is misleading as it represents a character that sql server is unable to display: [Unable to replace Char(63) by SQL query](https://stackoverflow.com/questions/6441208/unable-to-replace-char63-by-sql-query) The issue is possibly down to your selected collation, as if I run this ...
``` WHERE columnname LIKE N'%'+NCHAR(536)+'%' ``` This should help you find the character even if it was inserted as an unknown character as in the first insert below. ``` DECLARE @Table TABLE (text nvarchar(50)) INSERT INTO @Table(text) SELECT 'Ș' UNION ALL SELECT N'Ș' SELECT UNICODE(text) UNICODE FROM @Table ``` ...
Cannot find letter 'ș' or 'Ș' inserted from Romanian (Standard) keyboard
[ "", "sql", "sql-server", "t-sql", "sql-server-2012", "" ]
How do I count the average amount of times a given number appears in a database? ``` id | ... ---------- 1 | ... 5 | ... 2 | ... 3 | ... 3 | ... 1 | ... 6 | ... 4 | ... 3 | ... ...| ... ``` `id` corresponds to the id of the user. Perhaps the table is for customer orders or donations made by a user...
How about this? ``` select count(id) / count(distinct id) as avgEntriesPerUser from table t; ``` The only issue with this would be a `NULL` value for `id`. If this occurred (and I find it highly unlikely for a column named `id`), then the above ignores those rows entirely. It can be modified to take this situation in...
You mean? ``` select avg(countPerID) from ( select id, count(*) as countPerID from table group by id) x ```
Find average amount of times a value appears in table
[ "", "sql", "pdo", "" ]
I'm stuck and I could use a little input. How can I insert the SUM(amount) of all values of "accountKonto" of table "Buchung" into one row of the table "Erfolg"? "Buchung": id accountKonto amount "Erfolg": id totalAmountAccountKonto1 totalAmountAccountKonto2 … For each possible "accountKonto" in "Buchung", there is ...
You should combine `INSERT .. SELECT` with [`PIVOT`](https://technet.microsoft.com/en-US/library/ms177410%28v=sql.105%29.aspx). ### Using PIVOT (available in SQL Server and Oracle, only): ``` SELECT * FROM ( SELECT accountKonto, amount FROM Buchung ) t PIVOT ( SUM(amount) FOR accountKonto IN ([1], [2], [3]) ) A...
The design you are using is not very good - you run out of columns pretty fast (for MySQL - approx. 4k columns, depends a bit). I'd use design for aggregate table, similar to: ``` iteration | accountNr | sum ``` Now, to fill the table, you just do (replace 1 with some timestamp, iteration ID, link to some aggregatio...
How can I insert values from SELECT SUM into other table?
[ "", "mysql", "sql", "sql-server", "filemaker", "" ]
I'm using SQLite and I would like to know how to generalize the following SQL statement so that inequality conditions can be imposed on an arbitrary number of columns, not just column `x`: ``` SELECT * FROM t WHERE x BETWEEN xMin AND xMAX ``` I anticipated that this could be achieved in the following manner, but to n...
Your statement should work, e.g. with Oracle: ``` SELECT * FROM (SELECT 10 x, 40 y, 50 z FROM dual) WHERE (x BETWEEN 8 AND 12) AND (y BETWEEN 30 AND 42) AND (z BETWEEN 0 AND 100); ``` See [Fiddle demo](http://sqlfiddle.com/#!4/9eecb7db59d16c/736). With My SQL: ``` SELECT * FROM (SELECT 10 A...
Works fine in SQLite 3. ``` sqlite> CREATE TABLE test (x INT, y INT , z INT); sqlite> INSERT INTO test (x,y,z) VALUES (1,2,3), (2,3,4), (4,5,6); sqlite> SELECT * FROM test WHERE (x BETWEEN 0 AND 5) AND (y BETWEEN 0 AND 5) AND (z BETWEEN 0 AND 5) ...> ; 1|2|3 2|3|4 sqlite> ```
How do you write an SQL query which uses multiple BETWEEN optimizations?
[ "", "sql", "sqlite", "" ]
I've a table `ErrorLog` with following fields ``` Id - Primary key Message- varchar(200) CustomerId - int CreatedDate - DateTime ``` Everytime a Logged in user gets an error, it is logged in `ErrorLog` table. Now i want to fetch *distinct Message* along with *all other fields* where CreatedDate is equal to `getda...
Something like this should work: ``` with cte as( select *, row_number() over(partition by Message order by CreatedDate desc, CustomerID) as rn from Table where CreatedDate < cast(getdate() as date) and CreateDate >= dateadd(dd, -1, cast(getdate() as date)) ) select * from cte where rn = 1 ```
You need a ROW\_NUMBER to find the latest row per message: ``` select Id, Message, CustomerId, CreatedDate from ( select Id, Message, CustomerId, CreatedDate, row_number () over (partition by Message order by CreatedDate desc) as rn from ErrorLog where your-condition-here ) as dt w...
Get distinct value of column with date check
[ "", "sql", "sql-server-2008", "" ]
``` +------+------+ | id | no | +------+------+ | 1 | 1 | | 11 | 1 | | 21 | 1 | +------+------+ ``` I want to update 2nd row no. to 2. the query i can use is ``` update test set no = 2 where id = 11; ``` How can i achieve the same without where clause ??
To update the "second" row in the table, the row that has the second smallest id value... ``` UPDATE test t JOIN ( SELECT r.id FROM test r ORDER BY r.id LIMIT 1,1 ) s ON s.id = t.id SET t.no = 2 ``` **EDIT** As a followup to clarify the results of the query above... I...
I am not sure **why** you would want to but... ``` UPDATE `test` SET `no` = IF(`id`=11, 1, `no`); ``` For the record, I would be surprised if this didn't perform horribly as it would go through every row in the table.
Update without where clause
[ "", "mysql", "sql", "" ]
I am very new to hive and sql and I have a question about how I would go about the following: I have table A: ``` Name id Amy 1 Bob 4 Josh 9 Sam 6 ``` And I want to filter it using values from another table (table B): ``` Value id .2 4 .7 6 ``` To get a new table that looks like table ...
The correct syntax for the result I wanted was: ``` CREATE TABLE tableC AS SELECT tableA.* FROM tableA LEFT SEMI JOIN tableB on (tableA.id = tableB.id); ```
just join it.. ``` hive> CREATE TABLE TableC AS > SELECT A.* FROM TableA as A, > TableB as B > WHERE A.id = B.id; hive> SELECT * FROM TableC; OK Bob 4 Sam 6 ``` or try this, ``` hive> CREATE TABLE TableD AS > SELECT A.* FROM TableA as A join > TableB ...
Hive: filter a table using another table
[ "", "sql", "filter", "hive", "" ]
We are using the following question to get date out of a large mysql table. ``` SELECT fullPath, Permissiontype, DinstinguishedName from cdm.test where fullPath in (SELECT distinct fullPath FROMcdm.test WHERE (Permissiontype = 'EXPLICIT' and not DinstinguishedName ='') OR(Permissiontype = 'INHERITED' ...
For each record in the test table you're querying the entire table again in the subquery. Instead of using a subquery in the where clause, try an inner join on the same table. This will dramatically improve your performance. I haven't tried it yet but it could look like: ``` SELECT fullPath, Permissiontype, Dinstingu...
For the combination of IN statement and subqueries mysql has a usefull optimizer called EXISTS() (not specifically meant for this but can be used to optimize queries that use the IN statement in combination with subquery) According to the reference on <https://dev.mysql.com/doc/refman/5.0/en/subquery-optimization-with...
Mysql nested queries take a long time
[ "", "mysql", "sql", "mysql-workbench", "" ]
I have this SQL... ``` UPDATE table1 t1 SET (t1.wert) = (select t2.bezeichnung from table2 t2 where t1.id = t2.cpbezeichnung) where t1.id = t2.cpbezeichnung ``` ... which I cant run because it says me that it doesnt know `t2.cpbezeichnung` in line #5. How can I fix it?
Table with alias t2 is not defined for UPDATE query, so it's clearly not known at line 5. Table t2 is defined only inside subquery on lines 3 and 4. What exactly are you trying to achieve with condition on line 5? If do you want prevent setting NULL into t1.wert for rows where there is no appropriate record in table ...
The `t2` alias (along with `table2`) is only visible in the subquery. My guess is that you want ``` UPDATE table1 t1 SET t1.wert = (select t2.bezeichnung from table2 t2 where t1.id = t2.cpbezeichnung) where exists (select 1 from table2 t2 where ...
sql oracle update
[ "", "sql", "oracle", "" ]
Example related to my requirement. I have a table t\_policies\_details columns pol\_ref , inrtyp ``` inrtyp has values = ORD,PPC,AVCO,DSS,RVP, SP,TV ``` I want to fetch polref for which inrtyp is only SP and TV both , no any other. ``` SELECT DISTINCT p.polref, p.inrtyp FROM t_policies_details p WHERE p.inrtyp NOT I...
If I understand correctly, you want all instances where a `polref` has `inrtyp` for both 'TV', 'SP' but no other values at all. You can count the number of wanted and unwanted instances in a group by, and then apply logic in an outer select: ``` WITH cte AS ( SELECT p.polref, SUM(CASE WHEN p.inrtyp IN ('TV', ...
Please try below query. Query: SELECT DISTINCT p.polref, p.inrtyp FROM t\_policies\_details p WHERE p.inrtyp in ('SP','TV');
how to fetch data for particular values from a column among different values
[ "", "sql", "oracle", "plsql", "" ]
I have the following formula: ``` "Value1" * 100 * "Total day in a month" * "Value2" ``` I have the following table: ``` ID Date Time Value1 Value2 1 2014-01-01 00:00 10 20 2 2014-01-01 01:00 20 5 ``` I want to select a data in a year with only using one paramete...
You can get the number of days of a given date like this: ``` DECLARE @date DATETIME = '2014-01-01' SELECT DATEDIFF(DAY, @date, DATEADD(MONTH, 1, @date)) ``` And the query: ``` SELECT ID ,[Date] ,[Time] ,Value1 ,Value2 ,DATEDIFF(DAY, [Date], DATEADD(MONTH, 1, [Date])) AS Tota...
This expression will give you the number of days in the month that `date` is in no matter what day it is: ``` datediff(day, dateadd(month,datediff(month, 0, date),0), dateadd(month,datediff(month, 0, date)+1,0)) ```
SQL: Total days in a month
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
I have 3 tables in my database as shown below: ![enter image description here](https://i.stack.imgur.com/Imkhq.png) I want to insert data in `RESULT` table from `Infos` table. And only those rows are inserted that are listed in `Picker` table. But since `InfoID` column of `Result` table is a primary key, so it will re...
Finally, I figured out what was actually going wrong: ``` INSERT INTO @Result([INFOID],[VALUE],[PROCESSED]) (SELECT T1.Id, CASE WHEN T1.Value1 = '-1' THEN T1.Value2 ELSE T1.Value1 END, 0 FROM [Infos] T1 INNER JOIN (SELECT [InfoIDs] FROM Picker AS A1 WHERE (NOT EXISTS (SELECT [INFOID...
I think you need this query: ``` INSERT INTO @Result (SELECT ID, CASE WHEN i.Value1 = '-1' THEN i.Value2 ELSE i.Value1 END Value1, 0 FROM Infos i WHERE i.ID In (SELECT InfoIDs FROM Picker) AND NOT i.ID IN (SELECT InfoID FROM @Result)) ```
Inserting rows in a table from another table using a third table
[ "", "sql", "sql-server", "database", "stored-procedures", "join", "" ]
say I have 3 values, Bill, Steve, Jack. and I want to randomly update a table with those values, e.g. ``` Update contacts set firstname = ('Bill','Steve','Jack') where city = 'NY' ``` how do I randomize these values? Thanks
You can do this with the following trick: ``` update c set name=ca.name from contacts c outer apply(select top 1 name from (values('bill'),('steve'),('jack')) n(name) where c.id = c.id order by newid())ca; ``` `c.id = c.id` is just a dummy predicate that forces sql engine to call subquery for...
Here's some love using `choose` ``` with cte as ( select *, (ABS(CHECKSUM(NewId())) % 3) + 1 as n from contacts where city = 'NY' ) update cte set firstname = choose(n, 'Bill','Steve','Jack') ```
SQL Server 2012 Random string from a list
[ "", "sql", "sql-server", "sql-server-2012", "" ]
I am trying to query my database for all models with primary keys in a list. This is my query (idsList is an ArrayList containing integers): ``` new Select().from(PostModel.class) .where(Condition.column(PostModel$Table.ID).in(0, idsList)) .async().queryList(listener); ``` But Android Studio highlights the wh...
**DBFlow `v3.x` now allows you to pass a collection to `Condition.in()`** ``` List<String> ids = new ArrayList<>(); Condition.In in = Condition.column(Tree_Table.ID.getNameAlias()).in(ids); long count = new Select().count().from(Tree.class) .where(in) .count(); ```
Create a `In` Condition: ``` List<String> ids = new ArrayList<String>(); Condition.In in = Condition.column(Tree$Table.ID).in(ids.get(0)); for (i = 1; i < ids.size(); i++){ in.and(ids.get(i)); } long count = new Select().count().from(Tree.class) .where(in) .count(); ```
DBFlow select where COLUMN in List?
[ "", "android", "sql", "database", "dbflow", "" ]
My requirement is to display multiple rows data into a single cell. For example I have a teacher who is specialized in multiple subjects. ``` staffid Subjects ------------------- 13 Hindi 13 asd ``` I wants result in following format ``` Hindi, asd ``` for staffid 13. To do this task I used f...
Also try this method : ``` DECLARE @table TABLE(staffid INT, subject VARCHAR(30)) INSERT INTO @table VALUES (13,'Hindi'), (13,'English'), (14,'Japanese'), (14,'English') SELECT staffid, STUFF(grp, 1, 1, '') FROM @table a CROSS APPLY (SELECT ',' + subject FROM @table b ...
same as `@Deepak Pawar` variant, but without `cross apply` ``` DECLARE @table TABLE ( staffid INT , [subject] VARCHAR(30) ) INSERT INTO @table VALUES ( 13, 'Hindi' ), ( 13, 'English' ), ( 14, 'Japanese' ), ( 14, 'English' ) SELECT DISTINCT a.staffid , SUBS...
How to display multiple row data into a single cell with comma separated
[ "", "sql", "sql-server", "t-sql", "" ]
We have a legacy database schema that has some interesting design decisions. Until recently, we have only supported Oracle and SQL Server, but we are trying to add support for PostgreSQL, which has brought up an interesting problem. I have searched Stack Overflow and the rest of the internet and I don't believe this pa...
## Postgres 15 adds the clause `NULLS NOT DISTINCT` See: * [Create unique constraint with null columns](https://stackoverflow.com/questions/8289100/create-unique-constraint-with-null-columns/8289253#8289253) The solution is very simple now: ``` ALTER TABLE example ADD CONSTRAINT foo UNIQUE NULLS NOT DISTINCT (field...
Third method: use `IS NOT DISTINCT FROM` insted of `=` for comparing the key columns. (This could make use of the existing index on the candidate *natural* key) Example (look at the last column) ``` SELECT * , EXISTS (SELECT * FROM example x WHERE x.FIELD1 IS NOT DISTINCT FROM e.FIELD1 AND x.FIELD2 IS NO...
PostgreSQL multiple nullable columns in unique constraint
[ "", "sql", "postgresql", "database-design", "null", "unique-constraint", "" ]
A simplified example of what I need: Table 'Transport' has 2 columns; 'Vehicle' and 'Colour'. User can filter records by either a vehicle, a colour, or both. ``` variable vehicle_choice = user_selected_vehicle (selected from a dropdown for example) variable colour_choice = user_selected_colour If user_selected_vehic...
Here are two typical ways to solve this. Assume that the user input is in the variables `@vehicle` and `@colour`: ``` where (vehicle = @vehicle or @vehicle is null) and (colour = @colour or @colour is null) ``` The problem with this approach is the use of indexes. Indexing strategies have a hard time with `or`....
You can try something like ``` ("Select * From Transport Where Vehicle like '%' and Colour = 'yellow'") ```
select from table where column = anything
[ "", "sql", "sql-server", "" ]
I need to retrieve the distinct values of both the column and row. The oracle sql query in the current setup is given below: ``` select distinct ym.wh_id, ym.trlr_num, ym.arrdte, ri.invnum, ri.supnum from rcvinv ri, yms_ymr ym where ym.trlr_cod='RCV' and ri.trknum = ym.trlr_num and ym.wh_id <=50 and ym.trlr_stat in ('...
You could use the Analytic **ROW\_NUMBER()**. See the [SQL Fiddle](http://sqlfiddle.com/#!4/03ea9/1). For example, ``` SQL> SELECT trailer_number, 2 po, 3 vendor 4 FROM 5 (SELECT t.*, 6 row_number() OVER(PARTITION BY po, vendor ORDER BY po, vendor) rn 7 FROM t 8 ) 9 WHERE rn = 1;...
Your request can be written as: Get me the latest record per invnum. You get this by numbering (i.e. using `ROW_NUMBER`) the rows per invnum (i.e. `PARTITON BY invnum`) in the order desired, such that the latest record gets #1 (`ORDER BY ym.arrdte DESC`). Once the numbering is done, you remove all undesired records, i....
Oracle sql distinct query
[ "", "sql", "oracle", "distinct", "" ]
I need help writing a query to get some data from a table. I am trying to write a query that will select all of the book titles that have “bill” in their name and will display the title of the book, the length of the title, and the part of the title that follows “bill”. I know you are supposed to use the substring and ...
This is a Standard SQL version, afaik mysql should support those functions, too: ``` select Title ,char_length(Title) ,substring(Title from position('bill' in Title) + 4) from book where Title like '%bill%' ```
Use regexp for the match, as follows: ``` select title from books where title regexp '*book*' ``` As for what you're **supposed** to use, in my book, you're only supposed to use what gets the desired result. Optimisation comes later, if ever.
MYSQL query help- Substring and Instring
[ "", "mysql", "sql", "" ]
I have three related tables and need to select rows that show data from two tables based on a value (serial number) from the third. I am only interested in the max value of the serial number. I have tried multiple solutions suggested here on stackoverflow and I still cannot get my head around this. A sample code for m...
In SQL Server, probably the easiest way to do this is using [`APPLY`](https://technet.microsoft.com/en-us/library/ms175156%28v=sql.105%29.aspx): ``` SELECT p.usr_newref as reference, pag.tps_title as groupname, pag.pm_serial_number as serialnum FROM pm_process p OUTER APPLY (SELECT TOP 1 pa.pm_seria...
You can use `ROW_NUMBER()` to locate records having the maximum `serialnum` within each `reference` partition. Then, in an outer query, select only these records: ``` SELECT reference, groupname, serialnum FROM ( SELECT pm_process.usr_newref as reference, pm_assignment_group.tps_title as groupname, process_assig...
Selecting a record with max value on one of the joins
[ "", "sql", "sql-server", "greatest-n-per-group", "" ]
How do I read each line to determine if the customer has fully paid or partially paid or never paid? I would like the code to read every line of each customer's bill until I find the `TOTAL_PAYMENT_AMT = TOTAL_DUE`. If found, then mark it as paid, if not found, read the next line until I found the `TOTAL_PAYMENT_AMT <...
This seems to be a task for a Windowed Aggregate Function, a running total? ``` SELECT CUSTOMER_ID, BILL_DATE, TOTAL_DUE, TOTAL_PAYMENT_AMT, SUM(TOTAL_DUE) OVER (PARTITION BY CUSTOMER_ID ORDER BY BILL_DATE ROWS UNBOUNDED PRECEDING) AS due, SUM(TOTAL_PAYMENT_AMT) OVER (PARTITION BY CUST...
This will sum the `TOTAL_DUE` and `TOTAL_PAYMENT_AMT` for each `CUSTOMER_ID`. ``` SELECT CUSTOMER_ID, MIN(BILL_DATE) AS [FIRST_BILL], MAX(BILL_DATE) AS [LAST_BILL], SUM(TOTAL_DUE), SUM(TOTAL_PAYMENT_AMT) FROM TABLE_NAME GROUP BY CUSTOMER_ID ``` Change `TABLE_NAME` for the actual name o...
How to read every row in SQL
[ "", "sql", "teradata", "" ]
In My Table, I Have a Column Which Stores the Date. I am Passing Month Number as an argument to a stored Procedure. I would like to delete all entries of that month from table. Is it Possible....??
I think this is your answer : ``` delete from yourtable where month(YourDatetimeColumn) = 5 -- for example 'may' ``` OR ``` delete from yourtable where datepart(mm,YourDatetimeColumn) = 5 -- for example 'may' ``` Note : replace `5` with your input parameter. This will not consider the `year` part of your date so if...
I am not familiar with SQL server versions, but youre tagged as 2005. If there is issues with `month()` then you can also use; ``` delete from your_table where datepart(month, table_datefield) = @procedure_argument_month ``` But as in other answer, this will delete all fields which month is as you provided, as you d...
Delete Data From Table of Specific Month
[ "", "sql", "sql-server-2005", "" ]
I have two select statements like below ``` SELECT * FROM TABLE1 ``` gives me ``` COLUMNA, COLUMNB, COLUMNC ``` and ``` SELECT * FROM TABLE2 ``` gives me ``` COLUMNA, COLUMNB, COLUMND ``` COLUMNA, COLUMNB are identical(same number of rows and cell values) in those two SELECTs How can I merge these two SELECTs ...
I guess you're looking for something like this. ``` SELECT COLUMNA, COLUMNB, COLUMNC, NULL as COLUMND FROM TABLE1 UNION SELECT COLUMNA, COLUMNB, NULL as COLUMNC, COLUMND FROM TABLE2 ``` or maybe: ``` SELECT COLUMNA, COLUMNB, COLUMNC FROM TABLE1 UNION SELECT COLUMNA, COLUMNB, COLUMND as COLUMNC FROM TABLE2 ``...
This will give you 3 columns, the third being the different valued one: ``` SELECT COLUMNA, COLUMNB, COLUMNC AS [Column3] FROM TABLE1 UNION ALL SELECT COLUMNA, COLUMNB, COLUMND AS [Column3] FROM TABLE2 ```
Merge two SELECT statements which have one or more additional columns
[ "", "sql", "select", "merge", "" ]
I am currently working in sql 2012 visual management studio. I have two tables. Table1 has three columns (ItemNumber as varchar, Quantity as int, and TimeOrdered as datetime). Table2 has 2 columns (ItemNumber as varchar, and Price as float). Please note these item numbers are not the same, the part numbers on table 1 h...
How About This. The case is just to avoid div by Zero errors. ``` SELECT sum( Isnull(tbl.quantity,0) * Isnull(table2.price,0) ) as grandtotal, tbl.PartNumber, Sum(tbl.quanity), case when Isnull(Sum(tbl.quanity),0) = 0 then null else sum(Isnull(tbl.quantity,0) * Isnull(table2.price,0) ) / Sum(tbl.quanity) end a...
**[SQL Fiddle Example](http://sqlfiddle.com/#!6/99171/1)** ``` SELECT SUM(t1.quantity * t2.price) AS 'GrandTotal' ,SUM(t1.quantity) AS 'Quantity' ,t1.itemnumber ,t2.price FROM Table1 t1 JOIN Table2 t2 ON LEFT(t1.itemnumber, 10) = t2.itemnumber WHERE t1.Timeordered BETWEEN '2014-05-05 00:00:00.000' AND...
Select left 10 numbers, left join for a price from second table, and then sum, SQL
[ "", "sql", "select", "sql-server-2012", "sum", "multiplication", "" ]
I have this SQL statement. It works, and I need to add another one condition. I need to sort it by date. **occurence** - is my date row. ``` SELECT dd.caption, COUNT(t.occurence) FROM transaction t INNER JOIN dict_departments dd ON dd.id = t.terminal_id GROUP BY dd.caption ``` How to add this condition: ``` ...
`BETWEEN` requires two arguments, a start point and an end point. If your end point is the current time, you have two options: 1. Using `BETWEEN`: `WHERE t.occurence BETWEEN (CURRENT_DATE() - INTERVAL 1 MONTH) AND NOW()` 2. Using simple comparison operator: `WHERE t.occurence >= (CURRENT_DATE() - INTERVAL 1 MONTH)`
Try this: ``` WHERE t.occurrece BETWEEN current_date() AND dateadd(month,1,current_date()) ``` The function *dateadd* is a SQL SERVER function, but the rest of the clause is standard SQL.
How to add date condition to my query?
[ "", "mysql", "sql", "" ]
I have three tables **Patients** table: which contains the name of my patients, **Controls** table: which represents the UI controls which could be drawn for each illness , and **ControlsValues** table which contains the values of the controls submitted for each Patient Lets have some data **Patients** Table ``` |ID ...
A way to solve the problem is with subqueries ``` select patientId from controlValues where controlId=1 AND value=23 and patientId in ( select patientId from controlValues where controlId=2 and value=true ) ```
try this one ``` select * from controlvalues; +----+----------+-------+-----------+ | id | contrlId | value | patientId | +----+----------+-------+-----------+ | 1 | 1 | 23 | 1 | | 2 | 2 | true | 1 | | 3 | 1 | 26 | 2 | | 4 | ...
How to convert rows to columns and query on them in Mysql
[ "", "mysql", "sql", "" ]
I have a query that does a basic moving average using the `FOLLOWING` / `PRECEDING` syntax of PostgreSQL 9.0. To my horror I discovered our pg server runs on 8.4 and there is no scope to get an upgrade in the near future. I am therefore looking for the simplest way to make a backwards compatible query of the following...
[Postgres 8.4 already has CTEs.](http://www.postgresql.org/docs/8.4/interactive/queries-with.html) I suggest to use that, calculate the daily average in a CTE and then self-join to all days (existing or not) in the past week. Finally, aggregate once more for the weekly average: ``` WITH cte AS ( SELECT closing_da...
``` -- make a subset and rank it on date WITH xxx AS ( SELECT rank() OVER(ORDER BY closing_date) AS rnk , closing_date , price FROM auction_prices WHERE itemname = 'iphone6_16gb' AND price < 1000 ) -- select subset, + aggregate on self-join SELECT ...
SQL workaround to substitute FOLLOWING / PRECEEDING in PostgreSQL 8.4
[ "", "sql", "postgresql", "window-functions", "postgresql-8.4", "moving-average", "" ]
I have developed few SSIS packages in my local system and deployed it in to remote SQL Server. Now my local hard disk crashed. Is there a way to get back the packages that are deployed to SQL Server? Thanks in advance
If you have access to the server itself, you or somebody with the appropriate permissions can login to the server that is running SQL Server Integration Services, from there you can open SSMS, connect to Integration Services, and export any package that has been deployed to that server.
Do something like this: 1) Start integration services project. 2) Right click, Add existing package. 3) Select SSIS Package store. 4) Type the name of the remote server. 5) You can import any package locally from the remote server.
Is it possible to recover the SSIS packages that are deployed in SQL Server?
[ "", "sql", "sql-server", "ssis", "ssis-2012", "" ]
I have a table that looks like this... ``` id city date 1 chicago 5/1 1 chicago 5/2 1 new york 5/1 2 new york 5/3 2 seattle . 3 chicago . 4 seattle . 4 seattle . ``` And I want to create a third column that takes the value of 'city' where the...
``` WITH summary As ( SELECT your_table.*, COUNT(*) OVER (PARTITION BY id) AS id_count, COUNT(*) OVER (PARTITION BY id, city) AS id_city_count FROM your_table ) SELECT summary.*, MAX( CASE WHEN id_city_count * 2 > id_count THEN city ELSE NULL END ) OVER (PARTITION BY id) FROM summ...
This works fine but gives all cities (not unique one) for id which have equal count of cities, ``` with a as( select * from ( select id, city, nb, rank() OVER (PARTITION BY id ORDER BY nb DESC) as rnk from( select id, city, count(city) nb from test group by id, city)as t group by id, city,nb) as tt where rnk ...
How do you create a flag that takes the value of column value depending whether the values make up the majority of the count?
[ "", "sql", "postgresql", "" ]
I have started to learn MySQL. Here is the table `world`: ``` +-------------+-----------+---------+ | name | continent | area | +-------------+-----------+---------+ | Afghanistan | Asia | 652230 | | Albania | Europe | 2831741 | | Algeria | Africa | 28748 | | ... | ... | ...
This is a simple aggegation: ``` SELECT continent, MIN(name) AS name FROM world GROUP BY continent ORDER by continent ```
If it's an Exercise from [SQLZoo](http://sqlzoo.net/wiki/SELECT_within_SELECT_Tutorial), than IMO it should look something like this: ``` select continent, name from world x where name = (select name from world y where x.continent = y.continent order by name a...
MySQL - SELECT the name that comes first alphabetically
[ "", "mysql", "sql", "" ]
I this a query ``` SELECT * FROM user_state_logs WHERE user_state_logs.user_id = 1 AND created_at BETWEEN '2015-05-03 11:06:05' AND '2015-05-13 11:06:05' ``` That returns this ``` user_id state duration 1 call 10 1 call 20 1 wait 30 1 call 10 1 wait 20 ``` ...
Try to do it that way: ``` SELECT user_state_logs.state, user_state_logs.user_id, sum(user_state_logs.duration) as duration FROM user_state_logs WHERE user_state_logs.user_id = 1 AND created_at BETWEEN '2015-05-03 11:06:05' AND '2015-05-13 11:06:05' GROUP BY user_state_logs.state, user_state_logs.user_id ```
You should group by `user_id` and `state`: ``` SELECT user_id, state, sum(duration) WHERE user_state_logs.user_id = 1 AND created_at BETWEEN '2015-05-03 11:06:05' AND '2015-05-13 11:06:05' GROUP BY user_id, state ```
Group by one column and sum the other
[ "", "sql", "postgresql", "" ]
What's the difference or benefit of writing "NOT NULL" in a mysql field creation... For example if I'm creating a table like this... ``` CREATE TABLE IF NOT EXISTS game( id INT(11) NOT NULL AUTO_INCREMENT, name VARCHAR(128) NOT NULL, description VARCHAR(200) NOT NULL, PRIMARY KEY(id) ) ``` Here, id and name always h...
NULL and a blank field are [not the same thing](http://en.wikipedia.org/wiki/Null_%28SQL%29) (unless, under some circumstances, you're a brain-dead DBMS *cough*Oracle*cough*). NULL means unknown or not applicable whereas a blank field means, well, known and blank. It depends entirely on how you want to handle the fie...
First of all, in your situation, you really don't have to put NOT NULL, if you put NOT NULL, when you insert data to your database , if the field used NOT NULL, its mandatory to put values to this field, however ,as mentioned earlier by paxdiablo, that NULL doesn't mean blank field, since blank field can be of a lot of...
When to write NOT NULL when creating a MySQL table column
[ "", "mysql", "sql", "database", "null", "notnull", "" ]
I have a `VARCHAR2` that I want to `Select`, but it's too long. So, I want to `Split` it into multiples lines like this. ``` SELECT 'Veuillez adresser toute la correspondance à : Aktiva2 Service Comptabilité : 30 B rue de la Petite Hollande 59700 Marcq-en-Baroeul Tel : 03 20 20 34 83@RET@IMPORTANT: pour faciliter nos...
you can try something like this ``` declare text varchar2(1000); begin SELECT 'Veuillez adresser toute la correspondance à : Aktiva2 Service Comptabilité : 30 B rue de la Petite Hollande 59700 Marcq-en-Baroeul Tel : 03 20 20 34 83@RET@IMPORTANT: pour faciliter nos échanges comptables, lors de votre paiement, par chèq...
CHR(10) is a new line so `REPLACE(text,'@RET@',chr(10))` cheers
How to Replace a specific char in a Varchar2 on Select
[ "", "sql", "oracle", "replace", "newline", "" ]
Context: I have two tables: markettypewagerlimitgroups (mtwlg) and stakedistributionindicators (sdi). When a mtwlg is created, 2 rows are created in the sdi table which are linked to the mtwlg - each row with the same values bar 2, the id and another field (let's call it column X) which must contain a 0 for one row and...
Oooooh, an excellent job for [`MERGE`](https://docs.oracle.com/database/121/SQLRF/statements_9016.htm). Here's your pseudo code again: ``` For each market type wager limit group ID Check if there are 2 rows with that id in the stake distributions table, 1 where column X = 0 and one where column X = 1 ...
Answer: you don't. There is absolutely no need to loop through anything - you can do it in a single insert. All you need to do is identify the rows that are missing, and then you just need to add them in. Here is an example: ``` drop table t1; drop table t2; drop sequence t2_seq; create table t1 (cola number, ...
Oracle SQL - How can I write an insert statement that is conditional and looped?
[ "", "sql", "oracle", "sql-update", "conditional-statements", "liquibase", "" ]
I'm pretty sure this is an easy question, but I'm having trouble wording it. I need to count the total number of values in one column based on distinct criteria in another column. Example: ``` A CD B ABC C AD D A ``` Would yield: ``` A 3 B 1 C 2 D 2 ```
First, you shouldn't be storing lists of things in a string. But, sometimes one is stuck with this format. In your example, you seem to have a table with all possible values. If so you can use a `join`: ``` select e.col1, count(e2.col2) from example e left join example e2 on charindex(e.col1, e2.col2) > 0 g...
Here is how you can do it: ``` DECLARE @t TABLE ( c1 CHAR(1), c2 VARCHAR(5) ) INSERT INTO @t VALUES ( 'A', 'CD' ), ( 'B', 'ABC' ), ( 'C', 'AD' ), ( 'D', 'A' ) SELECT t.c1 , SUM(count) AS count FROM @t t CROSS APPLY ( SELECT LEN(c2) - LEN(REPLACE(c2, t.c1, '')) AS cou...
Count distinct records in one column with multiple values in another column
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have a table sample table as follows: ``` ID | City -------------- 1 | New York 2 | San Francisco 3 | New York 4 | Los Angeles 5 | Atlanta ``` I would like to select the distinct City AND the TOP ID for each. E.g., conceptually I would like to do the following ``` SELECT TOP 1 ID, DISTINCT City FROM Cities ``...
Try this way: ``` SELECT min(ID), City FROM Cities Group by City ``` `MIN` function is used for choose one of the `ID` from two `New York` cities.
You need to have your city in a `GROUP BY` ``` SELECT MIN(ID), City FROM Cities GROUP BY City ```
SELECT Top 1 ID, DISTINCT Field
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
I have a 'Case' conditional code snippet wherein I am returning two objects. The psuedocode is - ``` case name when 'a' object1 = - SQL Logic - when 'b' object1 = - SQL Logic - when 'c' object2 = - SQL Logic - when 'd' object2 = - SQL Logic - end return object1, object2 ``` As evident, I am returning two objects. Ho...
`return [object1, object2].compact` you can use `compact` method to remove `nil` value of array.
While you can use `compact` to eliminate the `nil` values from your array, I'm not sure why you need this in the first place. Doing ``` case name when 'a' return "SQL statement" when 'b' return "SQL statement" when 'c' return "SQL statement" when 'd' return "SQL statement" end ``` is way more...
Getting an Array from Return statement, deduce a string from that
[ "", "sql", "ruby-on-rails", "arrays", "ruby", "return", "" ]
I have a below sql query in MS-Access 2010 wghich works fine in query design window. Now I want to code it through VBA. ACTUAL QUERY: ``` INSERT INTO MAINRESULT(EXNAME, MASTER_TICKER,MASTER_CUSIP,TL_TICKER,TL_CUSIP,FC_CUSIP,FC_TICKER) SELECT EXC AS MY_EXC, SUM(IIF(MASTER_TICKER <> "NULL", 1, 0)) AS MY_MASTER_TICKER...
finally it beautifully work by using chr$(39) way: ``` Dim MYSTR As String MYSTR = "NULL" 'teststrSQL = "SELECT EXC,FC_CUSIP FROM TESTDATA " & _ "WHERE FC_CUSIP = " & Chr$(39) & MYSTR & Chr$(39) finalstrSQL = "SELECT EXC AS MY_EXC, " & _ "SUM(IIF(MASTER_CUSIP <> " & Chr$(39) & MYSTR & Chr$(39...
You seem to confuse NULL as a value, Null is something that cannot be compared against. You can use two variations. One is, ``` Dim strSQL As String Dim db As Database Set db = CurrentDb strSQL = "INSERT INTO MAINRESULT(EXNAME, MASTER_TICKER,MASTER_CUSIP,TL_TICKER,TL_CUSIP,FC_CUSIP,FC_TICKER) " & _ "SELECT EX...
ms-access VBA long sql query string line split ( with double quote inline) in editor
[ "", "sql", "ms-access", "vba", "" ]
I need a query that returns n number of spaces(" ") that I need to append I a fixed length file. So far I have been able to create ``` select ' ' from dual connect by level < 254 ``` this returns multiple records I need only one record with 253 spaces.
Check the [LPAD](http://docs.oracle.com/cd/B28359_01/olap.111/b28126/dml_functions_2017.htm#OLADM593) function: ``` select LPAD(' ', 254, ' ') from dual connect by level < 254; ``` ***p.s.***: if only one row is required use ``` select LPAD(' ', 254, ' ') from dual; ``` This pre-pends as many spaces `' '` to the St...
I think this will work: ``` select rpad(' ', 254) from dual; ```
SQL Query that returns n spaces
[ "", "sql", "oracle", "" ]
I have a `ParkingLot` model. Parking Lots have a number of available `lots`. Users can then book a parking lot for one or more days. Hence I have a `Booking` model. ``` class ParkingLot has_many :bookings end class Booking belongs_to :parking_lot end ``` # Simplified Usecase **ParkingLot** Given a parking lot ...
There is a simple way using a calendar table. If you don't have one already you should create it, it has multiple usages. ``` select c.calendar_date ,count(b.start_date) -- number of occupied lots from calendar as c left join bookings as b -- need left join to get dates where no lot is already booked on c.cale...
You need GROUP by day since your bookings are daily based. Check the total bookings in a specific day against your total lots, you get available space for that day. Let create a table bookings with following entries: ``` Book_Date Slot_Id Customer_Id 2015-05-14 1 100 2015-05-14 2 ...
Get max bookings count in range
[ "", "sql", "ruby-on-rails", "activerecord", "date-range", "" ]
I couldn't find what is causing this error, when I union headers with the actual data constructed using rollup to write them to a .csv file. ``` CREATE TABLE `products` ( `id` int(11) default NULL, `item` varchar(100) default NULL, `value` int(11) default NULL ) ENGINE=MyISAM ; INSERT INTO `products` VALUES (1,'Mobil...
``` select 'ITEM', 'SUM' union select item, sum(value) from products group by item with rollup ; ``` Result: ``` +---------+------+ | ITEM | SUM | +---------+------+ | ITEM | SUM | | Books | 700 | | Mobiles | 7000 | | NULL | 7700 | +---------+------+ ```
You can not use this way. You need to do either ``` select item, sum(value) from products group by item with rollup; ``` or ``` select item, sum(value) as tot from products group by item union all select 'ITEM',sum(value) from products ``` The result of first query will be as ``` +---------+------------+ | item ...
union and rollup in mysql
[ "", "mysql", "sql", "database", "union", "rollup", "" ]
I have a table having this table done\_by ``` Var_ID| Var_name| Q1_by |Q2_by|Q3_by|Q4_by 1 | abc | me | me |me |you 2 | cba | me | me |you |you 3 | abd | me | you |you |me ``` the result i want to get is get all the total of all the me and you value me=7 you=5 have done cou...
You can do with conditional aggregation like: ``` SELECT SUM(CASE WHEN Q1_by = 'me' THEN 1 ELSE 0 END + CASE WHEN Q2_by = 'me' THEN 1 ELSE 0 END + CASE WHEN Q3_by = 'me' THEN 1 ELSE 0 END + CASE WHEN Q4_by = 'me' THEN 1 ELSE 0 END) AS me , SUM(CASE WHEN Q1_by = 'you' THEN 1 ELS...
Conditional aggregates using "Sum" instead of "Count" is way to go, you can extend it by using dynamic sql, if you don't know the distinct values - ``` --Dynamic SQL Extension to count sum of all distinct values --Extract out distinct values in temporary table SELECT DISTINCT by_val=val INTO #by_tbl FROM (SELECT val=...
SQL COUNT And SUM
[ "", "sql", "count", "sum", "radix", "libreoffice", "" ]
For starters, some background information. I am building a simple recipe book database and I'm trying to build a query that will show me what I can make based on the items in my pantry. The table schemas are as follows: ``` RECIPE(*RecipeID*, RecipeName) RECIPE_INGREDIENT(***RecipeID***, **IngredientID**) INGREDIENT(*...
First off if you can put **only** ingredients into the pantry your `pantry` schema should rather look like this ``` CREATE TABLE pantry ( IngredientID int, FOREIGN KEY (IngredientID) REFERENCES ingredient (IngredientID) ); ``` Now, you can leverage `HAVING` clause to get the desired result ``` SELECT recipename ...
This WILL NOT perform well, but it's possible without changing your schema. I'd recommend though, perhaps you should consider having your PANTRY table id's match the ingredient id's... Essentially, we have to find any time a NULL value is presented when comparing a recipe ingredient to it's pantry item equivalent. Any...
SQL multi-table composite key unique query
[ "", "mysql", "sql", "database", "composite", "" ]
In a project, we have successfully implemented the paging mechanism for SQL Server, but as per our requirement, we are trying to implement the paging mechanism in generic way for Oracle, SQL Server, DB2 & DB400 databases. Is it possible to implement paging in such way? What can be the simplest generic way to implement ...
As far as I know there is no generic functionality to implement the pagining mechanism for the all the database. The syntax to implement the pagination may also change with the database, so it is hard to say that there is a genric functionality to implement it across all the database. You can refer [There are a metho...
What I understand. Try this: ``` WITH MyCte AS ( SELECT row_number() OVER (ORDER BY FieldName) ID, * FROM TableName ) SELECT * FROM MyCte WHERE ID BETWEEN 1 AND 10 ```
How to implement paging mechanism in generic way for SQL standards?
[ "", "sql", "sql-server", "oracle", "db2", "" ]
I am trying to update information in the column Mgrstat to a 3 and would like to mass enter the information. As it is I have to use "=" and enter each AppID individually but I would rather enter several at once. The query below shows my attempt using "in", which didn't work either. I get "Incorrect syntax near the kewo...
This is the SQL you Need: ``` update dev_RPT_Approval set Mgr_Stat=3 where designation in ('10995', '11201', '9523', '9558', '9666', '10069', '10547', '10548', '9702', '10698', '9754', '10161', '10162', '11240', '11241', '9553', '10848', '10667', '9383', '10709', '9696', '10053', '10702') ```
If i'm understanding correctly, and you want all `mgr_stats` to be 3 where the app\_id is in the list provided in your question, then you could do this a few ways: ``` update [Compensation].[dbo].[dev_RPT_Approval] set Mgr_Stat = 3 where app_id in ( '10995', '11201', '9523', '9558', '9666', '10069', '10547', '10548', ...
Update column information
[ "", "sql", "sql-update", "" ]
I have an oracle table with a unique `id` column. When I insert data into the table, I increment the last `id`. ``` insert into my_table vlaues((select max(id) from my_table), 'etc', 'etc'); ``` There can be multiple processes who writes into this table simultaneously. Auto commit is `on`. This table does not have ...
Oracle 12 finally has built-in identity columns. So, if you are using the most recent version of Oracle, you can just use that. Read about it [here](http://oracle-base.com/articles/12c/identity-columns-in-oracle-12cr1.php). In earlier versions, it is best to use a sequence. This guarantees uniqueness, even in a multi-...
You can try this: ``` CREATE TABLE myTable( ID RAW(16) DEFAULT SYS_GUID()) ``` Also it is preferred to use [Sequence](http://www.techonthenet.com/oracle/sequences.php) to get the auto incremented id. If you want to get the sequence id after the insert you can try like this: ``` declare x number; id number; begin x...
Get the unique id the record got when inserting to a database table
[ "", "sql", "oracle", "" ]
I have a 3.5 million rows in table `acs_objects` and I need to retrieve column `creation_date` with year only format and distinct. **My first attempt** : `180~200 Sec (15 Rows Fetched)` ``` SELECT DISTINCT to_char(creation_date,'YYYY') FROM acs_objects ``` **My second attempt** : `35~40 Sec (15 Rows Fetched)` ``` S...
In your second attempt you get distinct dates from the sub-query which you then all convert to a string representation and then you select the distinct ones. That is rather inefficient. Better is it to first extract the distinct years from the `creation_date` in a sub-query and simply cast those to text in the main que...
I think you shouldn't select `distinct` from this huge table. Instead try to generate a short [years sequence](http://www.postgresql.org/docs/9.1/static/functions-srf.html) (say from 1900 to 2100) and select from this sequence only years that exist in `acs_objects` table. Result set will be the same but I think it will...
Fastest way to PostgreSQL Distinct and Format
[ "", "sql", "postgresql", "distinct", "aggregate", "postgresql-performance", "" ]
I have one table like tbl ``` --------------------- id users name --------------------- 1 2,3 acc1 2 4 acc2 3 2,4,1 acc3 4 4,1 acc4 ``` In this table I want to get id and name by users i.e user [2] have which id and name Suppose I pass user [2] then i get result id is 1 and 3 and name acc...
Use the `LIKE` function ``` SELECT id, name FROM yourtable WHERE (user = '2' OR user LIKE '2,%' OR user LIKE '%,2' OR user LIKE '%,2,%') ```
You can split those comma separated values using XML functions and then search in the result : ``` DECLARE @table TABLE(id INT, users VARCHAR(30), name VARCHAR(30)) INSERT INTO @table VALUES (1,'2,3','acc1'), (2,'4','acc2'), (3,'2,4,1','acc3'), (4,'4,1','acc4') SELECT t.id, t.name, ( c1.value('.', '...
Get multiple id on multiple value in string with sql?
[ "", "sql", "sql-server", "" ]
I need to get the data in two parent > child table sets merged/combined into a third parent > child table. The tables look like this: ![Table structure](https://i.stack.imgur.com/6mvyg.png) The only difference in the three sets of tables is that TableC has a `TableType` column to help discern the difference between ...
Here is one way to do this without a cursor or other RBAR type stuff. ``` ALTER TABLE TableC ADD LegacyID INT GO INSERT INTO TableC (TableType, Name, LegacyID) SELECT 'A', Name, ID FROM TableA INSERT TableCChild SELECT C.ID, AC.Name FROM TableAChild AC JOIN TableA A ON A.Id = AC.ID JOIN TableC C ON C.LegacyID = A.ID...
You can use [merge](https://msdn.microsoft.com/en-us/library/bb510625.aspx) as described by Adam Machanic in [Dr. OUTPUT or: How I Learned to Stop Worrying and Love the MERGE](http://sqlblog.com/blogs/adam_machanic/archive/2009/08/24/dr-output-or-how-i-learned-to-stop-worrying-and-love-the-merge.aspx) and in [this](htt...
Merging two parent > child table sets
[ "", "sql", "sql-server", "common-table-expression", "database-cursor", "" ]
I am a bit lost about how to retrieve the Id. I have stored inside a string like `Hi i am interested in sharing apartment or to rent all rooms please text me {PropertyId:43499}` The part I want from this is `43499` How can I achieve this in my Sql-Server. The solution that worked for me, i edited the answer i got f...
Using SQL Query u can get the seperate id: ``` declare @id varchar(max)='Hi i am interested in sharing apartment or to rent all rooms please text me {PropertyId:43499}' select @id=STUFF(@id,LEN(@id),1,'') select @id=SUBSTRING(@id,CHARINDEX(':',@id)+1,LEN(@id)) select @id ``` Output: ``` id 43499 ```
``` CREATE FUNCTION dbo.propertyidextract (@strAlphaNumeric VARCHAR(256)) RETURNS VARCHAR(256) AS BEGIN DECLARE @intAlpha INT SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric) BEGIN WHILE @intAlpha > 0 BEGIN SET @strAlphaNumeric = STUFF(@strAlphaNumeric, @intAlpha, 1, '' ) SET @intAlpha = PATINDEX('%[^0-9]%', @str...
SQL : Retrieve ID stored in a string
[ "", "sql", "sql-server", "" ]
I have following SQL table: **AR\_Customer\_ShipTo** ``` +--------------+------------+-------------------+------------+ | ARDivisionNo | CustomerNo | CustomerName | ShipToCode | +--------------+------------+-------------------+------------+ | 00 | 1234567 | Test Customer | 1 | | ...
`Sample SQL FIDDLE` 1) Use CTE to get max ship code value record based on ARDivisionNo, CustomerNo for each Customers ``` WITH cte AS ( SELECT*, row_number() OVER(PARTITION BY ARDivisionNo, CustomerNo ORDER BY ShipToCode desc) AS [rn] FROM t ) Select * from cte WHERE [rn] = 1 ``` 2) To Delete the record us...
`ROW_NUMBER()` is great for this: ``` ;WITH cte AS (SELECT *,ROW_NUMBER() OVER(PARTITION BY ARDivisionNo,CustomerNo ORDER BY ShipToCode DESC) AS RN FROM AR_Customer_ShipTo ) SELECT * FROM cte WHERE RN = 1 ``` You mention removing the duplicates, if you want to `DELETE` you can simply: ...
Removing duplicate rows (based on values from multiple columns) from SQL table
[ "", "sql", "sql-server", "t-sql", "join", "duplicates", "" ]
In my stored procedure I'm provided with a varchar parameter that looks like the following: ``` '201503' ``` Which obviously indicates the 3rd month of 2015. However, I need to select the previous 12 months in the same format from the given parameter, including the parameter itself. For example, if given `'201503'` ...
Try this: ``` DECLARE @m VARCHAR(10) = '201503' SELECT LEFT(CONVERT(VARCHAR(8), DATEADD(m, -id, @m + '01'), 112), 6) AS result FROM ( VALUES ( 0), ( 1), ( 2), ( 3), ( 4), ( 5), ( 6), ( 7), ( 8), ( 9), ( 10), ( 11) ) m ( id ) ORDER BY result DESC ```
This could be working too. ``` DECLARE @Date VARCHAR(8) = '201503'; SELECT TOP (12) LEFT(CONVERT(varchar, DATEADD(MM, (ROW_NUMBER() OVER(ORDER BY (SELECT 1)) - 1) * -1, CAST(@Date + '01' AS DATETIME2)),112),6) FROM sys.columns ```
Get previous 12 months dates if given a datetime
[ "", "sql", "sql-server", "" ]
I'm inserting data from one table to another table. I just take the last value from first table as ID and need to increment from there, so I have taken `MAX(ID) + 1` and doing increment but I'm getting same values ``` declare @t table (ID INT,VID INT,Sname Varchar(10),Rname Varchar(10)) INSERT INTO @t (ID,VID,Sname,R...
I think, you are looking for something like this. Use `MAX(ID)` of `@t` + `id` for incremented values of `ID` and `ROW_NUMBER()` with `PARTITION BY` to get partitioned values of `VID` ``` INSERT INTO @t (ID,VID,Sname,Rname) Select (select MAX(ID) FROM @t) + id as Id,ROW_NUMBER()OVER(partition by id ORDER BY VID)VID,S...
You should add an additional table, with data that looks like this: ``` ID SName 4601 Car 4062 Bike 4063 Cloth ``` Then you can have that first column just be an autonumber/identity, and let Sql Server handle this. Doing otherwise puts you at risk of race conditions. Your existing table should then look mo...
How to do autoincrement based on last value from another table?
[ "", "sql", "sql-server", "" ]
I have a table which looks something as below ``` state_history +---------------------+-----------+----------------+ + | state_added_time | entity_id | state_id | .... | +---------------------+-----------+----------------+ | | 2015-05-15 13:24:22 | 1 | 1 | | | 2015-05-15 13...
You can also do it using variables: ``` SELECT entity_id, state_added_time, state_id FROM ( SELECT state_added_time, state_id, @row_number:= CASE WHEN @entity = entity_id THEN @row_number+1 ELSE 1 END AS row_number, @entity:=entity_id AS entity...
Are you looking for this? ``` SELECT h.* FROM ( SELECT entity_id, MAX(state_added_time) state_added_time FROM state_history WHERE state_added_time <= '2015-05-15 14:25:00' GROUP BY entity_id ) q JOIN state_history h ON q.entity_id = h.entity_id AND q.state_added_time = h.state_added_time ``` Outp...
MySQL select rows with timestamp closest to but not exceeding the given timestamp
[ "", "mysql", "sql", "" ]
I have a field that is a `longtext` in MySQL. I'm looking for any instances of 'media' that could be in it, +/- ~10 characters of context. There are usually multiple instances in a single rows' field, so I need to see the context. How can I write a query to do this? I can't even think of where to start. So what I'm lo...
In mysql you can create a user define function for this like wordcount. You can get help from this UDF. [mysql count word in sql syntax](https://stackoverflow.com/questions/12156970/mysql-count-word-in-sql-syntax)
[`CREATE FUNCTION`](https://dev.mysql.com/doc/refman/5.0/en/create-procedure.html) of your own. Inside the function you can use the [`WHILE`](https://dev.mysql.com/doc/refman/5.0/en/while.html) statement and general string functions such as [`LOCATE`](https://dev.mysql.com/doc/refman/5.0/en/string-functions.html#functi...
Selecting multiple substrings from a field in MySQL
[ "", "mysql", "sql", "string", "" ]
I have two tables (`User` and `Salary`). I want to do a `left join` from `User` to `Salary`. For each user I want their name and salary. In case they have no salary that field can be left empty. So far a left join is all we need. But I only want one row per user. Due to some defects there can be several salaries for on...
Changed `User` to `Userid` as `User` is a reserved word in SQL ``` SELECT u.Userid, u.Name, MAX(S.Salary) FROM Usertable u LEFT JOIN Salarytable s ON u.Userid = s.userid GROUP BY u.userid, u.name ``` SQL Fiddle: <http://sqlfiddle.com/#!6/ce4a8/1/0>
Try this: ``` select U.User, U.Name, min(S.Salary) from UserTable U left join SalaryTable S on S.User = U.User group by U.User, U.Name ```
Left join without multiple rows from right table
[ "", "sql", "sql-server", "teradata", "" ]
I'm a newbie in mysql programming, and i would create a mysql function ***myFunction*** with a string parametre; this function query ***myTable*** and return a string from the query-result like this example : ``` myTable --------------- |id | value | --------------- | id1 |value1 | | id2 |value2 | | id3 |...
This is a demo of how you can do it, of course you can put all together but I find it cleaner to split the functions. Check the [SQL Fiddle](http://sqlfiddle.com/#!9/dda93/1) **My table** ``` -- the table def create table myTable (id char(3), value char(6)); insert into myTable values( 'id1', 'value1'); insert into ...
Any reason you couldn't just run this kind of query? ``` SELECT GROUP_CONCAT(id ORDER BY FIELD(`value`, 'value2', 'value1', 'value4')) FROM myTable WHERE `value` IN ('value2','value1','value4') ; ``` Edited: Added `value` as first argument to FIELD() function to make it return the ids in the proper order.
Is it possible to create this mysql Function?
[ "", "mysql", "sql", "function", "" ]