Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have a table with a column that contains a few null values. I want to add a `NOT NULL` constraint on that column without updating the existing nulls to a non-null value. I want to keep the existing null values and check for future rows that they contain a not null value for this column. Is this possible? How?
You can add an unvalidated constraint - it will not look at existing rows, but it will be checked for any new or updated rows. ``` ALTER TABLE mytable MODIFY mycolumn NOT NULL NOVALIDATE; ``` Just be aware that you won't be able to update an existing row unless it satisfies the constraint. Also, be aware of the down...
ALTER TABLE table\_name SET column\_name = '0' WHERE column\_name IS NULL; ALTER TABLE table\_name MODIFY COLUMN(column\_name NUMBER CONSTRAINT constraint\_identifier NOT NULL); This is of course assuming that your column is a number but it's the same thing really, you would just change the '0' to a default value tha...
How to add a not null constraint on column containing null values
[ "", "sql", "oracle", "plsql", "oracle11g", "constraints", "" ]
I need to calculate number of spesific days (ex. wednesday & thursday) between two dates. I know about time function and all related ones, but I do not know how to use them in this context. --- The problem solved in two solutions, but it seems I can't choose booth solution. Thank you [Andrius Naruševičius](/users/11...
Method taken and adapted from [here](https://stackoverflow.com/questions/9757919/count-days-between-two-dates-excluding-weekends-mysql-only) ``` @S = start date @E = end date, not inclusive @full_weeks = floor( ( @E-@S ) / 7) @days = (@E-@S) - @full_weeks*7 OR (@E-@S) % 7 SELECT @full_week...
An alternative way of doing it with a SELECT statement:- ``` SELECT DAYNAME(DATE_ADD(@StartDate, INTERVAL (Units.i + Tens.i * 10 + Hundreds.i * 100) DAY)) AS aDayOfWeek, COUNT(*) FROM (SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 ...
Count specific days of week between two dates
[ "", "mysql", "sql", "" ]
There is a table: ``` +---------+--------+---------------------+----------+ | user_id | marker | date | trans_id | +---------+--------+---------------------+----------+ | 6 | M | 2013-08-27 11:45:24 | 5 | | 6 | MA | 2013-08-27 11:45:42 | 6 | | 6 | A | 2013-0...
This will give you the latest record for every `user_id` ``` SELECT a.* FROM tableName a INNER JOIN ( SELECT user_id , MAX(date) date FROM tableName GROUP BY user_ID ) b ON a.user_id = b.user_id AND a.date = b.date -- WHERE a.user...
This will give you the latest record for every `user_id` ``` SELECT a.user_id, b.marker, MAX(a.date) AS maxdate, b.trans_id FROM TableName a JOIN TableName b ON b.date = a.date AND a.user_id = b.user_id GROUP BY a.user_id ORDER BY a.date DESC; ``` `MAX()` is an aggregate function, just like `SUM()` and `COU...
How to retrieve row data by MAX(date)?
[ "", "mysql", "sql", "date", "select", "" ]
I am writing the following query that I want to display car registration, car group name, model name, cost and the number of bookings for each car. I have to use an explicit cursor and I have to use an implicit cursor to calculate the number of bookings that belong to each car. My query is as follows: ``` SET SER...
This did the trick for me. I moved my implicit SELECT statement into the cursor for loop and added a WHERE clause saying WHERE registration = v\_car.registration; ``` SET SERVEROUTPUT ON FORMAT WRAP SIZE 12000 Declare v_count number; cursor carcur IS SELECT * FROM i_car; v_car carcur%ROWTYPE; B...
The error you are facing is because you are trying to assign multiple values to a single valued variable. Your query is returning multiple values primarily because you are using a `group by`. What a `group by` does is, in your case, finds the total count of values in column `registration` for every distinct value in t...
PL/SQL Group By - ORA-01422: exact fetch returns more than requested number of rows
[ "", "sql", "oracle", "plsql", "oracle11g", "oracle10g", "" ]
I have a table as shown ``` Amount Debit Credit Description ------ ----- ------ ----------- 275.00 275.00 Payroll 500.00 500.00 Payroll 288.00 288.00 Payroll 500.00 500.00 Payroll 600.00 600.00 Payr...
Like this ``` select amount,debit,credit,Description from tablename where amount = 500 and amount = 600 group by amount,debit,credit,description; ```
try it using `EXISTS`. ``` SELECT a.* FROM tableName a WHERE EXISTS ( SELECT 1 FROM tableName b WHERE a.Amount = b.Amount GROUP BY Amount HAVING COUNT(AMOUNT) = 2 AND COUNT(Debit) = 1 AND COUNT(C...
Oracle SQL Query for displaying values?
[ "", "sql", "oracle", "" ]
I need a query which retrieve data from 1 table based on 3 table: ## Table1 UID | GID 1 | 0 2 | 1 3 | 1 4 | 2 ## Table2 CID | UID 1 | 2 2 | 3 3 | 4 4 | 5 ## Table3 LID | CID 1 | 2 2 | 2 3 | 3 4 | 1 Now I need to retrieve data from table3 where table1.GID=1 and table2.UID=table1.UID and ta...
You can use this: ``` SELECT Table3.* FROM Table1 LEFT JOIN (Table2, Table3) ON (table1.GID=1 and table2.UID=table1.UID and table3.CID=table2.CID) ```
Unless I made a typo ``` SELECT t3.* FROM t3 LEFT JOIN t2 ON t3.cid = t2.cid LEFT JOIN t1 ON t2.uid = t1.uid WHERE t1.gid = 1; ``` With tables: ``` CREATE TABLE IF NOT EXISTS `t1` ( `uid` int(11) NOT NULL AUTO_INCREMENT, `gid` int(11) NOT NULL, PRIMARY KEY (`uid`) ) ENGINE=...
MySQL- how to get data from 3 table?
[ "", "mysql", "sql", "" ]
I have a Google fusion table with 3 row layouts as shown below: ![enter image description here](https://i.stack.imgur.com/RCEWN.png) We can query the fusion table as, ``` var query = new google.visualization.Query("https://www.google.com/fusiontables/gvizdata?tq=select * from *******************"); ``` which select...
API queries apply to the actual table data. The row layout tabs are just different views onto that data. You can get the actual query being executed for a tab with Tools > Publish; the HTML/JavaScript contains the FusionTablesLayer request. I would recommend using the regular [Fusion Tables APi](https://developers.goo...
A couple of things: 1. Querying Fusion Tables with SQL is [deprecated](https://groups.google.com/forum/?hl=en-US&fromgroups=#!topic/fusion-tables-api-announce/_U1U4x2yD9g). Please see the [porting guide](https://developers.google.com/fusiontables/docs/v1/migration_guide). 2. Check out the [Working With Rows](https://d...
querying google fusion table
[ "", "sql", "select", "google-visualization", "google-fusion-tables", "" ]
Me and my workmate would like to fetch data from squid server via access.log to mysql server on another Debian server. We've found sort of guide to that kind of things on the internet and made a script that will put data in mysql from string in access.log file. but this doesnt seems to be working, something might be w...
If your log file looks like below, ``` "apple","red",1230,"Newton","Physics","Da vinci code" "iphone","black",44500,"Jobs","Mobiles","telephone booth" "shoe","brown",9900,"Elizabeth","Fashion","shoe shop" ``` My table structure looks like below, ``` table_name = t1 columns = topic, price, department ``` then I woul...
I created the table needed in mysql. Then created the fields required. Then I used the file import and pointed to where my log file was. Otherwise known as: File to import Where the Format of imported file was CSV using LOAD DATA I was able to specify the file delimiter as well as the fields. The log file with about...
insert data strings from log file to mysql database
[ "", "mysql", "sql", "unix", "logging", "debian", "" ]
I have this sample table: ``` ColA ColB ColC CBCP 25 popx ABC1 10 ppp1 ABC1 25 ppxx CBCP 30 xm2x ``` from there I would like to get these columns ``` ColA ColB ColC ABC1 25 ppxx CBCP 30 xm2x ``` what I would want is to get the row with max ColB.. But I am getting an error...
``` SELECT CaseNo,Date,Remarks, (SELECT max(cast(Date as datetime)) FROM tblCaseDev subc WHERE subc.CaseNo=c.CaseNo Group by c.CaseNo) AS MaxEntryDate FROM tblCaseDev c order by CaseNo ```
You want to use the `row_number()` window function: ``` select CaseNo, "Date", Remarks from (select t.*, row_number() over (partition by caseno order by date desc) as seqnum from tblCaseDev t where date > getdate() ) t where seqnum = 1; ``` EDIT: You can do this the old fashioned way if you don't ha...
How can I get the value of non-aggregated column with an aggregated column?
[ "", "sql", "sql-server", "" ]
I have three tables. * tax\_master * item\_master * item\_tax The values in it are like this. ``` *tax_master* tax_id tax_name tax_value -------------------------- 1 Vat 5 2 LBT 8 *item_master* item_id Prise --------------- 1 30 2 100 *item_tax* item_tax_id item_id ta...
``` select item_id, price, (min(case when tax_name = 'VAT' then tax end)) vat, (min(case when tax_name = 'LBT' then tax end)) lbt, coalesce(min(case when tax_name = 'VAT' then tax end),0) + coalesce(min(case when tax_name = 'LBT' then tax end),0) + price total from (select a....
The following statement should return the data the way you want it: ``` SELECT DISTINCT item_master.item_id, (SELECT tax_master.tax_value * item_master.prise / 100 FROM item_tax, tax_master WHERE item_tax.item_id = item_master.item_id and tax_master.tax_id = item_tax.tax_...
How to select column in table by creating row in another table in MySQL
[ "", "mysql", "sql", "" ]
I am trying to wrap a few actions in a transaction so I can determine if I should delete a table in the last step. Here's what I have so far: ``` --select the DB use DB1 --if the table exists, we want to delete it first IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES ...
If you want to perform multiple actions based on the number of rows that a single statement affected, then you need to capture that value into your own variable immediately: ``` DECLARE @rc int SELECT field1 ,field2 ,field3 INTO dbo.vv FROM vvr A WHERE A.field1 <> 'GEN' AND A.field2 <> 'NO DATA' AND ...
`PRINT 'ROW1:' + CAST(@@ROWCOUNT as varchar(11))` This line resets the @@ROWCOUNT. If you inserted 50 records into the table, the print statement would return 50, but then when you reference @@ROWCOUNT in your next line, the value will return 0, so therefore the table will never exist since you perform a rollback oper...
Commit tran on @@ROWCOUNT
[ "", "sql", "transactions", "" ]
I am trying to bring the last 5 rows of the `Order` table based on `OrderDate` with the column name `firstname` from `Customer` table. The below query displays all the values from the `Order` table instead of last 5 rows. ``` SELECT A.[FirstName], B.[OrderId], B.[OrderDate], B.[TotalAmount], B.[OrderStatusId] FR...
If you want to get the last 5 rows of `Order` table, why do you apply `TOP` to `Customer` table? ``` SELECT TOP 5 A.[FirstName],B.[OrderId],B.[OrderDate],B.[TotalAmount],B.[OrderStatusId] FROM [schema].[Order] B LEFT JOIN [schema].[Customer] A ON A.[CustomerId]=B.[CustomerId] WHERE B.[CustomerId]=1 ORDER BY B.[Or...
``` ;WITH MyCTE AS ( SELECT A.[FirstName], B.[OrderId], B.[OrderDate], B.[TotalAmount], B.[OrderStatusId], ROWNUMBER() OVER (ORDER BY B.[OrderDate] DESC) AS RowNum FROM [schema].[Order] B OUTER APPLY ( SE...
Select last 5 rows in join query SQL Server 2008
[ "", "sql", "select", "join", "" ]
I have the following SQL query: ``` SELECT t.trans_id, t.business_process_id, tsp.status, tsp.timestamp FROM tran_stat_p tsp, tran t WHERE t.trans_id = tsp.trans_id AND tsp.timestamp BETWEEN '1-jan-2008' AND SYSDATE AND t.business_process_id = 'ABC01' ``` It outputs data like this: `trans_ID` `busin...
You can use `LEAD` to retrieve the next timestamp value and calculated the time left in every status (F, W and S) and `TRUNC` to calculated days between as an integer : ``` SELECT t."trans_ID", t."business_process_id", tsp."status", tsp."timestamp", LEAD("timestamp", 1) OVER ( PARTITION BY ts...
The actual query would use [`LAG`](http://docs.oracle.com/cd/B28359_01/server.111/b28286/functions075.htm), which will give you a value from a prior row. Your status codes won't sort as `F` -> `W` -> `S` -> `P`, which is why the query below has the big `CASE` statement for the `LAG` function's `ORDER BY` - it translat...
Date difference between rows
[ "", "sql", "oracle", "date-difference", "" ]
Here is the problematic SQL query and the results that it yields: ![enter image description here](https://i.stack.imgur.com/uJhcU.png) What I need, however, is to have the data formatted in the following way: ``` Emp No Sign In Sign out 022195 2013-01-29 09:18:00 2013-01-29 1...
You can use the date() function to aggregate the day in MySQL. The trick is to use it in the group by clause. ``` select name, min(date) as Sign_In, max(date) as Sign_Out, from text_based_attendance group by date(date), name order by name ``` This will give a result grouping the employees by their names and t...
you don't have to do any subqueries for that, you can do it with basic [aggregate functions](http://www.postgresql.org/docs/9.2/static/functions-aggregate.html) over the table and group by name ``` select t.name as EmpNo, min(t.date) as SignIn, max(t.date) as SignOut from text_based_attendance as t grou...
How to query data with the GROUP BY keyword within a date
[ "", "sql", "oracle", "postgresql", "" ]
Are there any performance difference in querying a database for some character column starting with something and ending with something? ``` SELECT * FROM table WHERE column like '%something' SELECT * FROM table WHERE column like 'something%' ``` Any downsides to choose one approach instead of another? Disregarding t...
The SQL optimizer will look for an index on column in the second example, and will narrow it down to the records beginning with the characters before the wildcard. In the first example, it can't narrow it down, so you'll like scan either the index or table (depending on index structure). Which SQL product are you usin...
Instead of creating a new column and index to deal with the ``` SELECT * FROM table WHERE column like '%something' ``` query, you could create an index ``` CREATE INDEX rev_col_idx ON table (reverse(column) text_pattern_ops); ``` and then rewrite the above query as ``` SELECT * FROM table WHERE reverse(column) lik...
Performance of querying for a string that starts and ends with something
[ "", "sql", "performance", "algorithm", "" ]
Let's say I have three tables - Orders, OrderDetails, and ProductType - and the Orders table includes a column for Customer. What I need to do is write a query that will show me a list of customers and how many orders each customer has placed, as well as displaying and grouping by another column, which is a boolean bas...
This query should work ``` SELECT Customer, COUNT(Customer) AS NumOrders, CASE WHEN (ProductType.Type = 'Phone') THEN 'Yes' ELSE 'No' END AS IncludesPhone FROM Orders INNER JOIN OrderDetails INNER JOIN ProductType GROUP BY Customer, CASE WHEN (ProductType.Type = 'Phone') THEN 'Yes' ELSE 'No' END Order By Includes...
Change the group by to ``` GROUP BY Customer, CASE WHEN (ProductType.Type = 'Phone') THEN 'Yes' ELSE 'No' END ```
Group By not functioning as desired
[ "", "sql", "sql-server-2008", "group-by", "" ]
Will there be any other ways instead of writing the same criteria multiple times? ``` SELECT * FROM tblEmployees E WHERE E.CurrentAddress LIKE '%dan%' OR E.Email1 LIKE '%dan%' OR E.Email2 LIKE '%dan%' OR E.LatinName LIKE '%dan%' ```
There are other ways, but yours is probably the most efficient already. You could always do something like: ``` SELECT * FROM tblEmployees WHERE CurrentAddress + Email1 + Email2 + LatinName LIKE '%dan%' ``` If some of the columns are `NULL`, you could use `ISNULL([field], '')`. However, as @MitchWheat pointed out, i...
If none of the values are `NULL`, you could do: ``` SELECT * FROM tblEmployees E WHERE concat(E.CurrentAddress, ' ', E.email1, ' ', E.email2, ' ', E.LatinName) LIKE '%dan%'; ```
How to select rows with the same criteria in multiple columns?
[ "", "sql", "" ]
I am trying to write a query to Identify my subscribers who have abandoned a shopping cart in the last day but also I need a calculated field that represents weather or not they have received and incentive in the last 7 days. I have the following tables AbandonCart\_Subscribers Sendlog The first part of the query is...
Kishore is right in saying the main problem is that it should be <=7, not >=7. However, there is another problem. As it stands, you could get multiple results. You don't want to do a left join on SendLog in case the same email address is in there more than once. Instead you should be getting a unique result from that ...
should it not be less than 7 instead of greater than 7? select a.\*, CASE WHEN DATEDIFF(D,s.SENDDATE,GETDATE()) <= 7 AND CampaignID is not null THEN 1 ELSE 0 END As IncentiveRecieved from AbandonCart\_Subscribers a left join SendLog s on a.EmailAddress = s.EmailAddress --and s.CampaignID IS NULL where DATEDIFF(day,a.D...
Join Table on one record but calculate field based on other rows in the join
[ "", "sql", "join", "" ]
I try to use 3 local variable in a PL/SQL function, but when a run log shows that 2 are invalid Following is the code: ``` create or replace function valor_parcela(p_num_venda number, p_juros number) return number is tmp_valor_parcela number(7,2); f_num_parcelas number(7,2); f_valor number(7,2); begin Se...
1. As it already has been said by @REW, variable's name in the `into clause` of a query should not be preceded by a colon. ``` into f_num_parcela -- without colon ``` and ``` into f_valor ``` 2. Those two queries could be simply replaced by one: ``` Select num_parcelas , valor_to...
Try this too, you'll get the value for num\_parcelas and valor\_total from a single query. ``` CREATE OR REPLACE FUNCTION valor_parcela( p_num_venda NUMBER, p_juros NUMBER) RETURN NUMBER IS tmp_valor_parcela NUMBER(7,2); f_num_parcelas NUMBER(7,2); f_valor NUM...
how to use 3 variables in PL/SQL function
[ "", "sql", "oracle", "plsql", "oracle-sqldeveloper", "" ]
I need help... For example i have this table.. ``` acc_num open close activate date ------- ---- ----- -------- ---------- 200 1 0 0 2013/01/01 200 0 1 0 2013/01/12 200 0 0 1 2013/01/10 ``` The output should be: ``` acc_num open_d...
Try this (assuming there is only one row per state per acc\_num): ``` select acc_num, max(decode(open,1,date)) open_date, max(decode(close,1,date)) close_date, max(decode(activate,1,date)) activate_date from table group by acc_num ```
You can use a series of `CASE` statements to create the needed columns. here is a sample [fiddle](http://sqlfiddle.com/#!4/e5a88/5) ``` SELECT t1.acc_num ,MAX(CASE WHEN t1.open = 1 THEN t1.date ELSE TO_DATE('1901-01-01', 'YYYY-DD-MM') END) AS Open_Date ,MAX(CASE WHEN t1.activate = 1 THEN t1.date ELSE...
oracle 11g SQL :help for a complicated sql query
[ "", "sql", "oracle11g", "oracle10g", "" ]
I have a table called `Issues` that I need to get data from. I am joining the Issues table with another table called `IssueActivities`. So for each instance of an IssueID, there could be 1 to many IssueActivities. In the `IssueActivities` table is a field called `Notes` and it is of datatype `text`. I'm trying to selec...
You should find the rows you want to exclude, then eliminate them in the where clause. This example uses `APPLY` to find any IssueActivity row with "Pending DR" or "Pending E" in it for each Issues row. Here is a [SQLFiddle](http://sqlfiddle.com/#!3/acfcd/1) ``` SELECT i.IssueID FROM Issues i OUTER APPLY( SELECT TOP...
If I understand correctly, you need to first select what you want to ignore: ``` SELECT DISTINCT IssueID FROM IssuesActivities WHERE PATINDEX('%Pending DR%', ia.Notes) > 0 OR PATINDEX('%Pending E%', ia.Notes) > 0 ``` Then you can ignore it: ``` SELECT DISTINCT i.IssueID FROM Issues i LEFT JOIN (SELECT DISTINCT Issue...
Select DISTINCT field when using PATINDEX
[ "", "sql", "sql-server-2008", "t-sql", "" ]
I made this procedure.. ``` ALTER PROCEDURE [dbo].[MyProcedure] @pSelect nvarchar AS BEGIN SET NOCOUNT ON; select @pSelect from tabel1 END ``` I want to pass a select query like from c# code to this stored procedure ``` MyProcedure("column1,column2"); ``` How could I do this because stored proc...
You'll have to use dynamic sql inside the stored procedure. ``` ALTER PROCEDURE [dbo].[MyProcedure] @pSelect nvarchar(max) AS BEGIN SET NOCOUNT ON; DECLARE @SQL nvarchar(max) SET @SQL = 'select ' + @pSelect + ' from tabel1'; EXEC (@SQL) END ``` Here's a script to test the above stored procedure...
You can use dynamic SQL for the purpose, but it is not recommended. (More info here - [The Curse and Blessings of Dynamic SQL](http://www.sommarskog.se/dynamic_sql.html)) ``` create procedure MyProcedure @pSelect nvarchar AS begin declare @sql nvarchar(4000); set @sql='select ['+ @pSelect +'] from Table_1'; ...
i want to pass a select query in a stored procedure as an argumnet
[ "", "sql", "sql-server", "" ]
I need to convert data of a table and do some manipulation. One of the column datatypes is `Varchar`, but it stores **decimal** numbers. I am struggling to convert the `varchar` into `decimal`. I have tried `CAST( @TempPercent1 AS DECIMAL(28, 16))` Problem is that data also has some values in exponential notation, f...
You may try following, but you may loose accuracy: ``` select cast(cast('1.61022e-016' AS float) as DECIMAL(28, 16)) ```
You could just do ``` CAST(CAST(value AS float) AS decimal(36, 20)) ``` **but...** If you do that, the cast-to-float will also change all values that have no E inside - because floats can only be as exact as the machine-epsilon ... You can mitigate that, by only casting to float if the number contains an E (+/-). ...
SQL Server: Convert varchar to decimal (with considering exponential notation as well)
[ "", "sql", "sql-server", "decimal", "type-conversion", "" ]
I'm trying to update a stored procedure that determines a response time from when a ticket is received. In the table I have the timestamp when the ticket was received (ref\_dttm TIMESTAMP WITHOUT TIME ZONE) and the timestamp when the ticket was first responded to (first\_action\_dttm TIMESTAMP WITHOUT TIME ZONE). When ...
I like to store important business data in tables. Queries like this ``` select min(cal_date), max(cal_date), sum(hours_open) total_time_open, sum(hours_closed) total_time_closed from daily_hours_open_and_closed where cal_date between '2013-08-28' and '2013-09-03'; ``` are easy to understand, ...
You can count weekends by something like this query: ``` select *, (extract(week from ref_dttm) - extract(week from first_action_dttm)) * 2 - case extract(dow from first_action_dttm) when 0 then 1 else 0 end + case extract(dow from ref_dttm) when 0 then 2 when 6 then 1 else 0 end from t_tickets ``` tr...
Postgres function to determine number of weekends in an interval
[ "", "sql", "postgresql", "" ]
table1: ``` Id Customer No_ 7044900804 Z0172132 7044900804 Z0194585 7044907735 Z0172222 7044907735 Z0172222 7044910337 Z0172216 7044911903 Z0117392 ``` I would like to get only the values with the **same Id AND different Customer No\_** from table1. ``` Id Customer No_ 7044900804 Z0172132 70...
Try this ``` SELECT * FROM table1 WHERE Id IN ( SELECT Id FROM table1 GROUP BY Id HAVING COUNT(DISTINCT [Customer No_]) > 1 ) ``` [**SQL FIDDLE DEMO**](http://www.sqlfiddle.com/#!3/e92fe/1)
I think the easiest way is just to join the table together twice, where the IDs are joined, but the Customer No\_s do not match. ``` select t1.id, t1.[customer No_], t2.[customer No_] from table1 t1 inner join table1 t2 on t1.id = t2.id and t1.[customer No_] != t2.[customer No_] ```
T-SQL - query filtering
[ "", "sql", "sql-server", "t-sql", "" ]
I wrote a query to obtain First of month, ``` SELECT DATEADD(DAY, -(DATEPART(DAY,GETDATE())-1), GETDATE()) as First_Of_Month; ``` for which i do get the appropriate output, but my time stamp shows the current time. Here's what I am doing in the query, hope i make sense. using `datepart` i calculated the no. of days...
**For SQL Server 2012** (thanks adrift and i-one) ``` DECLARE @now DATETIME = CURRENT_TIMESTAMP; SELECT DATEADD(DAY, 1, EOMONTH(@now, -1)); -- or SELECT DATEFROMPARTS(YEAR(@now), MONTH(@now), 1); ``` **For SQL Server 2008+** ``` DECLARE @now DATETIME = CURRENT_TIMESTAMP; -- This shorthand works: SELECT CONVERT(...
``` SELECT convert(varchar(10),DATEADD(DAY, - (DATEPART(DAY,GETDATE())-1), GETDATE()),120)+' 00:00:00' as First_Of_Month; ```
How to get 00:00:00 in datetime, for First of Month?
[ "", "sql", "sql-server", "datetime", "sql-server-2008-r2", "" ]
anybody an idea why this gives me an error 102, wrong syntax? ``` declare @i int=20 while @i<=50 begin try if convert(char,getdate(),@i) is not null begin select convert(char,getdate(),@i) end set @i=@i+1 end try begin catch set @i=@i+1 ...
Judging by your indentation, I believe you wanted `BEGIN TRY` for line 5.
Remove the semi colon after end catch, and add begin before the try. Something like ``` declare @i int=20 while @i<=50 begin begin try if convert(char,getdate(),@i) is not null begin select convert(char,getdate(),@i) end set @i=@i+1 end try begin ...
Why does this code sequence give me an error 102
[ "", "sql", "sql-server-2008", "t-sql", "" ]
I have an application where I find a Sum() of a database column for a set of records and later use that sum in a separate query, similar to the following (made up tables, but the idea is the same): ``` SELECT Sum(cost) INTO v_cost_total FROM materials WHERE material_id >=0 AND material_id <= 10; [a little bit of int...
The syntax `select . . . for update` locks records in a table to prepare for an update. When you do an aggregation, the result set no longer refers to the original rows. In other words, there are no records in the database to update. There is just a temporary result set.
You might try something like: ``` <<LOCAL>> declare material_id materials.material_id%Type; cost materials.cost%Type; total_cost materials.cost%Type; begin select material_id, cost, sum(cost) over () total_cost into local.material_id, local.cost, local.total_cost...
Why can't I use SELECT ... FOR UPDATE with aggregate functions?
[ "", "sql", "database", "oracle", "aggregate-functions", "select-for-update", "" ]
I have the following tables: ![Table 1](https://i.stack.imgur.com/4abuG.jpg) and: ![Table 2](https://i.stack.imgur.com/ywRxY.jpg) And I formulated this query: ``` Update Table 1 SET DY_H_ID = ( SELECT MAX(ID) FROM Table 2 WHERE H_DateTime <= DY_Date AND H_IDX = DY_IDX AND H_HA_ID = 7 ...
Try this: ``` UPDATE TABLE 1 SET DY_H_ID = (SELECT Max(ID) FROM TABLE 2 WHERE H_DATETIME <= DY_DATE AND H_IDX = DY_IDX AND H_HA_ID = 7 AND H_HSA_ID = 19 AND H_DESCRIPTION...
Just add another condition to where: ``` Update Table 1 SET DY_H_ID = ( SELECT MAX(ID) FROM Table 2 WHERE H_DateTime <= DY_Date AND H_IDX = DY_IDX AND H_HA_ID = 7 AND H_HSA_ID = 19 AND H_Description LIKE 'Diary item added for :%' ) WHERE DY_H_ID IS NULL AND DY_IDX IS NOT NULL and ...
Updating only ID's with the latest date SQL (2 of 6)
[ "", "sql", "sql-server", "t-sql", "" ]
i have 3 tables 1)main\_table 2)Flag\_table 3)emp\_flagdetails main\_table structure ``` emp_no hod_no emp_name flgType E51397 E44417 Asha V E42342 E44417 Shaikh Faiz Ahmed E06636 E44417 Balu K U ``` in the above table i kept flgtype column blank to update later now i have Flag\_table str...
Query: **[SQLFIDDLEExample](http://sqlfiddle.com/#!6/fdb50/1)** ``` UPDATE m SET m.flgType = f.FlagCategory FROM main_table m JOIN emp_flagdetails fd ON fd.ecode = m.emp_no JOIN flag_table f ON f.FlagType = fd.flag; ```
``` update main_table m, (select a.emp_no, b.flagcategory from emp_flagdetails a, flag_table b where a.flag = b.flagtype) s set m.flgtype = s.flagcategory where m.emp_no = s.emp_no ```
complex sql query to update main table
[ "", "sql", "sql-server", "sql-update", "join", "" ]
I want to know if a date (Year-Month-Day) is between a day of the month (Month-Day). For example, I want to know if 'April 2, 2013' is between 'April 2' and 'April 19'. I can easily do this of the range has a year value. Howver, without a year, I need ideas how to do this. Some examples of what I'm trying to achieve...
You can make use of `DATE_FORMAT()`. **Example** ``` SELECT * FROM table WHERE DATE_FORMAT(date,'%m-%d') BETWEEN '04-01' AND '04-19' ``` **Edit** ``` SELECT * FROM table WHERE STR_TO_DATE(date, '%m-%d') BETWEEN '04-01' AND '04-19' ```
Following is work with oracle ``` select * from table_name where to_char(date_column, 'MM-DD') BETWEEN '08-01' AND '08-14' ```
Query to check if date is between two month-day values
[ "", "mysql", "sql", "date", "" ]
I have two tables like this: ``` Table1 ________ StudentNumbers ExamType 1234 1 2343 2 3345 5 3454 1 5465 2 ... Table2 ________ StudentNumbers ExamType ExamDate School Area 1234 1 0825 warren ny 1234 1 0829 north nj 123...
When using `max()` or another aggregate function, the other fields in the result set need to be grouped. ``` Select t2.StudentNumbers, t2.ExamType, max(t2.ExamDate), t2.School, t2.Area from Table2 as t2 Join Table1 as t1 on t1.StudentNumbers = t2.StudentNumbers where t2.ExamType = 1 group by t2.StudentNumbers, t2.Ex...
You need to use either `GROUP BY` or change the aggregate to a window function (eg. `MAX(t2.ExamDate) over (partition by t2.StudentNumbers, t2.ExamType)`. BTW, as mentioned in some of the comments, considering the data in the first table is included in the second , the whole idea of the `JOIN` is not really useful.
Sql script to get values for two tables combined
[ "", "sql", "" ]
**UPDATE** I know with variable $id the ID of data in table\_1. I have two same columns in table\_1 and table\_2 (with same content). I want to select and show column in table\_2 (result). **TABLE 1** ``` | ID | color | ----------------------------------- 1 | data1 | ...
``` Select t2.*, t1.color from t2 inner join t1 on t1.color = t2.data and t1.id = '$id' ```
A simple join will handle this. ``` select t2.result from table1 t1 join table2 t2 on t1.color = t2.flower where t1.id = 5 ```
MYSQL select in different table with condition
[ "", "mysql", "sql", "select", "" ]
I have a column of type bigint (ProductSerial) in my table. I need to filter the table by the Product serial using like operator. But I found that, like operator can't be used for integer type. Is there any other method for this (I don't want to use the `=` operator).
If you must use `LIKE`, you can cast your number to `char`/`varchar`, and perform the `LIKE` on the result. This is quite inefficient, but since `LIKE` has a high potential of killing indexes anyway, it may work in your scenario: ``` ... AND CAST(phone AS VARCHAR(9)) LIKE '%0203' ``` If you are looking to use `LIKE` ...
Although I'm a bit late to the party, I'd like to add the method I'm using to match the first N given numbers (in the example, 123) in any numeric-type column: ``` SELECT * FROM MyTable WHERE MyColumn / POWER(10, LEN(MyColumn) - LEN(123)) = 123 ``` The technique is similar to @dasblinkenlight's one, but it works rega...
Like operator for integer
[ "", "sql", "sql-like", "" ]
I am doing quite a large query to a database and for some reason it is returning many results that do not match any of my search terms. It also seems to duplicate my results so I get the same SQL item 16 times. Any ideas why? ``` SELECT a.* FROM j20e8_datsogallery AS a, j20e8_datsogallery_tags AS t WHERE (a.id L...
I'd make sure you qualify your join. Otherwise you'll end up with a full join, or worse, a Cartesian product from a cross join. Something along these lines: ``` SELECT a.* FROM j20e8_datsogallery AS a JOIN j20e8_datsogallery_tags AS t ON a.ID = t.GalleryID WHERE ... ORDER BY a.id DESC LIMIT 0, 16 ``` Also, consider u...
It's bringing back multiples because: ``` SELECT a.* FROM j20e8_datsogallery AS a, j20e8_datsogallery_tags AS t ``` brings back ***every*** combination of records from the two tables on it's own. So `bear` in one table joins to every record in the other table. You need to specify a relationship between the tables, p...
SQL Specific Statement Query
[ "", "mysql", "sql", "" ]
in my table i have a feild **user\_ids**. the user\_ids feilds containeing the values like **12,45,78,95,21,78,98** what i need is i need an **mysql** query that search for a specific id(for ex:45) in the feild. i used **like** operator but its not working as i expected. for ex: when i search for **5** its return tru...
This also works: ``` select * from FRIENDSLIST where find_in_set( $ID, USERS_ID ) <> 0 ```
Try ``` Where ',' + MyField + ',' Like '%,' + MySearchString + ',%' ``` The problem is that you're thinking of it as IDs, but it's just a string. So when you search for '5' in '12,45,78,95,21,78,98' it finds it in the 5 of the 45. If you surround with commas then it searches for ',45,' in ',12,45,78,95,21,78,98,' and...
how to search for an id from a group of id using mysql?
[ "", "mysql", "sql", "" ]
I would like to know how many rows would be returned without rownum condition in a given query: ``` SELECT columns , [number of rows before applying rownum] AS numberofrows FROM tables WHERE conditions AND rownum < 100 ``` Is it possible without using a subquery?
You can use the analytic version of `COUNT()` in a nested query, e.g.: ``` SELECT * FROM ( SELECT table_name, COUNT(*) OVER() AS numberofrows FROM all_tables WHERE owner = 'SYS' ORDER BY table_name ) WHERE rownum < 10; ``` You need to nest it anyway to apply an order-by before the `rownum` filter to get c...
You need to run two queries. First to find the size of set and second with data. `select count(*) from tables where conditions;` then the second one. Note that before you should order your set to have, and wrap it to another select `select * from (select columns from tables where conditions order by columns) rownum...
Oracle - calculate number of rows before some condition is applied
[ "", "sql", "oracle", "" ]
I would like to create a table that represents the list of contacts of an user, but each user may have a number diferent of contacts... I have a table **user** whith the colums **id\_user, nome, info** Each group needs contains the id of a user that is the owner of the group, the ids of the others users and other int...
Something like this: * (P) means primary key * (F table.column) means foreign key to table.column A table for all the groups. ``` groups id unsigned int(P) owner_id unsigned int(F users.id) name varchar(50) // Vitor's Group, Dan's Group, etc. ``` A table for all your users...
You need to have two tables to model this correctly. The first table should store info about the group, including an FK to the owning user. The second table should store the membership of the group. Basically to columns `group_id` and `user_id`.
About modeling a DB
[ "", "mysql", "sql", "database", "database-design", "" ]
I have a list of players. The players are sorted by points. What I'd like to know is how do I get the ranking number of a CERTAIN player? This is my code so far (which doesn't work because it seems to have some bugs): ``` $rank = mysql_query (SET @rank := 0; SELECT *, @rank := @rank + 1 FROM ava_users WHERE id = '".$...
``` $rank = mysql_query ( "SELECT a.*, ( SELECT COUNT(1) FROM ava_users b WHERE (b.points, b.id) >= (a.points, a.id) ) AS rank FROM ava_users a WHERE a.`user` = '$id'" ); ```
Try this: ``` SELECT `user`, rank FROM ( SELECT `user`, ( @rank := @rank + 1 ) as rank FROM ava_users, ( select (@rank := 0 ) ) rnk ORDER BY points DESC ) ranks WHERE `user` = '".$id."' ```
How to get ranking of specific player?
[ "", "mysql", "sql", "database", "" ]
@ConfListTable is a table valued parameter (TVP) which has a list of confirmation codes. I want to select all the records from PmtHist table where the confirmation code is also in @ConfListTable. The following code works well for this; no problems. ``` Select * from PmtHist Where Confirmation in( Select Str1 as Co...
A quick & easy way is to simply use REPLACE: ``` Select * from PmtHist Where REPLACE(Confirmation, 'voided', '') in( Select Str1 as ConfirmationCode From @ConfListTable ) ```
``` select * from PmtHist ph where exists ( select 1 from @ConfListTable where ph.Confirmation in (Str1, Str1 + 'voided') ) ```
How to Select where in(Other table) but with modification
[ "", "sql", "t-sql", "" ]
I tested each part of the SQL and it works fine. Something is Wrong with my `WHERE` clause however.. not getting much detail setting breakpoints in VS 2012 however... How should this be code for an `INSERT` statement with a subquery using MS SQL SERVER? ``` INSERT INTO Emails (email, insertDate) VALUES (@Email, @Da...
``` INSERT INTO Emails (email, insertDate) SELECT @Email, @DateToday WHERE NOT EXISTS (SELECT Emails.email FROM Emails WHERE Emails.email = @Email); ```
This will work ``` INSERT INTO Emails (email, insertDate) SELECT @Email, @DateToday WHERE NOT EXISTS (SELECT Emails.email FROM Emails WHERE Emails.email = @Email) ``` But a **better solution** may be a unique index on the email column
How to code INSERT Subquery correctly?
[ "", "sql", "sql-server", "" ]
I have a table with a column with strings that looke like this: ``` static-text-here/1abcdefg1abcdefgpxq ``` From this string `1abcdefg` is repeated twice, so I want to remove that partial string, and return: ``` static-text-here/1abcdefgpxq ``` I can make no guarantees about the length of the repeat string. In pur...
If you can guarantee a minimum length of the repeated string, something like this would work: ``` select REGEXP_REPLACE (input, '(.{10,})(.*?)\1+', '\1') "Less one repetition" from tablename tn where ...; ``` I believe this can be expanded to meet your case with some cleverness.
``` regexp_replace('static-text-here/1abcdefg1abcdefgpxq', '/(.*)\1', '/\1') ``` [fiddle](http://www.sqlfiddle.com/#!4/8e58e/2)
Oracle SQL -- remove partial duplicate from string
[ "", "sql", "regex", "oracle", "" ]
I'm really struggling with a case statement in MSSQL 2012. I've looked around for other answers, but although I've got some help, none seem to fix the problem. ``` case firstname when len(ltrim(rtrim(firstname))) > 11 then 'blah' else 'blahblah' end as test ``` I am getting a syntax error, on the '>' characte...
Try this version: ``` (case when len(ltrim(rtrim(firstname))) > 11 then 'blah' else 'blahblah' end) as test ``` The `case` statement has two versions. The one with the variable is used for constant expressions: ``` (case firstname when 'Arnold' then . . . when 'Betty' then . . . end) ``` The sec...
Chnage it to ``` case when len(ltrim(rtrim(firstname))) > 11 then 'blah' else 'blahblah' end as test ```
Case statement with aggregate and like clause - MSSQL 2012
[ "", "sql", "sql-server", "t-sql", "" ]
I have the below two tables ONE & TWO ``` ONE TWO ID ID CODE ----- --------- 1 1 1 2 1 2 3 2 1 4 3 1 5 3 2 3 3 ``` ## Output required ``` ID CODE ---------- 1 2 2 1 3 ...
``` SELECT A.ID ,B.CODE FROM ONE A LEFT outer JOIN (select id,max(code) CODE from two group by id) B ON A.ID = B.ID ``` I believe this is what you are looking for....
You can do this with a join and aggregation (if I understand the logic correctly): ``` select ONE.id, max(TWO.CODE) from ONE left outer join TWO on ONE.id = TWO.id group by ONE.id; ```
SQL Using inner query in left join
[ "", "mysql", "sql", "sql-server", "oracle", "db2", "" ]
Got two tables: "saldos\_one" and "saldos\_two", both tables got the following fields: CLIENTID, DATE, VALUE. I have to get the TOTAL arithmetic mean from the arithmetic mean for each CLIENTID in some periods of time. Lets take some examples: ``` > SELECT * FROM saldos_one; +----------+------------+---------+ | CLIE...
Try this ``` SELECT CLIENTID,SUM(VALUE)/2 VALUE FROM ( SELECT CLIENTID, TRUNCATE(SUM(VALUE)/COUNT(VALUE), 2) VALUE FROM saldos_one WHERE (DATE BETWEEN '2009-08-01' AND '2009-10-01') GROUP BY CLIENTID; UNION ALL SELECT CLIENTID, TRUNCATE(SUM(VALUE)/COUNT(VALUE), 2) VALUE FROM saldos_two ...
You could use a `UNION` of the tables, and then perform your analysis on them. E.g. ``` SELECT CLIENTID, AVG(VALUE) FROM ( SELECT CLIENTID, VALUE FROM saldos_one WHERE (DATE BETWEEN '2009-08-01' AND '2009-10-01') UNION SELECT CLIENTID, VALUE FROM saldos_two WHERE (DATE BETWEEN '2009-08-01' A...
join results and perform arithmetic mean
[ "", "mysql", "sql", "mean", "" ]
I have a query and when I run it I get the error message **ORA-00907: missing parenthesis**. When I replace the **CASE** statement with either **x = g and** or **y = g and** it runs as expected. ``` SELECT * FROM table1, table2, table3, table4, table5, table6, table7, table8 WHERE a = b and c = d and e = d and CASE st...
`case` is an expression, not a predicate (i.e condition) : it 'returns' a typed value and can not contain predicate as result (in the `then` parts). In your case (assuming `else -1` means 'no match') : ``` AND g = CASE strfldvar WHEN 'BROKEN_ARROW' THEN x WHEN 'BROKEN_BOX' THEN y ELSE NULL -- never match, eve...
Instead of ``` CASE strfldvar WHEN 'BROKEN_ARROW' THEN (x = g) WHEN 'BROKEN_BOX' THEN (y = g) ELSE -1 ``` have this: ``` x=CASE strfldvar WHEN 'BROKEN_ARROW' THEN g ELSE x END y=CASE strfldvar WHEN 'BROKEN_ARROW' THEN g ELSE y END ```
Where Clause Case Statement; ORA-00907: missing parenthesis
[ "", "sql", "oracle", "" ]
I just created a table within a huge database and saved it. I've tried to refresh the database to see if my new table appears and I closed & reopened the Management Studio but don't see my new table. I was wondering if there is a way to search for my new created table? I'm using SQL Server 2005. Thanks a lot.
You can try this:- ``` SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[table_name_here]') ``` or try this:- ``` USE YourDBName GO SELECT * FROM sys.Tables where name like '%tablename%' GO ```
``` Select * from sys.tables where name like '%tablename%' ```
How do I search for a table in sql 2005?
[ "", "sql", "sql-server", "sql-server-2005", "search", "qsqlquery", "" ]
I want to store partial dates in a relational database (MySQL, PostgreSQL, etc.). For example, input may just be the year (2013); the year and month (2013-08); or the year, month, and day (2013-08-29). I cannot just use a normal DATE type, as the year will be expanded to 2013-01-01, and this indistinguishable from havi...
I think there're two possible ways to go: **(1)** Store **substrings** of date, like: ``` '2013' -- year 2013 '2013-01' -- year 2013, January '2013-01-01' -- year 2013, January 1 ``` **(2)** Store **3 different columns**, Year, Month, Day (and you can build index Year + Month + Date...
Perhaps the best way is to treat these as spans of time and to have an `effdate` and `enddate`. The you can represent any time span you want. A year would be like '2012-01-01' and '2012-12-31'. A single date would be like '2013-08-28' and '2013-08-28'. This would also give you the flexibility to expand the representat...
Storing partial dates in a database
[ "", "sql", "database-design", "schema", "" ]
I want something like this. But I dont know the proper syntax. ``` select id from table1 where name = (insert into table1 (name) values ('value_abcd')) ```
So you have a table with an autoincrementing primary key, and you want to know its value after you have inserted a record. In SQL, you can use the [last\_insert\_rowid](http://www.sqlite.org/lang_corefunc.html#last_insert_rowid) function: ``` INSERT INTO table1(name) VALUES('value_abcd'); SELECT last_insert_rowid(); ...
When you say: ``` WHERE something = somethingElse ``` `somethingElse` is an expression (so is `something`, but anyway). You are trying to use an `INSERT` statement as your `somethingElse`, but an `INSERT` statement doesn't return anything, so it can not be evaluated as an expression. Therefore, not only is whatever y...
How can i use INSERT as subquery in SELECT statement in sqlite?
[ "", "sql", "sqlite", "select", "insert", "" ]
I've been trying to write a SQL query to return all rows in a table without a matching value. I have company, job, subjob, costcode, and costtype (among other fields). I need to return all rows which have a 'J' costtype, but no 'L' costtype. This is probably better explained with data: ``` Company Job Subjob ...
No need to use `JOIN`s: ``` SELECT * FROM YourTable A WHERE EXISTS(SELECT 1 FROM YourTable WHERE Company = A.Company AND Job = A.Job AND Costtype = 'J') AND NOT EXISTS(SELECT 1 FROM YourTable WHERE Company = A.Company AND Job = A.Job A...
SELECT company, job, subjob, costcode FROM Table WHERE Company = A.Company AND Job = A.Job AND Costtype = 'J' Minus SELECT company, job, subjob, costcode, FROM Table WHERE Company = A.Company AND Job = A.Job AND Costtype = 'L' I hope this satisfies,unless you want to display cost type in your result set.
SQL inner join without a match (same table)
[ "", "sql", "self-join", "" ]
I'm trying to create a search function. If the search input field is "foo bar", I split it into two keywords then do this query: ``` SELECT p.* FROM p_extra_fields as x INNER JOIN products as p ON x.product = p.id WHERE x.type = "1" AND ( (x.key = "model" AND x.value LIKE "%foo%") OR (x.key = "model" AND...
If you have [**SQLite FTS3 and FTS4 Extensions**](http://www.sqlite.org/fts3.html) enabled then you can take advantage of Full Text Search (FTS) capabilities. You will need to recreate the `p_extra_fields` table as a [`VIRTUAL`](http://www.sqlite.org/vtab.html) table. Then you can insert `OR` between your search terms ...
I think this `where` clause is simpler: ``` WHERE x.type = "1" and x.key in ('model', 'color', 'make') and (x.value like '%foo%' or x.value like '%bar%') ```
Multiple LIKE in sqlite
[ "", "sql", "sqlite", "search", "select", "sql-like", "" ]
If I set a Record in Sql with a `Default` constraint like ``` [Publicbit] BIT DEFAULT ((0)), ``` Do I need to set the `NULL/NOTNULL` Constraint? **Edit:** I am using a boolean but please expand your answer to other datatypes.
You never *need* the Null constraints, but the default value won't guard your table against explicit NULL's. So you should use a NOT NULL constraint if you want to enforce this condition. ``` use tempdb go CREATE TABLE example ( id BIT DEFAULT (0) ) INSERT example (id) VALUES (null) SELECT * FROM example ```
You should specify NOT NULL, to protect against a NULL from getting into this record. It sounds like the only valid values you want are 0 and 1. If someone (or you in the future) writes a record (or code) passing in a NULL for this column, then it will be allowed unless you specified NOT NULL. By specifying a DEFAULT,...
NULL NOT NULL on Default constraint in sql
[ "", "sql", "sql-server", "" ]
Join multiple table and get data in one line. tbl\_2012-08 (structure) ``` id | data_log | data_name 1 | 0001 | first 2 | 0002 | second ``` tbl\_2012-09 (structure) ``` id | data_log | data_name 1 | 0003 | third ``` Output: ``` data_log 0001 0002 0003 ``` How could I join this 2 table so t...
I don't know why you have separate tables for each month but you should be able to use a `UNION` query to return the data from both tables: ``` select id, data_log, data_name from `tbl_2012-08` union all select id, data_log, data_name from `tbl_2012-09` ``` I used a `UNION ALL` to return all rows from both tables whi...
You should uses [UNION ALL](http://technet.microsoft.com/en-us/library/ms180026.aspx) ``` SELECT id, data_log, data_name FROM `tbl_2012-08` UNION ALL SELECT id, data_log, data_name FROM`tbl_2012-09` ``` In this case the Union will join the result from one select statement with the other to make one table. Its import...
How to join and get data with multiple table but the same structure?
[ "", "mysql", "sql", "" ]
So .. I want to have a query that creates multiple rows with one query. Say I want something like this ``` Row 1: col1 = 'val1', col2 = 'val2', col3 = 'val3' Row 2: col1 = 'val1', col2 = 'val2', col3 = 'val4' Row 2: col1 = 'val1', col2 = 'val2', col3 = 'val5' ``` where ``` val3,val4,val5 ``` are returned by a sub-q...
Yes, it's possible: if your `val1` and `val2` are constant, then: ``` insert into table_name (col1, col2, col3) select 'val1', 'val2', column_name from table_two where condition; ```
Try this: ``` INSERT INTO table_name (col1, col2, col3) SELECT 'val1', 'val2', column_name FROM table_two WHERE condition; ```
inserting multiple rows with varying data with one query
[ "", "sql", "" ]
I have created the following script to set up my MySQL database: ``` CREATE DATABASE IF NOT EXISTS magicc_hat; USE magicc_hat; CREATE TABLE people ( personID INT NOT NULL AUTO_INCREMENT, firstName VARCHAR(45) NOT NULL, lastName VARCHAR(45), archived BOOL NOT NULL DEFAULT '0', PRIMARY KEY (personID) ); CRE...
The characters need to be the same. Use parentheses for both ``` CREATE TABLE homes ( }; ``` In this case: It's showing you the incorrect character in the error message: ``` check the manual that corresponds to your MySQL server version for the right syntax to use near '}' at line 8 ```
Get rid of the curly braces and replace with `(` Works great : <http://sqlfiddle.com/#!8/4ad37>
MySQL error on CREATE TABLE with BOOL column
[ "", "mysql", "sql", "" ]
I've been working all day on a problem that I expected to be simple, but is proving incredibly elusive. I suspect I may not be asking the right questions, so please bear with me. I have a table with a bunch of newspaper articles for a research project. The idea is that researchers can tag individual articles. These ta...
Try this: ``` SELECT A.ID, A.`Name`, GROUP_CONCAT(`TAGS`.`TAG`) AS tags FROM ARTICLES A LEFT JOIN TAGS ON TAGS.ID = A.ID WHERE NOT EXISTS( SELECT 1 FROM TAGS WHERE ID = A.ID AND Tag = 'search term') GROUP BY ARTICLES.ID, ARTICLES....
``` SELECT A.ID, A.`Name`, GROUP_CONCAT(`TAGS`.`TAG`) AS tags FROM ARTICLES A LEFT JOIN TAGS ON TAGS.ID = A.ID LEFT JOIN ( SELECT ArticleID FROM TAGS LKP WHERE Tag = 'search term' ) SRCH ON SRCH. ArticleID =A.ID WHERE SRCH. ArticleID IS NUll ```
Selecting for the absence of value in a one-to-many table design
[ "", "mysql", "sql", "" ]
I have a table that has data that looks something like this: ``` data_type, value World of Warcraft, 500 Quake 3, 1500 Quake 3, 1400 World of Warcraft, 1200 Final Fantasy, 100 Final Fantasy, 500 ``` What I want to do is select the maximum of each of these values in a single statement. I know I can easily do something...
If you want to return the max value for each data\_type in a separate column, then you should be able to use an aggregate function with a CASE expression: ``` select max(case when data_type='World of Warcraft' then value end) WorldofWarcraft, max(case when data_type='Quake 3' then value end) Quake3, max(case whe...
Once again, for more than just a few "data types", I suggest to use `crosstab()`: ``` SELECT * FROM crosstab( $$SELECT DISTINCT ON (1, 2) 'max' AS "type", data_type, val FROM tbl ORDER BY 1, 2, val DESC$$ ,$$VALUES ('Final Fantasy'), ('Quake 3'), ('World of Warcraft')$$) AS x (...
Selecting multiple max() values using a single SQL statement
[ "", "sql", "postgresql", "pivot", "crosstab", "" ]
I am trying to formulate a seemingly simple SQL query where I join two tables and order the results by the date difference from one of the columns and `NOW()`. I am trying the query: ``` SELECT advertise_id, qr_startdate, qr_enddate, DATEDIFF(day, NOW(), t1.qr_enddate) AS d FROM `adv_qr` t1 I...
``` SELECT advertise_id, qr_startdate, qr_enddate, DATEDIFF(NOW(), t1.qr_enddate) AS d FROM `adv_qr` t1 INNER JOIN advertise_table t2 ON t1.advertise_id = t2.lid ORDER BY d ASC ```
Check out [this SQLFiddle](http://sqlfiddle.com/#!2/754de/8): ``` SELECT advertise_id, qr_startdate, qr_enddate, DATEDIFF(NOW(), t1.qr_enddate) AS d FROM `adv_qr` t1 INNER JOIN advertise_table t2 ON t1.advertise_id = t2.lid ORDER BY d ASC ``` You can find the MySQL [`DATEDIFF` docume...
SQL - Order by ascending date difference from NOW()
[ "", "mysql", "sql", "" ]
I have a database structure in the below format, subjects table ``` subject_id subject_name 1 HTML 2 Java ``` chapters table ``` chapter_id chapter_name subject_id 1 Doctype 1 2 Intro to Java 2 ``` tutorials table ``` tutorial_id tutorial_name chapter_id...
No, you can get it indirectly from the chapters table. It's redundant in the tutorial table.
No need of Using it as its chapter id is available in chapter table
Database structure
[ "", "sql", "database-design", "" ]
I need to select recods from oracle table for the current calendar week based on a date datatype field. Currently I am doing like this: ``` select * from my_table where enter_date > sysdate -7 ``` If today is Thursday, this query will select records seven days from today which infiltrates to last week on Thursday. Is...
`to_char(sysdate, 'd')` returns day of week in [1..7] range; so try using ``` select * from my_table where enter_date >= trunc(sysdate) - to_char(sysdate, 'd') + 1 ```
If your week starts on a Monday then: ``` select ... from ... where dates >= trunc(sysdate,'IW') ``` For alternative definitions of the first day of the week, trunc(sysdate,'W') truncates to the day of the week with which the current month began, and trunc(sysdate,'WW') truncates to the day of the week with which ...
select records weekly from Oracle table
[ "", "sql", "oracle11g", "" ]
Xml Column returns no rows. Below created a table type and xml value inserted into that table. After executing the below mentioned two queries no value is returned. Xml data is a valid data. ``` DECLARE @Test TABLE (Id INT IDENTITY (1,1), XMLDATA XML) INSERT INTO @test SELECT ' <TXLife xmlns="http://ACORD.org/Sta...
Well, if I test your code with `CREATE TABLE`, [here](http://sqlfiddle.com/#!6/4d160/1) and [here](http://sqlfiddle.com/#!6/4d160/3), the unfiltered select works just fine. However, the second filtered select returns no results. If I alter the query to to specify the right namespace, like in [@Devart](https://stackove...
Try this one - ``` DECLARE @XML XML SELECT @XML = ' <TXLife xmlns="http://ACORD.org/Standards/Life/2" xmlns:tx="http://ACORD.org/Standards/Life/2" Version="2.20.00"> <TXLifeRequest PrimaryObjectID="Holding_1"> <CorrelationGUID>4b30545a-158b-441a-a37a-0b259f757059</CorrelationGUID> </TXLifeRequest> </T...
Selecting XML Data from SQL query - No values returned
[ "", "sql", "sql-server", "" ]
I'm working with Microsoft SQL Server. ``` IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'ServerSettings' AND COLUMN_NAME = 'MapIsAlwayCalcLenByWebServices' ) IF ( SELECT MapIsAlwayCalcLenByWebServices FROM ServerSettings ) = 0 UPDATE Server...
No, the entire *batch* is first compiled, and then execution starts. Since it can't compile the batch because you reference an invalid column, it never executes the `if` statement. You would need to protect the code that references a possibly absent column in an `EXEC`, something like: ``` if exists(select * from INF...
Try this one - ``` IF EXISTS( SELECT 1 FROM sys.columns c WHERE c.name = 'MapIsAlwayCalcLenByWebServices' AND c.[object_id] = OBJECT_ID('dbo.ServerSettings') ) BEGIN EXEC sys.sp_executesql ' UPDATE dbo.ServerSettings SET MapCalculateDistanceSource = 0 WHERE MapIsA...
Sql if statement after another if check
[ "", "sql", "sql-server", "" ]
Here are my two tables: Songs: ``` +--------+---------------------+ | SongID | SongDeviceID | +--------+---------------------+ | 3278 | 1079287588763212246 | | 3279 | 1079287588763212221 | | 3280 | 1079287588763212230 | +--------+---------------------+ ``` Votes: ``` +--------+--------+ | SongID | Use...
Try this ``` SELECT Songs.SongDeviceID, COUNT(*) FROM Votes INNER JOIN Songs ON Votes. SongID = Songs.SongId GROUP BY Votes.SongID, Songs.SongDeviceID ORDER BY count(*) DESC LIMIT 1 ```
for first ``` SELECT SongID,COUNT(*) from votes GROUP BY SongID order by count(*) DESC LIMIT 1 ``` and you want song device name then ``` SELECT SongID,COUNT(*),SongDeviceID from votes left join Songs on votes.songid = song.songid GROUP BY SongID order by count(*) DESC LIMIT 1 ```
Selecting only top result from two table query
[ "", "mysql", "sql", "relational-database", "" ]
I had join 4 sql statement by using UNION ALL. as the WHERE condition is the same, is it possible to combine the WHERE condition into one ? ``` select 'Transfer In' as MovementType, * from vHRIS_StaffMovement_TransferIn where cur_deptid in (1,2,3,4,5) and cast(EffectiveDate as date) <='2013-08-02' an...
You can do it this way: ``` select * from ( select 'Transfer In' as MovementType, * from vHRIS_StaffMovement_TransferIn union all select 'Terminate' as MovementTyep, * from vHRIS_StaffMovement_Terminate union all select 'New Hire' as MovementTyep, * from vHRIS_StaffMoveme...
You can use a sub query: ``` SELECT X.* FROM (SELECT 'Transfer In' AS MovementType, * FROM vhris_staffmovement_transferin UNION ALL SELECT 'Terminate' AS MovementTyep, * FROM vhris_staffmovement_terminate UNION ALL SELECT 'New Hire' AS MovementTyep, * ...
SQL Union all statement
[ "", "sql", "union", "where-clause", "union-all", "" ]
I have the following table ``` table x labref name repeat_status 111 L 1 111 L 1 111 K 1 111 K 1 111 L 2 111 L 2 111 M 1 111 M 1 ``` The result that i need is ``` labref name repeat_status 111 ...
``` SELECT name, repeat_status FROM `x` WHERE labref = '111' GROUP BY name ,repeat_status; ```
``` select DISTINCT labref ,name, repeat_status FROM x WHERE labref = '111' ``` This query would get the result you are looking for.
Group returned result by mysql
[ "", "mysql", "sql", "" ]
I have a problem I'm working on with Oracle SQL that goes something like this. TABLE ``` PurchaseID CustID Location ----1------------1-----------A ----2------------1-----------A ----3------------2-----------A ----4------------2-----------B ----5------------2-----------A ----6------------3------...
``` SELECT * FROM YourTable T WHERE CustId IN (SELECT CustId FROM YourTable GROUP BY CustId HAVING MIN(Location) <> MAX(Location)) ```
You should be able to use something similar to the following: ``` select purchaseid, custid, location from yourtable where custid in (select custid from yourtable group by custid having count(distinct location) >1); ``` See [SQL Fiddle with Demo](http://sqlfiddle....
Oracle SQL - Comparing Rows
[ "", "sql", "oracle", "" ]
I'm looking for a SQL Server UDF that will be equivalent to `DATEPART(WEEK, @date)`, but will allow the caller to specify the first day of the week. Somewhat similar to MySql's `WEEK` function. E.g.: ``` CREATE FUNCTION Week (@date date, @firstdayofweek int) RETURNS int BEGIN -- return result would be the same as: ...
I've found a couple of articles that helped me answer to derive an answer to this question: 1. [Deterministic scalar function to get week of year for a date](https://stackoverflow.com/questions/11432719/deterministic-scalar-function-to-get-week-of-year-for-a-date/11433441) 2. <http://sqlmag.com/t-sql/datetime-calculat...
You could use something like this: ``` DATEPART(WEEK, DATEADD(DAY, 8 - @firstdayofweek, @date)) ``` Instead of moving the first day of the week you are moving the actual date. Using this formula the first day of the week would be set using the same number values for days that MS SQL Server uses. (Sunday = 1, Saturday...
SQL Server UDF for getting week of year, with first day of week argument
[ "", "sql", "sql-server", "datepart", "" ]
I'm trying to do an `UPDATE` on a double `INNER JOIN`, and getting the following error: ``` #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM pro_users AS u INNER JOIN cAlerts AS c ON c.user_id = u.user_id I' at line 3 ``...
This would be the ISO/ANSI SQL way of doing the update: ``` update pro_users u set active_member = 0 where u.active_member = 1 and exists ( select * from cAlerts c where c.user_id = u.user_id and c.status = 0 ) and exists ( select * from s...
Can you try this : ``` UPDATE pro_users AS u SET u.active_member = 0 WHERE u.active_member = 1 AND ( SELECT c.user_id FROM cAlerts AS c WHERE c.user_id = u.user_id AND c.status = 0 LIMIT 1 ) IS NOT NULL AND ( SELECT s.user_id FROM srAle...
UPDATE and double INNER JOIN kicking up mysql error
[ "", "mysql", "sql", "" ]
I have two tables: Table1 looks like this: ``` id type 1 bike 2 car 3 cycle 4 bike ``` And Table2 looks like this: ``` id type 1 bike 2 car ``` I want my final output to look like the following: ``` type count_table1 count_table2 bike 2 1 car ...
Simple solution, no need for complicated table joins & functions: ``` SELECT type, MAX(count_table1) as count_table1, MAX(count_table2) as count_table2 FROM ( ( SELECT type, COUNT(*) AS count_table1, 0 AS count_table2 FROM Table1 GROUP BY type ) UNION ( SELECT type, 0 AS count_table1, COUNT(*) AS count...
You can try this: ``` SELECT t1.TYPE, ifnull(t1.COUNT1,0) CountTable1, ifnull(t2.COUNT2,0) CountTable2 FROM (SELECT TYPE, COUNT(*) count1 FROM TABLE1 GROUP BY TYPE)T1 LEFT JOIN (SELECT TYPE, COUNT(*) count2 FRO...
Group by column and display count from all tables in mysql
[ "", "mysql", "sql", "" ]
I have a key string like ``` Empl:9998 Earn Code:7704 Seq:1 ``` I need take the employee number 9998 out of the string. The employee number will always start at position 6 and end before the second `E`. I have been played around with all string function but no success. I use MS SQL.
The following statement will do this: ``` select substring(empno, 6, charindex('E', empno, 6) - 6) from (select 'Empl:9998 Earn Code:7704 Seq:1' as empno) t; ``` You might really want `-7` if you don't want the space in the "number".
the [substring](http://technet.microsoft.com/en-us/library/ms187748.aspx) function will get you started, but you'll also need [charindex](http://technet.microsoft.com/en-us/library/ms186323.aspx). (I recommend searching for the index of the space character)
Take substring out of string
[ "", "sql", "sql-server", "" ]
Consider the below table ``` CREATE TABLE `temp` ( `id` int(11) NOT NULL, `lang` char(2) COLLATE utf8_unicode_ci NOT NULL, `channel` char(2) COLLATE utf8_unicode_ci NOT NULL, `name` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, PRIMARY KEY (`id`,`lang`,`channel`) ) insert into `temp` (`id`, `lang`, `cha...
There are several ways of achieving this. One way is to use a sub-select with `not exists` clause: ``` select id, channel from temp t1 where t1.lang = 'en' and not exists ( select 1 from temp t2 where t2.lang = 'fr' and t1.id = t2.id ) ``` Alternatively, you can use an outer join: ``` select t1.id, t1.channe...
based on @AleksG ``` SELECT t1.id, t1.channel, t1.name FROM temp t1 LEFT JOIN temp t2 ON t1.id = t2.id AND t2.lang = 'fr' WHERE t1.lang = 'en' AND t2.lang IS NULL ```
SQL join table to self to find difference
[ "", "mysql", "sql", "join", "" ]
I have the following example code ``` DECLARE myRow table%rowtype myVar table2.column%type BEGIN SELECT table.col1, table.col3, table.col4, table2.column INTO myRow FROM table JOIN table2 On table.col6 = table2.col1; END; ``` How can I refactor so that it is a valid statement? Can I s...
Your PL/SQL is valid and acceptable provided: 1. Table TABLE contains exactly 4 columns, corresponding to the 4 values you are selecting. 2. The query will return exactly 1 row. If table TABLE does not contain exactly 4 columns then you need to select into something else, perhaps just 4 variables: ``` DECLARE v...
You can use a cursor, for doing this. That way you dont have to worry about TOO\_MANY\_ROWS or NO\_DATA\_FOUND exception. And also you will have the flexibility of each time you add a column to your query it automatically gets added to your variable of the same type You have two options with the cursor: using just th...
How to use SELECT... INTO with a JOIN?
[ "", "sql", "oracle", "join", "plsql", "select-into", "" ]
I am trying to understand how the single quotes work in SQL. All I want to achieve is ``` INSERT INTO LOGTABLE (ID, ROLLNO) VALUES ('E8645F55-A18C-43EA-9D68-1F9068F8A9FB', 28) ``` Here `ID` is a uniqueidentifier field and `rollNo` is an int. So I have this sample test cod...
*(I'm going to assume you need dynamic SQL for reasons not obvious in the question, since this doesn't seem to require dynamic SQL at all.)* As @Gidil suggested, the problem here is trying to treat a uniqueidentifier as a string. In this case, there really isn't any reason to declare `NEWID()` in the outer scope, sinc...
My question is: Why are you using dynamic SQL? It's one of those techniques that is useful in some situations, but can be abused easily. As for the answer to your question, I use a technique to help minimize the flipping in and out of SQL construction: ``` DECLARE @query VARCHAR(MAX) SET @query = ' insert into fil...
Building insert statement with quotes in SQL
[ "", "sql", "sql-server", "" ]
I am trying to select rows that have columns with incomplete data. In this case, incomplete columns have a value less than 1. I'm trying to find rows that have at least one incomplete column, but I'm not sure how to combine this into a SQL statement. Here's what I've been trying unsuccessfully: ``` SELECT id FROM ...
In SQL `AND` takes precedence over `OR` in the same way as multiplication takes precedence over addition, so you need to use parentheses to force the precedence that you want: ``` SELECT id FROM eval WHERE (month = :month) AND (uid=:uid) AND ( (rotation < 1) OR (mr < 1) OR (nc < 1) OR ...
You need to fix the logic. I think you want an `and` before the `or`, along with parentheses: ``` SELECT id FROM eval WHERE (month = :month) and (uid=:uid) AND ( (rotation < 1) OR (mr < 1) OR (nc < 1) OR (clinic_days < 1) OR (clinic_pts < 1) OR (mksap < 1) ) ```
SQL Statment with OR and AND < 1
[ "", "mysql", "sql", "" ]
I have a table like this ``` CREATE TABLE [dbo].[tbl_LandRigs]( [ID] [int] IDENTITY(700000,1) NOT NULL, [Company] [nvarchar](500) NULL, [Rig] [nvarchar](500) NULL, [RigType] [nvarchar](200) NULL, [DrawWorks] [nvarchar](500) NULL, [TopDrive] [nvarchar](200) NULL, [RotaryTable] [nvarchar](50...
You are storing them as text(`nvarchar`), that's why you get [lexographical order](http://en.wikipedia.org/wiki/Lexicographical_order). That means every character is compared with each other from left to right. Hence `4000` is "higher" than `30000` (the last zero doesn't matter since the first 4 is already higher than ...
As `MaxDD` is a `varchar`, not a number it is sorted in lexicographical order (i.e. ordered by the first character, then second, ...), not numerical. You should convert it to a numerical value
SQL Order By not working properly
[ "", "sql", "sql-server-2008", "sql-order-by", "" ]
Imagine the following MySQL table of orders: ``` id | name 1 | Mike 2 | Steve 3 | Janet 4 | Juliet 5 | Mike 6 | Jane ``` This is my current query: ``` SELECT * FROM table ORDER BY id DESC ``` However, I'd like to "group" those by `name`, so that I have orders from the same person listed after one another, how...
E.g.: ``` SELECT y.id , y.name FROM my_table x JOIN my_table y ON y.name = x.name GROUP BY name , id ORDER BY MAX(x.id) DESC , id DESC; ```
You need to have special calculation to get their row position. ``` SELECT a.* FROM tableName a INNER JOIN ( SELECT Name, @ord := @ord + 1 ord FROM ( SELECT MAX(ID) ID, NAME FR...
Order by two columns
[ "", "mysql", "sql", "" ]
SQL Server - I have 3 simple tables (Fname, Lname and Exceptions) with one column each called Name. I want my end result to look like: (Everybody in Fname + Everybody in LName) - (Everybody in Exceptions). FName: ``` Name A B ``` LName: ``` Name Y Z ``` Exceptions: ``` Name A Z ``` Expected Query Result Set: ``...
The parts of a `UNION` are handled as separate queries, so you can group them in a subquery: ``` SELECT Name FROM (Select Name from Fname UNION ALL Select Name from Lname)sub WHERE Name NOT IN (Select Name from Exceptions) ``` You can keep that as `UNION ALL` if you don't care about duplicates.
You need a subquery, i prefer `NOT EXISTS`: ``` SELECT X.name FROM (SELECT name FROM fname UNION ALL SELECT name FROM lname) X WHERE NOT EXISTS (SELECT 1 FROM exceptions E WHERE x.name = E.name) ``` [**Demo**](http://sqlfiddle.com...
UNION ALL and NOT IN together
[ "", "sql", "sql-server", "sql-server-2008", "union", "" ]
The result of the two queries should be identical. Same data. Same formula. Same cast. One result is calculated in a query against a table variable, while the second is calculated against variables. I have replaced the table variable with temp table and permanent table with identical results. Why are my results differ...
The difference is due to the difference in precision of your two `DECIMAL` fields: Changing @comm to `(38,6)`: ``` DECLARE @comm DECIMAL(38 , 6) , @quantity INT , @multiplier INT , @price DECIMAL(38 , 10) ``` I get: ``` --------------------------------------- 0.0034990000 0.0034990000 ``` Likewise changi...
`@comm` is defined as decimal(20,6) while the `comm` column is decimal(38,6). You also assign a value with 7 decimal points to @comm, which only accepts up to 6 decimals According to the [docs](http://msdn.microsoft.com/en-us/library/ms187746.aspx), decimals with a precision between 20-28 take 13 bytes while larger de...
SQL Formula Returns Inconsistent Precision
[ "", "sql", "sql-server", "t-sql", "" ]
How to insert string with super script characters in PostgreSQL? I want to insert "TM" as power of string "RACH"? I tried the following query: ``` update contact SET name=E'RACH$^'TM where id='10782' ```
Use the dedicated characters '®' or '™' as trademark signs. ``` UPDATE contact SET name = 'RACH™' -- '™' not 'ᵀᴹ' WHERE id = '10782'; ``` Some other characters (but not all!) have superscript variants in Unicode, but many fonts don't support these exotic code points and don't even include glyphs to represent them. ...
I don't know if it possible to convert symbols to supersripts without creating mapping function for that, but you can just write it manually: ``` update contact SET name='RACHᵀᴹ' where id='10782' ``` [**`sql fiddle demo`**](http://sqlfiddle.com/#!1/a2222/1) Mapping function could be something like this: ``` create ...
Special superscript characters
[ "", "sql", "postgresql", "postgresql-9.1", "superscript", "" ]
I need help building a SQL query that returns a flattened result of the top 2 items in an order. The tables and relevant fields are as follows: ``` Order OrderItem ------- ----------- orderId orderId productCode quantity ``` I'm looking for the des...
``` select o.orderId, max(case when row_num = 1 then oi.ProductCode end) as ProductCode1, max(case when row_num = 1 then oi.Quantity end) as Quantity1, max(case when row_num = 2 then oi.ProductCode end) as ProductCode2, max(case when row_num = 2 then oi.Quantity end) as Quantity2 from Order as o ...
You can do this with conditional aggregation and the window function `row_number()`: ``` select orderId, max(case when seqnum = 1 then ProductCode end) as ProductCode1, max(case when seqnum = 1 then Quantity end) as Quantity1, max(case when seqnum = 2 then ProductCode end) as ProductCode2, ...
SQL Query Flattens Order and Top Order Items
[ "", "sql", "sql-server", "" ]
I need to write a query that will return to me all the items in a group in one record, separated by commas,from two tables, example result below, Items table: ``` -------------------- Name | Group_ID -------------------- item1 | 1 item2 | 1 item3 | 3 ``` Group table: ``` -------------------- ID | N...
USE [GROUP\_CONCAT](http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat) ``` SELECT group_concat(Name) FROM table ```
You need to use GROUP\_CONCAT and a GROUP BY It would be something like this: ``` SELECT gr.id, GROUP_CONCAT(item.name SEPARATOR ',') FROM `group` gr LEFT JOIN item ON(gr.id=item.group_id) GROUP BY gr.id ``` This query will display groups that don't have items associated. If you don't need those groups, then the be...
sql query to list all the items in a group in one record
[ "", "mysql", "sql", "" ]
``` SELECT school WHERE school LIKE '%suny at albany%'; ``` This will result in Suny at Albany. If I were to type in: ``` SELECT school WHERE school LIKE '%suny albany%'; ``` Returns nothing Is there a way to separate the white space characters so that there are LIKE statements between them. so that when I enter ...
Use a `%` wildcard in the middle as well. ``` SELECT school WHERE school LIKE '%suny%albany%'; ``` You could also leave a space around the `%` like ``` SELECT school WHERE school LIKE 'suny % albany'; ``` to prevent matching super strings like `sunyys palbanys` or `sunyalbany`.
Use another percentage sign instead of the space like so: ``` SELECT school WHERE school LIKE '%suny%albany%'; ```
Is there a way to separate a MySql statement by space with a LIKE statement?
[ "", "mysql", "sql", "" ]
I have created a query to generate some data to sql databases, but generation of 1 GB data takes about 45 minutes. How to increase a performance of data generation? ``` DECLARE @RowCount INT DECLARE @RowString VARCHAR(10) DECLARE @Random INT DECLARE @Upper INT DECLARE @Lower INT DECLARE @InsertDate DATETIME SET @Lowe...
You may try following also: ``` ;with seq as ( select top (3000000) N = row_number() over (order by @@spid) - 1 from sys.all_columns c1, sys.all_columns c2 ) INSERT INTO Table_1 (q, w, e, r, t, y) select right('0000000000' + cast(N as varchar(10)), 10) ,p.InsertDate ,DATEADD(dd, 1, p.InsertDate) ,D...
The problem is you are generating and inserting the data one row at a time. SQL Server is not designed to work that way. You need to find a set-based solution. This worked for me in under 30 seconds: ``` CREATE TABLE #Table_1 ( Id INT IDENTITY(1,1) , RowString AS REPLICATE('0', 10 - LEN(CAST(Id AS VARCHAR))) +...
SQL query to fast data generation
[ "", "sql", "sql-server", "performance", "data-generation", "" ]
I'm converting old code to use LINQ. The old code looked like this: ``` // Get Courses sqlQuery = @"SELECT Comment.Comment, Status.StatusId, Comment.DiscussionBoardId, DiscussionBoard.CourseId, Comment.CommentID FROM Status INNER JOIN Comment ON Status.StatusId = Comment.StatusId INNER JOIN ...
Enclose the whole query in parentheses and add `.ToList()` at the end. Or add another line: ``` var list = query.ToList(); ```
Try adding the `ToList()` method at the end of the query.
Getting LINQ query result into a list?
[ "", "asp.net", "sql", "linq", "" ]
I have two tables. One of them named `files` and there is al list of all files. the second table called `payments`, and there is in there a list of payments for some files. Payments: ``` id | fileid | {...} 1 2 2 3 3 2 ``` Files: ``` id | {...} 1 2 3 ``` I want to select all files, and join the table `pay...
As others have noted you need to use LEFT JOIN. - This tells MySQL that entries from the tables to the left should be included even if no corresponding entries exists in the table on the right. Also you should use GROUP BY to indicate how the COUNT should be deliminated. So the SQL should be something like; ``` SELE...
Try `LEFT JOIN` - in MySQL, the default `JOIN` is actually an `INNER JOIN`. In an `INNER JOIN`, you will only get results back that are in both sides of the join. See: [Difference in MySQL JOIN vs LEFT JOIN](https://stackoverflow.com/questions/9770366/difference-in-mysql-join-vs-left-join) And, as noted in the commen...
SQL Select - Some Rows Won't Display
[ "", "mysql", "sql", "join", "" ]
I'm using PostgreSQL 9.1. I have the column name of a table. Is it possible to find the table(s) that has/have this column? If so, how?
you can query [system catalogs](http://www.postgresql.org/docs/current/static/catalogs-overview.html): ``` select c.relname from pg_class as c inner join pg_attribute as a on a.attrelid = c.oid where a.attname = <column name> and c.relkind = 'r' ``` [**`sql fiddle demo`**](http://sqlfiddle.com/#!1/f5c03/5)
You can also do ``` select table_name from information_schema.columns where column_name = 'your_column_name' ```
How to find a table having a specific column in postgresql
[ "", "sql", "database", "postgresql", "postgresql-9.1", "" ]
I have a datetime column that I need to display in the following format: ``` YYYY/MM/DD 00:00:00:000 ``` With `CONVERT`, I can't find any suitable styles. The `/` in the format is really important as it needs to be compared with a `VARCHAR` column that has text `YYYY/MM/DD 00:00` as part of the description like belo...
You can use the style that most closely resembles what you want to compare on and use `REPLACE` to replace the `-` with `\`. ``` SELECT REPLACE(CONVERT(<yourstyle>),'-','/'); ``` --- **Edit** *Cudo's to @bluefeet* ``` SELECT REPLACE(CONVERT(varchar(23), yourdate, 121),'-','/'); ``` From [Technet](http://technet.mi...
Well you can convert both Dates in any format before you compare the two just use any of these: run this and you can select from them, make sure to convert both dates before Comparing ``` Select convert(varchar, GetDate(), 100) as '100 Conversion', convert(varchar, GetDate(), 101) as '101 Conversion', ...
Convert Datetime format to varchar format style workaround
[ "", "sql", "sql-server", "t-sql", "datetime", "" ]
DBMS : MS SQL 2005 Consider the following table as an example ``` [CurrencyID] ---- [Rate] ---- [ExchangeDate] USD --------------- 1 ------ 08/27/2012 11:52 AM USD -------------- 1.1 ----- 08/27/2012 11:58 AM USD -------------- 1.2 ----- 08/28/2012 01:30 PM USD --------------- 1 ------ 08/28/2012 01:35 PM ``` Ho...
For SQL 2008, the following does the trick: ``` SELECT CurrencyID, cast(ExchangeDate As Date) as ExchangeDate , ( SELECT TOP 1 Rate FROM Table T2 WHERE cast(T2.ExchangeDate As Date) = cast(T1.ExchangeDate As Date) AND T2.CurrencyID = T1.CurrencyID ORDE...
You didn't specify which DBMS, following is Standard SQL: ``` select CurrencyID, Rate, ExchangeDate from ( select CurrencyID, Rate, ExchangeDate, row_number() over (partition by CurrencyID, cast(ExchangeDate as date) order by ExchangeDate desc) as rn from tab ) as dt where rn =...
SQL select value by Maximum time per day
[ "", "sql", "" ]
I am trying to visualize tables and their relations using pgAdmin. I have understood that there is a [query visualizer tool](http://link.sheidaei.com/byqyv) available for pgAdmin. However, that only is useful if you are dealing with queries. My main goal is to generate a graphical representation of all the tables avail...
I have found [this webpage](https://wiki.postgresql.org/wiki/Community_Guide_to_PostgreSQL_GUI_Tools) on postgresql wiki, with various tools on utilizing a postgresql database. I have used DbWrench on Mac to generate the ERD.
In pgAdmin 4 right click on the database and then "Generate ERD (Beta)" [![enter image description here](https://i.stack.imgur.com/WbVVv.png)](https://i.stack.imgur.com/WbVVv.png)
How to visualize database tables in postgresql using pgAdmin?
[ "", "sql", "database", "postgresql", "pgadmin", "" ]
I have a table like following: ``` ID Type ParentID 001 C 007 002 C 005 003 B 007 004 C 008 005 R NULL 006 C 004 007 B 004 008 R 009 009 X NULL ``` The ...
you need recursive CTE: ``` with cte1 as ( select T.ID, T.Type, T.ParentID, case when T2.Type = 'X' then cast(null as varchar(3)) else T.ParentID end as MasterParentID from Table1 as T left outer join Table1 as T2 on T2.ID = T.ParentID ), cte2 as ( select ...
In SQL Server 2005 and above, a "[common table expression](http://technet.microsoft.com/en-us/library/ms175972%28v=sql.105%29.aspx)" can do this... ``` -- Assuming this table structure --CREATE TABLE dbo.Test ( ID char(3), Type char(1), ParentID char(3)) ; WITH Tree(StartID, StartType, Parent, Child) AS ( SELECT ...
SQL Find Parent ID for Certain Record Type
[ "", "sql", "sql-server", "t-sql", "" ]
Little backstory: We have two scheduling databases that we import from, that feeds Data into our SQL Server. Sometimes that creates duplicate records for the same classroom during the same academic period, but it doesn't happen very often. What I need to do is merge them into one row WITHOUT altering database (as I do ...
``` SELECT AcademicPeriod , BuildingNumber , RoomNumber , DayOfWeek MAX(930A) AS 930A, MAX(945A) AS 945A, MAX(1230P) AS 1230P, MAX(1245P) AS 1245P FROM {YourResultSet} Group BY AcademicPeriod, BuildingNumber, RoomNumber, DayOfWeek ```
Try this question: ``` SELECT x.AcademicPeriod, x.BuildingNumber, x.RoomNumber, x.DayOfWeek, MAX(x.[9:30a]) AS [9:30a], MAX(x.[9:45a]) AS [9:45a], MAX(x.[12:30p]) AS [12:30p], MAX(x.[12:45p]) AS [12:45p] FROM MySchema.MyTable x GROUP BY x.AcademicPeriod, x.BuildingNumber, x.RoomNumber, x.DayOf...
Merging two Schedule rows into one in SQL
[ "", "mysql", "sql", "sql-server", "" ]
**Context:** I've the following table(Example): ``` | ID | name | COUNTRY | --------------------------------------------- | 1 | cristian | FRANCIA,HOLANDA,ALEMANIA | | 2 | Andrea | FRANCIA,ESPAÑA,BELGICA | | 3 | Fabian | BELGICA,ALEMANIA | ``` I need to put all countries in ...
There's no builtin function to do this in MySQL. It's possible to do a boatload of string processing in MySQL, but it's ugly, and there has to be known finite limit on the number of string values in the comma separated list. Here's one way to get a distinct list of field values from all those comma separated lists: ...
No way with mysql for getting unique like this way. First it's bad that you storing values like this way. you have two solution: 1- Normalize your database. 2-get values from table and use php `explode()` , and use `array_unique` to remove duplicate values.
Distinct,REGEXP apply to Field and CONCAT_GROUP in MYSQL to remove repeated words to stored procedure
[ "", "mysql", "sql", "regex", "stored-procedures", "group-concat", "" ]
Is there a way to determine the first day of a year in Teradata SQL? For example, I use this to find the first day of the month: ``` SELECT dt + (1 - EXTRACT(DAY FROM dt)) AS dt ``` I know I can extract the year directly using `YEAR()` but I want to output the results as a date so it will work in some external chart...
Figured it out: ``` ADD_MONTHS(dt, -(EXTRACT(MONTH FROM dt) - 1)) + (1 - EXTRACT(DAY FROM dt)) ```
dnoeth's approach is cool for long term optimization of jobs, but, in my opinion, the simple answer is either Jeffrey's or the following. Not sure which one uses less resources: ``` select cast(extract(year from current_date)||'0101' as date format 'yyyymmdd'); ```
Teradata Determine First Day of Year
[ "", "sql", "teradata", "" ]
Hi I am using Oracle SQL Developer and am trying to get percentages on my table. My Current Query is: ``` select decode(grouping(life), 1, 'Total', life) as "LifeName", sum(case when task is not null and to_char(datee, 'MM') = '08' and to_char(datee, 'YYYY') = '2013' then 1 ...
``` SELECT t1.lifename, t1.monthstatus, (t1.monthstatus / t2.total * 100) as prcent FROM ( select decode(grouping(life), 1, 'Total', life) as "LifeName", sum(case when task is not null and to_char(datee, 'MM') = '08' and to_char(datee, 'YYYY') = '2013' then 1 else 0 end) as "MonthStatu...
The analytic function ratio\_to\_report() would probably work for you. It gives the ratio of a value to the sum of all of those values for a specified window. In your case: ``` 100* ratio_to_report(sum(...)) over () ``` I'm not sure how it would work in the presence of a rollup, though. <http://docs.oracle.com/cd/E...
Oracle SQL Trying to get Percentage of columns
[ "", "sql", "oracle", "" ]
I have a question according to SSRS. I am working with MSSQL Server management studio 2012 and BIDS Visual studio 2008 for the report design. I have a report with some multivalue parameters and a stored procedure in behind which returns the records. Now I've tried to find the problem on the parameter values passed to...
I will take a guess and say it is 'how' you are passing the multi value parameter. Personally when dealing with SSRS I use views, table functions, or just selects as SSRS can understand natively that this: ``` Where thing in (@Thing) ``` Actually means this in SSMS: ``` Where thing in (@Thing.Value1, @Thing.Value2, ...
This answer might look outdated but in case someone needs it I will just reproduce my experience since I had the same problem just yesterday and I the solution from a webpage. The problem: My report has 2 date parameters so to get data between that range, but i first noticed it did not work for 1 day, then I noticed t...
SSRS shows no records in report but query returns results
[ "", "sql", "t-sql", "reporting-services", "sql-server-2012", "" ]
I want to do query. ı use Microsoft sql if product is equal FAST and tree\_level is equal 0,1,2,3,4,5 count the number 0,1,2,3,4,5 and multiply 2 and tree\_level equal -1 count number multiply 2 and if product is equal MOBIL and tree\_level is equal 0,1,2,3,4,5 count the number multiply 3 and if product is equal FAC...
try this query and do let me know if u still facing problem ``` select DS.PersTel , DW.AD , DW.SOYAD , DS.RefPhoner , DS.Product , DS.Tree_level , CASE WHEN DS.Tree_level IN (-1) And DS.Product LIKE '%FACE%' THEN count(DS.Tree_level) * 2 WHEN DS.Tree_level IN (-1) And DS.Product LIKE '%FAST%' THEN ...
You can't do this: ``` CASE DS.Tree_level WHEN DS.Tree_level IN (0,1,2,3,4,5) THEN count(DS.Tree_level) * 3 WHEN DS.Tree_level IN (-1) THEN count(DS.Tree_level) * 2 WHERE DS.Product like '%FACE%' END AS Answer1 ``` But you can do: ``` CASE WHEN DS.Tree_level IN (0,1,2,3,4,5) AND DS.Product like '%FACE%' THEN ...
Multiply numbers using SQL and if else statement
[ "", "sql", "sql-server", "" ]
The below query gives the result i.e wherever value1 is there changes into changeValue1 ``` select case 1 when person ="value1" then "changeValue1" when person="value2" then "changeValue2" else person end as nickname from person; ``` Below query is not changing the value1 and value2 to co...
## General notes There are 2 types of cases: with a value after CASE and without it. 1. `CASE value WHEN [compare_value] THEN result [WHEN [compare_value] THEN result ...] [ELSE result] END` It compares the value after case with a list of possible values: ``` mysql> SELECT CASE 1 WHEN 1 THEN 'one' -> WHEN 2...
The reason it's not working is that you are comparing an integer with a boolean, which in mysql is either `1` or `0` - never `2`. There are two forms of the case statement. The first form is like this: ``` case when condition then value1 when condition1 then value2 else value3 end ``` the second is like th...
Case Value Statement
[ "", "mysql", "sql", "" ]
I want to display the names which is start from 0 to 9. i do not to use reg\_exp and like functions. My data: ``` select * from emp2; 15326 25371 35371 48615 59718 69718 79718 89718 99718 05326 15326 25371 35371 48615 59718 69718 79718 89718 99718 a19716 b09414 d%5034 !5033 **5031 89718 39718 05326 a19716 b09414 d%50...
``` select * from emp2 where name >= '0' and name < ':' ``` This statement would use an index on `name` column if it exists.
The query you want is: ``` select * from emp2 where substr(name, 1, 1) between '0' and '9'; ``` You are misunderstanding `between` when applied to strings. The expression: ``` name between '+1' and '10' ``` Is looking for names that start with a character ranging from a `'+'` to a `'1'`. For digits, that would be t...
I want to display the name which is start from 0 to 9
[ "", "sql", "database", "oracle", "" ]
Is this possible in SQLite? Like: ``` UNIQUE(col1, col2 = "something", col3), ``` What I mean by unique: ``` #1 col1=Foo | col2=Foo | col3=Foo > OK #2 col1=Foo | col2=Foo | col3=Foo > OK #3 col1=Foo | col2=something | col3=Foo > OK #4 col1=Foo | col2=something | col3=Foo > Should fail becaus...
This is not supported directly; you have to implement it with a trigger: ``` CREATE TRIGGER something_unique_check BEFORE INSERT ON MyTable FOR EACH ROW WHEN NEW.col2 = 'something' BEGIN SELECT RAISE(FAIL, '"something" record is not unique') FROM MyTable WHERE col1 = NEW.col1 AND col2 = NEW.col2 ...
I haven't tested it but I think you can do that with [partial indexes in SQLite 3.8.0](http://www.sqlite.org/partialindex.html) (released 2013-08-26): ``` CREATE UNIQUE INDEX "partial_index" ON "table" ("col1", "col2", "col3") WHERE ("col2" = 'something'); ``` I might be wrong though.
UNIQUE constraint but only when column = something
[ "", "sql", "sqlite", "pdo", "constraints", "unique", "" ]
For example I have this stored procedure ``` Create Procedure sampleProcedure AS BEGIN Select EmpID, Name, Address, PhoneNumber From EmpTable END ``` Now in my application how I will do this: For example a user checked the checkBox1 then the query above will be `ORDER BY EmpID` else if the checkBox2 is checked then ...
Introduce a parameter for the procedure to dictate the sort order: ``` Create Procedure sampleProcedure1 @orderByEmpId bit AS BEGIN if (@orderByEmpId = 1) Select EmpID, Name, Address, PhoneNumber From EmpTable Order By EmpID else Select EmpID, Name, Address, PhoneNumber From EmpTable Order By Name END `...
I would suggest ordering your collection in your application based on your checkbox selection. E.g. ``` if (checkbox1.Checked) employees = employees.OrderBy(x => x.EmpID).ToList(); else employees = employees.OrderBy(x => x.Name).ToList(); ``` But if you need to do this SQL side for whatever reason, I would su...
Conditional Order By In Stored Procedure
[ "", "sql", "sql-server", "t-sql", "stored-procedures", "sql-server-2008-r2", "" ]